Sort Characters By Frequency Java For context, I worked on the LeetCode May 2020 Challenge Week 3 Day 1. The challenge was described as this:

  Given a string, sort it in decreasing order based on the frequency of
  characters.

  Example 1:

  Input: "tree"

  Output: "eert"

  Explanation: 'e' appears twice while 'r' and 't' both appear once. So
  'e' must appear before both 'r' and 't'. Therefore "eetr" is also a
  valid answer.

  Example 2:

  Input: "cccaaa"

  Output: "cccaaa"

  Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also
  a valid answer. Note that "cacaca" is incorrect, as the same
  characters must be together.

  Example 3:

  Input: "Aabb"

  Output: "bbAa"

  Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
  Note that 'A' and 'a' are treated as two different characters.

Anyways, I looked up some popular solutions. One was to get the frequency of each character and sort, and the other was the use a heap. I liked both of these solutions, but I wanted to make one where there was no sorting.

My solution involved an idea of an ArrayList of "tiers," where the index of the tier represents the frequency. Each tier consists of an ArrayList containing the characters which the corresponding frequency. As letters increase in frequency, the higher frequency tier they move up. I also used a HashMap to keep track of which frequency tier each character was in. Upon finishing iterating through the whole string, I simply use a StringBuilder to append the letters starting at the bottom tier, reverse the StringBuilder, then return the String. I was hoping someone could give me pointers (ha, code pun) on optimizing/modifying this approach without including any kind of sorting. Below is the functional code:

public static String frequencySort(String s) {
        if (s.length() <= 1) return s;

        ArrayList<ArrayList<Character>> tieredFreq = new ArrayList<>(); // stores characters at their proper frequency "tier"
        HashMap<Character, Integer> tierOfChars = new HashMap<>(); // maps the characters to their current frequency tier
        tieredFreq.add(null); // tier 0

        for (char c : s.toCharArray()) {
            tierOfChars.put(c, tierOfChars.getOrDefault(c, 0) + 1); // add char or increment the tier of the character
            int i = tierOfChars.get(c); // i = tier of the character
            if (tieredFreq.size() <= i) tieredFreq.add(new ArrayList<>()); // if not enough tiers, add a new tier
            if (i > 1) tieredFreq.get(i - 1).remove(new Character(c)); // if c exists in previous tier, remove it
            tieredFreq.get(i).add(c); // add to new tier
        }

        StringBuilder result = new StringBuilder();
        for (int i = 1; i < tieredFreq.size(); i++) { // iterate through tiers
            ArrayList<Character> tier = tieredFreq.get(i); // get tier
            for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier
                for (int j = 0; j < i; j++) result.append(c);
            }
        }

        result.reverse(); // reverse, since result is currently in ascending order
        return result.toString();
    }

You have conceived a theoretical model that works. And avoids sorting.

Tiers by frequency
Every tier contains letters of that frequency

It will come at no surprise, that moving a char from on frequency's bin to the next frequency's bin will cost at least as much as sorting. But it is a nice mechanism
one sees too rare, and might have its application in vector operations, GPUs or whatever.

Improved could be the names. "Tier" one inclines to love, and might be apt, but does the term help in understanding the code?
Use if possible more general interfaces implemented by specific classes, like List<T> list = new ArrayList<>();. This is more flexible, when passing to methods, reimplementing with another class.
The comment to remain is for adding null for the frequency 0.
For characters in a tier use a Set. As implementation I used a TreeSet which is sorted to give nicer output.
Use as index not i but rather freq.
Moving from one frequency to the next higher can be done in two separate steps old+new. That makes the code more readable.

so:

public static String frequencySort(String s) {
    if (s.length() <= 1) return s;

    List<Set<Character>> charsByFrequency = new ArrayList<>(); // stores characters at their proper frequency "tier"
    Map<Character, Integer> frequencyMap = new HashMap<>(); // maps the characters to their current frequency tier
    charsByFrequency.add(null); // entry for frequency 0 is not used

    for (char c : s.toCharArray()) {
        Character ch = c; // Does ch = Character.valueOf(c);
        int oldFreq = frequencyMap.getOrDefault(c, 0);
        if (oldFreq != 0) {
            charsByFrequency.get(oldFreq).remove(ch);
        }
        int freq = oldFreq + 1;
        if (freq >= charsByFrequency.size()) {
            charsByFrequency.add(new TreeSet());
        }
        charsByFrequency.get(freq).add(ch);
        frequencyMap.put(ch, freq);
    }

    StringBuilder result = new StringBuilder();
    for (int i = 1; i < charsByFrequency.size(); i++) { // iterate through tiers
        Set<Character> tier = charsByFrequency.get(i); // get tier
        for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier
            for (int j = 0; j < i; j++) result.append(c);
        }
    }

    result.reverse(); // reverse, since result is currently in ascending order
    return result.toString();
}


Triangle style output, incrementing max line length The output that I want:

  1
  2 3
  4 5 6
  7 8 9 10
  11 12 13 14 15
  16 17 18 19 20 21
  22 23 24 25 26 27 28

        <?php
        $i;
        $a = 1;
        $b = 0;

        for($i = 1; $i < 29; $i++){
          echo $i;

          if ($i == $a){
            echo "

";

            $a = $i + 2 + $b;
            $b++;
          }
       }
       ?>

Is it possible to get rid of $b and make it simpler ?

The output of your program is not as you are saying. This is the real output:

1
23
456
78910
1112131415
161718192021
22232425262728

To get your desired output, you can change this:
echo $i;

To:
echo $i." ";

This will append the extra space after each iteration.

$a
a is a poor variable name. You could make your code much clearer if you gave it a meaningful name, like $countOfNumbersToDisplay. Sure, it's a lot longer to type, but it indicates your intention much more clearly than $a.
Same goes for $b.

Avoid magic numbers
This is not very easy to understand:
      if ($i == $a){
        echo "</li><li>";

        $a = $i + 2 + $b;
        $b++;
      }

Why + 2? This really could use some clarification. I suggest to make 2 a constant with a meaningful name earlier in your code.


Fetch and append player statistics to an Excel spreadsheet I am a new programmer in python, and I need a bit of help to structure my code.

game_schedule = (
    ('Daily Game Schedule', 'daily_game_schedule'),
    ('Full Game Schedule', 'full_game_schedule'),
)

team_standings = (
    ('Overall Team Standings', 'overall_team_standings'),
    ('Playoff Team Standings', 'playoff_team_standings'),
)

worksheets = (
    ('Game Schedule', game_schedule),
    ('Cumulative Player Stats', 'cumulative_player_stats'),
    ('Player Injuries', 'player_injuries'),
    ('Team Standings', team_standings),
)

def create_and_update_worksheets():
    """
    Add 'Player statistics' if the worksheet is not in file_name.
    Otherwise, it will update the worksheet itself.
    """

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    writer = pd.ExcelWriter(file_name, engine='openpyxl')

    for key, value in worksheets:
        start_row = 0
        if isinstance(value, tuple):
            for subkey, subvalue in value:
                response = send_request('2017-2018-regular', subvalue).content
                df1 = pd.DataFrame(['Title'])
                df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

                df1.to_excel(writer, key, startrow=start_row, header=None, \
                             index=False)
                df2.to_excel(writer, key, startrow=start_row+2, index=False)
                start_row += len(df2) + 4
        else:
            response = send_request('2017-2018-regular', value).content
            df1 = pd.DataFrame(['Title'])
            df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

            df1.to_excel(writer, key, startrow=start_row, header=None, \
                         index=False)
            df2.to_excel(writer, key, startrow=start_row+2, index=False)

    for sheet in writer.sheets.values():
        resize_columns(sheet)

    writer.save()
    writer.close()

create_and_update_worksheets()

I think there is repetitive code in the for loop for key, value in worksheets:. How can I change the structure so that it is not repetitive?

As we can see these piece of code is repeated:

response = send_request('2017-2018-regular', value).content
df1 = pd.DataFrame(['Title'])
df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
df2.to_excel(writer, key, startrow=start_row+2, index=False)

you can define a function for it, it works like this:

def create_and_update_worksheets():
    def less_repetitive(value, start_row):
        response = send_request('2017-2018-regular', value).content
        df1 = pd.DataFrame(['Title'])
        df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

        df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
        df2.to_excel(writer, key, startrow=start_row+2, index=False)
    ...
    for key, value in worksheets:
        ...
        if isinstance(value, tuple):
            for subkey, subvalue in value:
                less_repetitive(subvalue, start_row)
                start_row += len(df2) + 4
        else:
            less_repetitive(subvalue, start_row)
    ...

Another solution is change the value in worksheets to be all tuple, but I am not sure if it works. As you didn't use the subkey, in such situation those value is not tuple now, can be changed to (('', value))

and as you don't need use subkey just replace it with _
code works like this:

def create_and_update_worksheets():
    ...
    for key, value in worksheets:
        ...
        if not isinstance(value, tuple):
            value = (('',value))

        for _, subvalue in value:
            response = send_request('2017-2018-regular', subvalue).content
            df1 = pd.DataFrame(['Title'])
            df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

            df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
            df2.to_excel(writer, key, startrow=start_row+2, index=False)
            start_row += len(df2) + 4

    ...


Given n input strings and m query strings, find each query frequency in the list of input strings I'm doing questions on HackerRank to brush up on Java & CS.

Problem

This problem is called Sparse Arrays in HackerRank.

  There is a collection of input strings and a collection of query
  strings. For each query string, determine how many times it occurs in
  the list of input strings.

  For example, given input strings = ['ab', 'ab', 'bc'] and queries =
  ['ab', 'abc', 'bc'], result is [2, 1, 0]

  Full Question

Solution

static int[] matchingStrings(String[] strings, String[] queries) {
    Map<String, Integer> counter = new HashMap<>();
    for (String current: strings) {
        counter.put(current, counter.getOrDefault(current, 0) + 1);
    }

    int[] result = new int[queries.length];
    for (int i = 0; i < queries.length; i++) {
        result[i] = counter.getOrDefault(queries[i], 0);
    }
    return result;
}

This passes all the test cases.

Can I do it in a better way?
Can this be simplified in Java-8, 11 or later?

Can I do it in a better way?

From the time complexity or space complexity your solution is good enough. Your store all your string frequencies beforehand so that to retrieve a frequency by any given string in O(1) time later. Also, it passes all the test cases so it's a good sign too.

Below are a couple of concerns regarding other aspects of your code.

Variable Naming

Your choice of variable names should be improved. For instance, Map<String, Integer> counter doesn't really reflect for what it stands for. I would call it stringFrequencyMap or stringCountMap.

Also, result sounds too generic here. How about queryResults?

I'll leave it up to you to think about other variable names you have (luckily not many left :) ).

Static method

I guess you've kept this method static as it was like this by default and to avoid creating an instance of your Solution class in the main() method. While it's fine for a small challenge like yours, generally there should be a good reason to add static to your method.

Improvements

  Can this be simplified in Java-8, 11 or later?

Of course, if we just use JAVA 8 then we can take advantage of streams and write a solution as :

static long[] matchingStrings(String[] strings, String[] queries) {
    Map<String, Long> stringCountMap = Arrays.stream(strings).collect(Collectors.groupingBy(Function.identity(), counting()));

    return Arrays.stream(queries).mapToLong(query -> stringCountMap.getOrDefault(query, 0L)).toArray();
}

As you can see, we do this in 2 steps. First, we calculate a frequency map and then calculate an array of results using streams again. Please note that I changed the return type from int[] to long[].

UPDATE

Since there was a question why I've used Map<String, Long> rather than Map<String, Integer> - well, Long can hold bigger numbers. But since it's irrelevant for this problem here's a solution for Map<String, Integer>:

int[] matchingStrings(String[] strings, String[] queries) {
    Map<String, Integer> stringCountMap = Arrays.stream(strings).collect(Collectors.groupingBy(Function.identity(), summingInt(x -> 1)));

    return Arrays.stream(queries).mapToInt(query -> stringCountMap.getOrDefault(query, 0)).toArray();
}


Automation of entity reading in yesod I'm trying to automate entity reading in my yesod application.

This is what I have:

withEntity
  :: ( PersistEntity a
     , YesodPersistBackend site ~ PersistEntityBackend a
     , PersistStore (YesodPersistBackend site)
     , YesodPersist site )
  => String
  -> Key a
  -> (Entity a -> ExceptT Text (HandlerT site IO) b)
  -> ExceptT Text (HandlerT site IO) b
withEntity what key f =
  do mrec <- lift . runDB . get $ key
     case mrec of
       Nothing  -> throwError . pack $ "unknown " ++ what
       Just rec -> f (Entity key rec)

Users of my application may send a request for data in DB using integer ID instead of Key a. So I have a wrapper around withEntity:

withEntitySql
  :: ( PersistEntityBackend a ~ SqlBackend
     , ToBackendKey SqlBackend a )
  => String
  -> Int64
  -> (Entity a -> ExceptT Text (HandlerT App IO) b)
  -> ExceptT Text (HandlerT App IO) b
withEntitySql what key f = withEntity what (toSqlKey key) f

This way I can write functions specifying error messages when record doesn't exist:

withA
  :: Int64
  -> (Entity A -> ExceptT Text (HandlerT App IO) a)
  -> ExceptT Text (HandlerT App IO) a
withA =
  withEntitySql "A"

withB
  :: Int64
  -> (Entity B -> ExceptT Text (HandlerT App IO) a)
  -> ExceptT Text (HandlerT App IO) a
withB =
  withEntitySql "B"

I can combine this functions with each other:

withA aId $ \ ea ->
  withB bId $ \ eb -> do
    ...

On the top level in handler for route I wrap the result of runExceptT into json object so client can see if something went wrong with his request.

I don't like that I have to write a function for each entity I'm working with in order to specify error message. I'm not sure how to improve withEntity to determine error message by itself.

I would experiment with something like the following:

import Data.Typeable

withEntitySql
  :: ( PersistEntityBackend a ~ SqlBackend
     , ToBackendKey SqlBackend a
     , Typeable a )
  => Int64
  -> (Entity a -> ExceptT Text (HandlerT App IO) b)
  -> ExceptT Text (HandlerT App IO) b
withEntitySql key f = withEntity (show $ typeRep (Proxy :: Proxy a)) (toSqlKey key) f


List of dates with special formatting I have a code that calls many times a function returning a list of the dates between two dates formatted as

  ('0001-01-01 00:01:00'),('0001-01-02 00:01:00'), ...

The current solution is:

import numpy as np
import time
from datetime import datetime

beg = datetime.strptime('01 01 0001', '%d %M %Y') #datetime
end = datetime.strptime('01 01 2001', '%d %M %Y')

def get_days(date1, date2):
    day_diff = (date1 - date2).days + 1
    days = [str(start_date + dt.timedelta(d)) for d in range(day_diff)]
    dates = "('" + "'),('".join(days) + "')"
    return dates

Is there a faster way to achieve this?

 #timing
 t0 = time.time()

dates_list = get_days(beg, end) #feed datetime

t1 = time.time()
total_create = t1-t0
print("list comprehension: ", total_create,'s')

With the list comprehension you are filling a whole list with your values, and then you are sending that list to join.

Instead of a generating a list and then sending it, you can send a generator instead: similar to the list comprehension, but generates the values on-demand. With your old approach, if you had 10000 dates you would have them all at a list; with a generator it generates one at a time, so at least you will be consuming less memory.

With a generator, you would directly do:

dates = "('" + "'),('".join(str(start_date + dt.timedelta(d)) for d in range(day_diff)) + "')"

On a side note, the parameter names date1, date2 are not very explicit; it should be clear from the names which is the start and which is the end date.


Iterating and fetching values from dictionary Here is my dictionary:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"finance": "10.54%"}}

I want extract, first key value of 1 i.e. time, length of the dictionary may vary.

My code:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
flag = 0
result = []
result1 = ''
result2 = ''
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result1 = k1
        result.append(result1)
        print 'result = ', result1
        flag = 1
        if flag == 1:
            break
    if flag == 1:
        break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result2 = k1
        result.append(result2)
        print 'result = ', result2
        flag = 1
        if flag == 1:
            break
    if flag == 1:
        break
print 'REsult is : , ', result

What is the standard way to do this, rather then using flag?

After that I want to extract time and money from each result and pack them into list like ['time','money'], but due to flag I have used here, I was not able to do this.

In your code you write

    flag = 1
    if flag == 1:
        break

The if will always be True, so this is just

    flag = 1
    break

You only use flag for another if that also will always be True, so make this

    break
break

Simplifying this to

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
result1 = ''
result2 = ''
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result1 = k1
        result.append(result1)
        print 'result = ', result1
        break
    break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result2 = k1
        result.append(result2)
        print 'result = ', result2
        break
    break
print 'REsult is : , ', result

Removing the inner prints gives

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result.append(k1)
        break
    break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result.append(k1)
        break
    break
print 'REsult is : , ', result

This can be simplified by using itervalues and not calling iteritems on the inner loop:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
for v in c_result1.itervalues():
    for k in v:
        result.append(k)
        break
    break
for v in c_result2.itervalues():
    for k in v:
        result.append(k)
        break
    break
print 'REsult is : , ', result

This is actually just the same as calling next twice:

help(next)
#>>> Help on built-in function next in module builtins:
#>>>
#>>> next(...)
#>>>     next(iterator[, default])
#>>>
#>>>     Return the next item from the iterator. If default is given and the iterator
#>>>     is exhausted, it is returned instead of raising StopIteration.
#>>>

However this is only simpler if you know it's going to succeed:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []

inner = next(c_result1.itervalues())
result.append(next(iter(inner)))

inner = next(c_result1.itervalues())
result.append(next(iter(inner)))

print 'REsult is : , ', result

Either way, one should make a function or use a loop to avoid repeating oneself:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []

for c_result in (c_result1, c_result2):
    for v in c_result.itervalues():
        for k in v:
            result.append(k)
            break
        break

print 'REsult is : , ', result


SQLite DB Check and Update Script My script looks for handshake files in an input folder to determine whether certain processes have completed.  If it finds them, it will update the database with the current time stamp.

Things I am wondering:

My update_db function takes 5 parameters.  I have heard that in that case there is probably a better way to do it.  Would this be a good candidate for creating a class and using an OO approach?
I am eventually going to be using a datetime to compare against the handshake timestamps, would it be difficult to somehow pull the file dates off our Linux server instead of creating them in the script?
Finally, any inconsistencies, ways I can simplify/improve my code.  I am a new programmer of only 6 months, and love to learn:)

Here's the code:

def main():

    # Get current time stamp
    now = datetime.now()
    formatted_dt = '{0}/{1}/{2}-{3}:{4}:{5}'.format(now.month,
                                                    now.day,
                                                    now.year,
                                                    now.hour,
                                                    now.minute,
                                                    now.second)
    # Connect to db
    sqlite_file = '/bcs/lgnt/clientapp/csvbill/database/csv.db'
    csv_connection = sqlite3.connect(sqlite_file)
    c = csv_connection.cursor()

    file_type = ['auditv2', 'handshake']

    # Check for files that don't have first hshake
    c.execute('SELECT pivot_id FROM aud_qty WHERE hshake1 is NULL')
    piv_id_list = [str(x[0]) for x in c.fetchall()]
    missing_list = update_db('CSV1000', file_type[0], piv_id_list, c, formatted_dt)
    # hshake1_miss = check_hshake('CSV1000', file_type[0], piv_id_list)
    # print(hshake1_miss)
    csv_connection.commit()
    csv_connection.close()

def update_db(proj_id, audit_type, piv_id_list, db_cursor, time_stamp):

    # chdir('/prod/bcs/lgnp/input')
    # prod_list = listdir('/prod/bcs/lgnp/input/')
    # for testing
    chdir('/bcs/lgnt/input')
    prod_list = listdir('/bcs/lgnt/input/')
    hshake_list = []

    for i, e in enumerate(prod_list):
        prod_list[i] = prod_list[i].split('_') # Field 6 is auditv2, Field 7 is the Pivot ID
    # Get only the Pivot ID
    for i, e in enumerate(prod_list):
        try:
            if prod_list[i][0] == proj_id and prod_list[i][6] == audit_type:
                hshake_list.append(prod_list[i][7])
        except IndexError:
                pass
    # pdb.set_trace()
    for i, e in enumerate(hshake_list):
        if hshake_list[i] in piv_id_list:
            print(hshake_list[i])
            # pdb.set_trace()
            db_cursor.execute('UPDATE aud_qty SET hshake1 = ? WHERE pivot_id = ?',
                             (time_stamp, hshake_list[i]))
            piv_id_list.remove(hshake_list[i])
    print(piv_id_list)
    return piv_id_list

Working with resources

Whenever possible,
anything that must be closed after using,
in this example the database connection,
it's good to wrap it in a with ... as, like this:

with sqlite3.connect(sqlite_file) as conn:
    cursor = conn.cursor()
    # ...

This way, conn will be automatically closed when exiting the block,
so it's impossible to forget to close it, therefore more robust.

Using enumerate

enumarate is really handy, but you're not using it to its full potential:

for i, e in enumerate(prod_list):
    prod_list[i] = prod_list[i].split('_')

Do you see the unused variable e? Since you have it, why not use it:

for index, item in enumerate(prod_list):
    prod_list[index] = item.split('_')

Naming

The posted code is filled with poor names, for example:

the main function
the c cursor variable -> cursor
the i loop variable for index -> index
the e loop variable for an element -> item

At the minimum, try to avoid single-letter names.

mm/dd/yyyy format

If at all possible, I'd recommend to use any other date format.

Comprehensive map of all countries in the world that use the MMDDYYYY format:


Filter functionality Project using C# I am simply implementing a filter function for one my forms. I'd like to hear some reviews where I can improve in my code or my functionality  :)
Summary
I have 1 textbox and 2 comboboxes (See image below):

Category options

Status options

Code
public MainView()
{
    InitializeComponent();
    categoryText.SelectedIndex = 0;
    statusText.SelectedIndex = 0;

    RefreshData();
}

List<ConcessionModel> concessionList = new List<ConcessionModel>();
public void RefreshData()
{
    DataAccess db = new DataAccess();
    concessionList = db.LoadConcessionLog();
    dataGrid.DataSource = concessionList;

    dataGrid.Columns["Id"].Visible = false;
    dataGrid.Columns["PersonCompletingID"].Visible = false;
}

private void searchBtn_Click(object sender, EventArgs e)
{
    dataGrid.DataSource = Filter(productText.Text, categoryText.Text, statusText.Text);
}

private List<ConcessionModel> Filter(string product, string category, string status)
{
    if (category == "All" && status != "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
                .IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
    else if (category != "All" && status == "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
                .IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
    else if(category == "All" && status == "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList();
    }
    else
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
                .IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
                .IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
}

public void ClearConcessionFilter()
{
    productText.Clear();
    categoryText.SelectedIndex = 0;
    statusText.SelectedIndex = 0;
    dataGrid.DataSource = concessionList;
}

ConcessionModel
public class ConcessionModel
{
    public int Id { get; set; }

    [DisplayName("Date Created")]
    public DateTime DateCreated { get; set; }

    public int PersonCompletingID { get; set; }
    public string Product { get; set; }

    [DisplayName("Batch Number")]
    public string BatchNumber { get; set; }

    [DisplayName("Quantity Affected")]
    public string QuantityAffected { get; set; }

    [DisplayName("Reason For Concession")]
    public string ReasonForConcession { get; set; }

    public string Category { get; set; }
    public string Status { get; set; }
}

Let me focus on the Filter method.

There are a lot of repetitions in that method, which makes your code

harder to maintain

for example: replacing IndexOf to Equals
or by changing the StringComparison option to another

and more error-prone

for example: it is easy to misspell the All at one of the occurrences.

There are a couple of useful techniques that can make your code less error-prone and easier to change:

Using constants, like: const string all = "All";
Using single return, like: return concessionList.Where(predicate).ToList();
Extracting common logic, like:

static bool IsPresent(string source, string target)
   => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;

Using default values instead of fallback,

like: predicate can have default value instead of relying on a
final else block.

With these in our hand the Filter method could be rewritten like this:
private List<ConcessionModel> Filter(string product, string category, string status)
{
    const string all = "All";

    static bool IsPresent(string source, string target)
        => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;

    Func<ConcessionModel, bool> predicate = model =>
        IsPresent(model.Product, product) &&
        IsPresent(model.Category, category) &&
        IsPresent(model.Status, status);

    if (category == all && status != all)
    {
        predicate = model =>
            IsPresent(model.Product, product) &&
            IsPresent(model.Status, status);
    }
    else if (category != all && status == all)
    {
        predicate = model =>
            IsPresent(model.Product, product) &&
            IsPresent(model.Category, category);
    }
    else if (category == all && status == all)
    {
        predicate = model =>
            IsPresent(model.Product, product);
    }

    return concessionList.Where(predicate).ToList();
}

predicate: I've defined a function variable (Func<TInput, TOutput>)

It receives a ConcessionModel (as TInput)
and will return with a bool (as TOutput).

So, I have defined a function which implementation varies based on the input parameters.
We use this function as a filter condition (Where) against the data source (concessionList)

Here I have used the short form, but could be written like this:

return concessionList.Where(model => predicate(model)).ToList();


Leetcode Longest Common Prefix I just recently finished the following problem on Leetcode problem. I know it's not the cleanest or fastest solution. I would appreciate if I can get some feedback on how to optimize the code.

The idea is too add all possible prefixes into an array and return the longest possible prefix. I believe this is probably why the algorithm doesn't run as fast as it should.

Also, I would appreciate if someone can assist in determining what the space and time complexity would be for the algorithm below?

var longestCommonPrefix = function(strs) {
const firstWord = strs[0];
const arrResults = [];
let index = 1;
let arrWithoutFirstElement = strs.slice(1, strs.length);
if(strs.length===0)return '';
if(strs.length===1)return strs[0];

while(index <= firstWord.length) {
   if(arrWithoutFirstElement.every(element =>
       element.substring(0,index)===firstWord.substring(0,index))){
       arrResults.push(firstWord.substring(0,index));
   }
   index++;
}

return arrResults.length > 0  ? arrResults[arrResults.length-1] : '';
}

console.log(longestCommonPrefix(["flower","flow","flight"]));

Fast strings in Javascript
It is important to note that something as simple as assigning a string to a variable will cost the length of the string in complexity a = "12345" will cost 5 characters. Assign to another variable and the cost is the same b = a will cost 5.
Every time you assign a string you need to count the length of that string. If you copy an array of strings then you move all the characters, not just the number of strings in the array.
You do a lot of string assignments in your code.
Avoid string assignment
The trick to handling strings is to avoid assigning strings if you can. Arrays and string array character referencing (eg a = "abcdef"; b = a[1])  lets you treat the JS string like a C (char *) string. You dont copy the string, you are just indexing into the string.
The only time any sequence of characters are copied is on the return. The performance increase is very significant.
const longestCommonPrefix = words => {
    var i, pos = 0, len = words.length;
    const char = words[0][pos];
    var min = words[0].length;
    for (i = 1; i < len; i++) { // finds the min word length and check first char
        min = words[i].length < min ? words[i].length : min;
        if (char !== words[i][pos] || pos === min) { return "" }
    }
    pos ++;
    while (pos < min) {  // check up to min word length.
        const char = words[0][pos];
        for (i = 1; i <len; i++) {
            if (char !== words[i][pos]) { return words[0].substring(0,pos) }
        }
        pos ++;
    }
    return words[0].substring(0,pos);
}


Generating primes with Sieve of Eratosthenes There are many problems on the Internet that require you to find prime numbers, so I decided to write a set of functions to find them. I used the Sieve of Eratosthenes for generating the primes as it was fast and easy to implement compared to other algorithms.

However, I'm wondering if my code, rather than my method, is inefficient. Am I using STL containers/iterators correctly? Is there any section in my code slowing down the program?

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

#define initial_prime_barrier 100
bool isFlagged(int i) { return i == 0; }
bool isNextStart(int i) { return i != 0; }

vector<int> generatePrimesBelow(int limit)
{
   vector<int> primes;
   for (int i = 2; i < limit; i++)
   {
      primes.push_back(i);
   }
   vector<int>::iterator currentStart = primes.begin();
   do
   {
      int numberAtStart = *currentStart;
      vector<int>::iterator currentNumber = currentStart + numberAtStart;
      do
      {
         *currentNumber = 0;
         advance(currentNumber, numberAtStart);
      } while (currentNumber < primes.end());
      currentStart = find_if(currentStart + 1, primes.end(), isNextStart);
   } while ((*currentStart) * (*currentStart) < limit);
   vector<int>::iterator newEnd = remove_if(primes.begin(), primes.end(), isFlagged);
   primes.erase(newEnd, primes.end());
   return primes;
}

bool isPrime(int number)
{
   static vector<int> primes = generatePrimesBelow(initial_prime_barrier);
   static int numPrimes = primes.size();
   static int largestPrime = primes[numPrimes-1];
   static int halfwayPrime = primes[numPrimes/2];
   if (number == largestPrime)
   {
      return true;
   }
   else if (number < largestPrime)
   {
      if (number == halfwayPrime)
      {
         return true;
      }
      else if (number > halfwayPrime)
      {
         for (int i = numPrimes/2; i < numPrimes; i++)
         {
            if (number == primes[i])
            {
               return true;
            }
         }
      }
      else if (number < halfwayPrime)
      {
         for (int i = numPrimes/2; i >= 0; i--)
         {
            if (number == primes[i])
            {
               return true;
            }
         }
      }
   }
   else if (number > largestPrime)
   {
      primes = generatePrimesBelow(number + number);
      numPrimes = primes.size();
      largestPrime = primes[numPrimes-1];
      halfwayPrime = primes[numPrimes/2];
      return isPrime(number);
   }
   return false;
}

int main (int argc, char * const argv[])
{
   const int number = 123123;
   cout << (isPrime(number) ? "YES" : "NO") << endl;
}

I take it you are really hell bent to use STL for everything but maybe you are over using it. However your code as it is, is very redundant. The specific issue I found are:

Whenever you call isPrime(), you are generating the primes array inside generatePrimesBelow() from scratch. Its not a problem now, but if you call isPrime() from main inside a loop for a couple of numbers, it will be very inefficient.
Since you are using only one vector<int> for storing both the primes and the sieve, you are using find_if(), remove_if() and erase() which would not be needed if you use 2 vectors for storing the primes and the sieve separately, and hence make the code more efficient.
In isPrime(), you can simply use the find() function from STL to look whether your number is in primes or not. You don't need to write your own look-up code. Better yet, since the primes is sorted, you can directly use binary_search() STL algorithm on it. But all of this is moot as should search for a number to be prime or not if you have already found whether it is prime or not using generatePrimesBelow().

As per my understanding you can do everything in your isPrime() function itself, including what you are doing in generatePrimesBelow() in lesser lines of code that what your current isPrime() looks like. Here is what you can do:

Have two vectors<int>, primes and eratosthSieve with eratosthSieve's size being the number - 1 where number was passed in as argument.
Use STL generate algorithm to populate eratosthSieve from 2 to number, by having a function passed in as the generating function. It would like like this:

int fillUp() {
    static int i = 1;
    return ++i;
}

and will be used as generate( eratosthSieve.begin(), eratosthSieve.end(), fillUp)
Your sieve logic would become something like this with the two vectors:

vector<int>::iterator currentStart = eratosthSieve.begin();
vector<int>::iterator currentNumber;
do
{
    int numberAtStart = *currentStart;
    if ( numberAtStart != 0 )                 // If the number is 0, it means has been filtered out in the sieve.
    {
        primes.push_back( numberAtStart);
        currentNumber = currentStart + numberAtStart;
        do
        {
            *currentNumber = 0;
            advance(currentNumber, numberAtStart);
        } while (currentNumber < eratosthSieve.end());
    }
    currentStart = find_if(currentStart + 1, eratosthSieve.end(), isNextStart);
} while (currentNumber < eratosthSieve.end());

Check if the last element of the primes vector is equal to number or not:
    return ( number == primes.back() );


Pattern-matching function I am new to Scala and I have written a function which uses pattern matching to filter words based on some conditions.  It seems to work correctly but I am suspect that I haven't used the Scala pattern matching in the best way.  I think this because each of my cases contain an if statement.  I have not seen any examples where people use if statements in pattern matching functions so I'm thinking there might be a better way of doing this.  Or maybe this particular usage does not fit well with pattern matching.

def getImportance(token:String,stopWords:Set[String])={
    token match{
      case t if t.length()==1 => 0
      case t if t.length()>15 => 0
      case t if t.matches("\\p{Punct}+") => 0
      case t if stopWords.contains(t.toLowerCase()) => 0
      case _ => 1
    }
}

I don't think that using pattern matching is necessary in this case, you only have a few simple conditions that can be better represented with a simple if. See what you think about this solution:

def getImportance(token: String, stopWords: Set[String]) =
  if (token.length() == 1 || token.length() > 15 ||
    token.matches("\\p{Punct}+") ||
    stopWords.contains(token.toLowerCase()))
      0
  else
      1

I believe it is simpler and easier to read. I think using patter matching for these simple cases only hinders the understanding of the code ;)


Checking unique words and their abbreviations In an attempt to solve a problem on Leetcode, I used dictionary and sets to have O(1) time complexity.
However, my speed is too slow, better than just the 5% of Python submissions.
Here is my code:

from typing import List

class ValidWordAbbr:

    def __init__(self, dictionary: List[str]):
        self.dictionary = dictionary
        self.dictionary_abbn = {}
        self.abbn_set = set()
        for key in self.dictionary:
            if len(key) <= 2:
                self.dictionary_abbn[key] = key
                continue
            abbn = '{}{}{}'.format(key[0], len(key)-2, key[-1])
            self.dictionary_abbn[key] = abbn
            self.abbn_set.add(abbn)

    def isUnique(self, word: str) -> bool:
        abbn = word if len(word) <= 2 else '{}{}{}'.format(
            word[0], len(word)-2, word[-1])
        if abbn not in self.abbn_set:
            return True
        for key in self.dictionary_abbn.keys():
            if key != word and self.dictionary_abbn[key] == abbn:
                return False
        return True

How can I improve the runtime?

Variable names
I assume that your dictionary: List refers to an English dictionary and not a data-structure dictionary. This is confusing. Consider calling it something like words.
PEP8
isUnique should be is_unique if LeetCode lets you.
Formatting
'{}{}{}'.format is a quite slow method of concatenating three strings in this case. Try instead
''.join((
   key[0],
   str(len(key) - 2),
   key[-1],
))

This should also be factored out into a function since you use it twice.
Define slots
Read about how to do this here:
https://docs.python.org/3/reference/datamodel.html#object.__slots__


Map client application's DTO to service-proxy's DataContract My idea is to not not expose/use service's Proxy everywhere throughout the application, rather exercising all service communications(using client Proxy) from a single class. To achieve this I have created below class: -

namespace MyOrganization.EventSender
{
    using MyOrganization.EventSender.DTOs;
    using MyOrganization.EventSender.Proxy;
    using MyOrganization.EventSender.Utilities;
    using log4net;
    using Newtonsoft.Json;
    using System;
    using System.ServiceModel;
    using System.ServiceProcess;

    /// <summary>
    /// The User Session Detail Sender
    /// </summary>
    public class SessionDataSender : ISessionDataSender
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SessionDataDTO _sessionDataDTO;

        public SessionDataSender(SessionDataDTO sessionDataDTO)
        {
            _sessionDataDTO = sessionDataDTO;
        }

        public bool Send()
        {
            try
            {
                Proxy.MessageProcessorProxy.SessionDetails sd = new Proxy.MessageProcessorProxy.SessionDetails();
                sd.ChangeTime = _sessionDataDTO.ChangeTime;
                sd.ChangeType = _sessionDataDTO.ChangeType;
                sd.Username = _sessionDataDTO.Username;
                sd.SessionId = _sessionDataDTO.SessionId;

                log.Info($"Sending SessionEvent [{sd.ChangeType}] to Web-Srver.");

                var client = new Proxy.MessageProcessorProxy.MessageProcessorClient();
                var response = client.LogEventDetails(sd);

                Proxy.ProxyFactory.CloseProxy(client as ICommunicationObject);

                log.Info($"Web-Server Response: [{response.ResponseMessage}]. Reference: [ {JsonConvert.SerializeObject(sd)} ] ");

                return true;
            }
            catch (Exception ex)
            {
                log.Error($"Exception: [{ex.ToString()}]");

                return false;
            }
        }
    }
}

Now, my questions are: -

Is it good to map every DTOs into Proxy's DataContract? As my this class will grow with more service calls with different DTOs.
How this class should be architect so that it doesn't violate SRP/Design-patterns?

Is it good to map every DTOs into Proxy's DataContract? As my this
  class will grow with more service calls with different DTOs.

Yes, mapping to your own domain improves modularity by decoupling the DTO library from your domain.

  How this class should be architect so that it doesn't violate
  SRP/Design-patterns?

Use either a custom or existing mapping framework to remove the boiler-plate mapping code from your flow. You could create a Mapper class.
Consider using AOP for refactoring boiler-plate try-catch blocks. You could create a LogEntryExitAndErrorAnnotation class.
Your reponse object is not required
Use a using block to dispose the client
Don't use a boolean, when it is always true on success, and hidden when an exception occured.

adapted:

     [LogEntryExitAndErrorAnnotation]
     public void Send()
     {
          var sd = mapper.Map<Proxy.MessageProcessorProxy.SessionDetails>(_sessionDataDTO);

          // see notes below why to use an adapter
          using (var client = new MessageProcessorClientAdapter(
              new Proxy.MessageProcessorProxy.MessageProcessorClient()))
                  client.LogEventDetails(sd);
     }

Note on (4)

As the OP pointed out: Dispose could hide the root exception.

To avoid this, you can use an adapter. I would use T4 templates to generate these for all my clients.

Suppose your client interface is

public interface IMessageProcessorClient : IDisposable {
    void LogEventDetails(object data); // or typed class
}

You can use the code below to have the best possible exception details. If no error occured during the operation, the error of Dispose is thrown, else an aggregate error is thrown.

public class MessageProcessorClientAdapter : IMessageProcessorClient {
    public IMessageProcessorClient Source {get; private set;}
    public Exception Error {get;private set;}
    public MessageProcessorClientAdapter(IMessageProcessorClient source) {
        this.Source = source; // check for null
    }
    public void LogEventDetails(object data) {
        try {
            this.Source.LogEventDetails(data);
        } catch (Exception error) {
            this.Error = error;
        }
    }
    public void Dispose() {
        try {
            this.Source.Dispose();
        } catch (Exception error) {
            if (this.Error == null) {
                this.Error = error;
            } else {
                this.Error = new AggregateException(this.Error, error);
            }
        } finally {
            if (this.Error != null) {
                throw this.Error;
            }
        }
    }


Reading a file and storing all the data in a buffer I wrote a function to read the entire content of a file and return a pointer to an allocated bufer containing all the data.

Please could you tell me if there is a better way of doing this ? One solution could be to use stat() to pre-allocate a buffer and do only one read() call but I don't know if it's better, any though ?

#include <stdio.h>
#include <memory.h>

char *file_read(const char *path, size_t *file_size)
{
    FILE *file = fopen(path, "r");
    char buffer[FILE_READ_BUFFER_SIZE];
    char *tmp = NULL;
    char *data = NULL; // The buffer containing the data of the file
    char *data_cursor = NULL; // The current position in the data buffer
    size_t data_size = 0; // The size of the data buffer
    size_t n = 0; // The number of bytes read by fread()

    if (file == NULL)
        goto error;

    while ((n = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) {
        if (data == NULL) {
            data = malloc(sizeof(char) * n);
            data_cursor = data;
            data_size = n;
        } else {
            // We compute the position in the buffer as an integer
            // to be able to re-apply after realloc(). Because realloc()
            // can move the pointer we need this position as an integer.
            size_t cursor_pos = data_cursor - data;
            tmp = realloc(data, sizeof(char) * data_size + n);
            if (tmp == NULL)
                goto error;
            data = tmp;
            data_cursor = data + cursor_pos;
            data_size += n;
        }
        memcpy(data_cursor, buffer, n);
    }

    if (ferror(file))
        goto error;

    fclose(file);
    if (file_size != NULL)
        *file_size = data_size;
    return data;

    error:
    if (file != NULL)
        fclose(file);
    if (data != NULL)
        free(data);
    return NULL;
}

I recommend to pass a file pointer rather than a path. This will enable the code to work with streams as well. It would also simplify the awkward error handling.
Modern c allows, and recommends, to declare variables closer to their use.
It is OK to realloc even when data is NULL.
sizeof(char) is guaranteed to be 1.
Incrementing data_size after memcpy lets you drop data_cursor and cursor_pos, which IMHO obfuscate the code. You'd need to

    memcpy(data + data_size, buffer, n);
    data_size += n;

Allocating an array on the stack is usually not recommended. Consider reading directly into data + data_size, and get away without buffer and memcpy.


Parsing GTF file using command-line I am extracting exons details from a GTF file using command line in Unix like cut, awk, grep or sed.

input file.gtf:

chrI    ce11_ws245Genes CDS 8378308 8378427 0.000000    -   0   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes exon    8377602 8378427 0.000000    -   .   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes CDS 8379137 8379239 0.000000    -   1   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes exon    8379137 8379239 0.000000    -   .   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes CDS 8379706 8379815 0.000000    -   0   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes exon    8379706 8379815 0.000000    -   .   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes CDS 8380330 8380445 0.000000    -   2   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes exon    8380330 8380445 0.000000    -   .   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";
chrI    ce11_ws245Genes CDS 8388028 8388092 0.000000    -   1   gene_id "T19A6.1a.2"; transcript_id "T19A6.1a.2";

Desired output:

chrI 8377602 8378427 -  T19A6.1a.2
chrI 8379137 8379239 -  T19A6.1a.2
chrI 8379706 8379815 -  T19A6.1a.2
chrI 8380330 8380445 -  T19A6.1a.2

My successful attempts to solve the problem:

awk '/exon/ {print $1 " " $4 " " $5 " " $7 " " $10;}' file.gtf | awk '{sub(/gene_id/,"",$5)};1' | awk -F'"' '{print $1, $2}'

grep 'exon' file.gtf | cut -f1,4,5,7,9 | cut -d ';' -f1 | awk '{sub(/gene_id/,"",$5)};1' | awk -F'"' '{print $1, $2}'

steps:

search for lines which contain the word 'exon'
cut the fields of interest 1,4,5,7,9
in field 9: cut using the delimiter ';'
remove 'gene_id'
remove the double quotations around the genes' names

Your code can be simplified with only awk script:

awk '/exon/ {gsub("[\";]","", $10);print $1,$4,$5,$7,$10}' file.gtk

gusb removes any occurrence " or ; in the 10th element.


Simplify TcpListener application in C# I have a simple application that can receive and send tcp data.
right now there's a thread used to start the listener and within this thread there's another thread to receive.

it works but it seems like a waste of resources. Can the connect be simplified?

    public partial class Form1 : Form
    {
    private readonly TcpListener server = new TcpListener(IPAddress.Any, 1980);
    private NetworkStream sendStream;
    private NetworkStream recvStream;
    private TcpClient client;
    private byte[] datalength = new byte[4];

    public Form1()
    {
        InitializeComponent();
    }

    public void ServerReceive()
    {
        recvStream = client.GetStream();
        new Thread(() =>
        {
            while (recvStream.Read(datalength, 0, 4) != 0)
            {
                byte[] data = new byte[BitConverter.ToInt32(datalength, 0)];
                recvStream.Read(data, 0, data.Length);
                this.Invoke((MethodInvoker)delegate
                {
                    txtLog.Text += System.Environment.NewLine + "Client : " + Encoding.Default.GetString(data);
                });
            }
        }).Start();
    }

    public void ServerSend(string msg)
    {
        sendStream = client.GetStream();
        var data = Encoding.Default.GetBytes(msg);
        var length = data.Length;
        datalength = BitConverter.GetBytes(length);
        sendStream.Write(datalength, 0, 4);
        sendStream.Write(data, 0, data.Length);
    }

    private void btnListen_Click(object sender, EventArgs e)
    {
        Connect();
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        if (client.Connected)
        {
            ServerSend(txtSend.Text);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Connect();
    }

    private void Connect()
    {
        server.Start();
        MessageBox.Show("Waiting For Connection");
        new Thread(() =>
        {
            client = server.AcceptTcpClient();
            MessageBox.Show("Connected To Client");
            if (client.Connected)
            {
                ServerReceive();
            }
        }).Start();
    }
}

Various things about your code seem odd.

Field level values

There's no reason for these variables to be declared at a class level, you only ever use them within a single function:

private NetworkStream sendStream;
private NetworkStream recvStream;

btnSend_Click bug

If the user clicks on the send button, before they've clicked on the Listen button, your client member won't have been initialised so will throw an exception when you do:

if (client.Connected)

Listen/Read Thread

It looks like you're only expecting a single client (your listen thread doesn't contain a loop to accept more than a single connection).  Rather than spinning up another thread to perform the receive functionality, you might as well be doing it in the same thread that you performed the listen on.

Listen Management

Your listen code doesn't check the state of the Server before calling start.  If you click it twice, it seems likely that this is going to cause a problem.

Exception Handling

You don't have any exception handling around your read/write calls.  TCP can be a bit of a pain at times, depending upon how the connection has been shutdown it may throw various exceptions rather than just returning 0 from the read call.  It's also worth remembering that since you're accessing the socket from multiple threads it can change state between your is connected call and your write operation.


Multiple file creation with sorted input Is there a more efficient way to create the three files and write to those files using BufferedOutput and BufferedWiter I/O? The code works, but I thought there has to be a more compact way to accomplish this.

import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;

public class SortStudent
{

    public static void main(String[] args)
    {
       //variables for processing
        Path fileOut1 = Paths.get("Honors_Students.txt");
        Path fileOut2 = Paths.get("Good_Standing.txt");
        Path fileOut3 = Paths.get("Probation_Students.txt");
        String recOut;
        String delimiter = ",";
        Scanner input = new Scanner(System.in);
        final int QUIT = 999;

        //data class record
        Student student = new Student();

        //input.output may generate exceptions
       try
       {
            //Setup the 3 files to be used for output
            OutputStream output1 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut1, CREATE));
            OutputStream output2 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut2, CREATE));
            OutputStream output3 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut3, CREATE));
            BufferedWriter writer1 =
                   new BufferedWriter(new OutputStreamWriter(output1));
            BufferedWriter writer2 =
                   new BufferedWriter(new OutputStreamWriter(output2));
            BufferedWriter writer3 =
                   new BufferedWriter(new OutputStreamWriter(output3));

            BufferedWriter writer = null;

           //initial read for indefinite repetition
           System.out.print("Enter Student's ID number or 999 to quit: ");
           student.setID(input.nextInt());

           //sentinel controlled loop
           while (student.getID() != QUIT)
           {
                //get Student First Name
                System.out.print("Enter Student's First Name: ");
                student.setFirstName(input.next());

                //get Student Last Name
                System.out.print("Enter Student's Last Name: ");
                student.setLastName(input.next());

                //get Student GPA
                System.out.print("Enter Student's Grade Point Average: ");
                student.setgpa(input.nextDouble());

                //if gpa is 3.6 or> write to Honors Student
                if (student.Honors())
                    writer=writer1;

                //if gpa is >=2.0  and >3.5 write to Good Standing Student
                else if (student.Good_Standing())
                        writer=writer2;

                //if gpa is <2.0  write to Probation Student
                else if (student.Probation())
                        writer=writer3;

                //out of range
                else
                    continue;

                //build the record
                recOut = student.getID() + delimiter
                        + student.getFirstName() + delimiter
                        + student.getLastName() + delimiter
                        + student.getgpa();

                //write the record
                writer.write(recOut, 0, recOut.length());
                writer.newLine();

                //subsequent read for indefinite repetition
                System.out.print("Enter a Student's ID number or 999 to quit: ");
                student.setID(input.nextInt());

            }
            //close all files
            writer1.close();
            writer2.close();
            writer3.close();
        }
        catch(Exception e)
        {
            System.out.println("<<An exception has occurred.>> ");
            System.out.println(e.getMessage());
        }
    }
}

Formatting

Your if statement block should use braces { ... } to better identify the scope of each clause as a good practice. Also, you can consider renaming setgpa(double)/getgpa() to setGpa(double)/getGpa() respectively.

try-with-resources

Since Java 7, you should be using try-with-resouces for safe and efficient handling of your I/O resources:

private static final Path HONORS = Paths.get("Honors.txt");
private static final Path GOOD_STANDING = Paths.get("GoodStanding.txt");
private static final Path PROBATION = Paths.get("Probation.txt");
private static final String DELIMITER = ",";
private static final int QUIT = 999;

public static void main(String[] args) {
    try (PrintWriter honorsWriter = new PrintWriter(HONORS.toFile());
         PrintWriter goodStandingWriter = new PrintWriter(GOOD_STANDING.toFile());
         PrintWriter probationWriter = new PrintWriter(PROBATION.toFile());
         Scanner scanner = new Scanner(System.in)
    ) {
        // ...
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

I have taken the liberty to declare your file paths as private static final constants outside of the main() method, again as a good practice. Also, I have opted to use a PrintWriter, which is buffered, so that I can make use of its println(String) method.

Determining the student's details and ranking

You are creating only one Student instance, and then repopulating its details for each input. Ideally, you should be creating a new one each time, so that they can all go into a Collection in the future for further processing. Right now, you probably can settle for temporary variables in order to print them afterwards.

Assuming we are sticking with your approach, you can hide the Student creation within its own method, e.g. getStudent(Scanner). The idea is that given a Scanner instance, student details can be retrieved and a Student instance is returned:

Student student = getStudent(scanner);

Joining strings with delimiter

Since Java 8, you can use String.join(CharSequence, CharSequence) to easily join strings:

private static String toFileOutput(Student student) {
    return String.join(DELIMITER,
            Integer.toString(student.getID()),
            student.getFirstName(),
            student.getLastName(),
            student.getGpa());
}

Determining the file output

Instead of reassigning the writers to a writer, you should be using them directly:

Student student = getStudent(scanner);
while (student.getID() != QUIT) {
    String output = toFileOutput(student);
    if (student.isHonors()) {
        honorsWriter.println(output);
    } else if (student.isGoodStanding()) {
        goodStandingWriter.println(output);
    } else if (student.isProbation()) {
        probationWriter.println(output);
    }
    student = getStudent(scanner);
}

for vs while

Another way of looping through each Student input is to use a for loop, this approach is sometimes (often? always?) recommended to reduce the scope of the student instance:

for (Student student = getStudent(scanner);
     student.getID() != QUIT;
     student = getStudent(scanner)) {
    // ...
}

Shortening the process

Alternatively, you can consider Files.write(Path, Iterable, OpenOption) to expressively write (pun unintended) a line of output, the only thing to be aware of is that you will need to turn your single String into an Iterable, e.g. using Collections.singleton(T).

Putting it altogether:

public static void main() {
    try (Scanner scanner = new Scanner(System.in)) {
        for (Student student = getStudent(scanner);
             student.getID() != QUIT;
             student = getStudent(scanner)) {
            Set<String> output = Collections.singleton(toFileOutput(student));
            if (student.isHonors()) {
                Files.write(HONORS, output, APPEND);
            } else if (student.isGoodStanding()) {
                Files.write(GOOD_STANDING, output, APPEND);
            } else if (student.isProbation()) {
                Files.write(PROBATION, output, APPEND);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}


Fed Singleton struct class from plist I have a plist file which has URLs in it and struct class is feeding from this plist. This struct class has static variable which I use to reach URLs in every part of the app. My question is that I'm defining this static instance with "!". I can also define it with optional ("?"). I'm not sure If I'm declaring singleton variable in right way.

Note: If something happens with reading Plist or creating struct class, app needs to display a message or something then close. So reading successfully is mandatory.

    struct URLs: Codable {
    let urlBaseURL: String
    let urlCheckCMS: String
    let urlJSON: String

    static var instance: URLs!

    enum CodingKeys: String, CodingKey {
        case urlBaseURL = "base_url"
        case urlCheckCMS = "check_cms_url"
        case urlJSON = "table_json_url"
    }

}

// MARK: Convenience initializers

extension URLs {

    init?(data: Data) {
        guard let me = try? PropertyListDecoder().decode(URLs.self, from: data) else { return nil }
        self = me
        URLs.instance = me
    }

    init?(_ plist: String, using encoding: String.Encoding = .utf8) {
        guard let data = plist.data(using: encoding) else { return nil }
        self.init(data: data)
    }

    init?(fromURL url: String) {
        guard let url = URL(string: url) else { return nil }
        guard let data = try? Data(contentsOf: url) else { return nil }
        self.init(data: data)
    }

    var plistData: Data? {
        return try? PropertyListEncoder().encode(self)
    }

    var plist: String? {
        guard let data = self.plistData else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

If I try to declare singleton as usual way;

static let instance = URLs()

It gives below error;

  Cannot invoke initializer for type 'URLs' with no arguments

So I get rid of this error by writing a default init method in which I read plist file and write it to instance. However, I'm not sure with this.

Generally a singleton is declared as

    static let shared = URLs()

or for lazy instantiation

    static let shared = { URLs() }()

I would suggest naming the static property shared. That's a convention used throughout the standard library and Foundation.

In your case, if you change the value of instance, I'd use an optional. Your app init method (such as applicationDidFinishLaunching) should instantiate the instance of URLs with a guard and display the message if it fails.

If you are only setting the value once, I'd suggest something like

static var instance: URLs! { willSet {
    guard instance == nil else { fatalError("value has already been set") }
} }

I normally only use unwrapped optionals when working with an Objective-C based class where I can't overload the initializer (such as view controllers and XCTestCase). In those cases, you know viewDidLoad(), awakeFromNib(), or setUp() will be called (or something is seriously wrong and it isn't safe to continue execution).

Over the last year I've switched to using dependency injection instead of referencing singletons. I even use DI for things like NSNotificationCenter and NSUserDefaults. That makes unit testing a lot easier.


How bad is this jQuery? $($(this).parent().parent().parent().parent().parent().parent().children()[0]).html()

.parent().parent().parent().parent().parent().parent()

This can be much simplified by using parents() which returns an array, which you can just access with an index. I.e. you can replace the above with:

.parents()[5]

The upsides of this, besides being more concise, are that it the reader of your code can see which parent you're accessing without having to count the calls to parent and that if you ever need to access a different parent, you can just change the number instead of having to add or remove calls to parent.


Learning nested for loops in Python with Pig Latin translator I've been trying to learn Python for a bit now. I've taken a few courses, but I've found that I've been going about them wrong and had allowed them to "hold my hand" too much. I'm trying to build projects on my own and thought I would start off small. My third or so project was this Pig Latin translator and I wanted to get my head wrapped around nested for loops.

I know this code is super sloppy and I would love to have some feedback on how to make it more efficient or if there are any glaring mistakes I missed.

vowels = 'AaEeIiOoUuYy'
sentence = raw_input("Enter word to be translated: ")
pig_word = ""
# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()
pig_list = []

def pig_latin_trans():
    global pig_word, pig_list
    for item in sentence_list:
        count = 0
        for letter in vowels:
            if letter == item[0]:
                pig_word = str(item) + "way"
                pig_list.append(pig_word)
                break
            if letter != item[0] and count < len(vowels):
                count += 1
            if letter != item[0] and count == len(vowels):
                pig_word = str(item[1:]) + str(item[0]) + "ay"
                pig_list.append(pig_word)
    print " ".join(pig_list)

pig_latin_trans()

It's nice that you created a function.  Unfortunately, your function accepts no parameters and returns no values.  Rather, it refers to the global sentence_list as its input, and prints the output as a side-effect.  Worse, it uses global variables pig_word and pig_list, which should definitely have been local variables instead.  (Call this function a second time, and you'll have a mess!)

Your variable naming is poor, here:

# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()

… and here:

for item in sentence_list:

For clarity, those should be words = sentence.split() and for word in words:, respectively.  You could then drop the comment.

Since vowels is a constant, it should be named VOWELS instead.

The for letter in vowels loop is problematic.  You just want to see whether the first letter of the word is a vowel.  The way to do that should be

if word[0] in VOWELS:

Suggested solutions

VOWELS = 'AaEeIiOoUuYy'

def pig_latin_trans(sentence):
    pig_list = []
    for word in sentence.split():
        if word[0] in VOWELS:
            pig_list.append(word + "way")
        else:
            pig_list.append(word[1:] + word[0] + "ay")
    return " ".join(pig_list)

print(pig_latin_trans(raw_input("Enter words to be translated: ")))

The loop to build pig_list could be more elegantly expressed using a generator expression.

def pig_latin_trans(sentence):
    return " ".join(
        word + "way" if word[0] in VOWELS else
        word[1:] + word[0] + "ay"
        for word in sentence.split()
    )


Stack implementation using a singly linked list I've implemented a stack using a singly linked list and would like to know if there are any things I could improve on.

StackList.h:

#ifndef STACKLIST_H
#define STACKLIST_H

#include <iostream>

class Node
{
public:
    Node() : data(0), next(nullptr) {}
    Node(int theData, Node *newPtrToNext)
        : data(theData), next(newPtrToNext) {}
    Node* getNext() const { return next; }
    int getData() const { return data; }
    void setData(int theData) { data = theData; }
    void setNext(Node *newPtrToNext)
    {
        next = newPtrToNext;
    }
    ~Node() {}
private:
    int data;
    Node *next;
};

class StackList
{
public:
    //default constructor
    StackList();

    //copy constructor
    StackList(const StackList& otherStack);

    //overloaded assignment operator
    StackList& operator=(const StackList& otherStack);

    //destroyStack
    void destroyStack();

    //destructor
    ~StackList();

    //size
    int size() const;

    //push
    void push(int newVal);

    //pop
    void pop();

    //top
    int top() const;

    //empty
    bool empty() const;

private:
    Node * topOfStack;
    int count;
};

#endif

StackList.cpp:

#include "StackList.h"

//default constructor
StackList::StackList()
{
    topOfStack = nullptr;
    count = 0;
}

//copy constructor
StackList::StackList(const StackList& otherStack)
{
    Node* temp = otherStack.topOfStack;
    topOfStack = new Node(temp->getData(), nullptr);
    Node * prev = topOfStack;
    temp = temp->getNext();

    while (temp != nullptr)
    {
        Node * current = new Node(temp->getData(), nullptr);
        prev->setNext(current);
        prev = prev->getNext();
        temp = temp->getNext();
    }
    count = otherStack.count;
}

//overloaded assignment operator
StackList& StackList::operator=(const StackList& otherStack)
{
    if (&otherStack != this)
    {
        destroyStack();
        Node* temp = otherStack.topOfStack;
        topOfStack = new Node(temp->getData(), nullptr);
        Node * prev = topOfStack;
        temp = temp->getNext();

        while (temp != nullptr)
        {
            Node * current = new Node(temp->getData(), nullptr);
            prev->setNext(current);
            prev = prev->getNext();
            temp = temp->getNext();
        }
        count = otherStack.count;
    }
    else
        std::cerr << "Error. Attempted assignment to itself." << std::endl;

    return *this;
}

//destroyStack
void StackList::destroyStack()
{
    Node  *temp = topOfStack;

    while (topOfStack != nullptr)
    {
        topOfStack = topOfStack->getNext();
        delete temp;
        temp = topOfStack;
    }

    count = 0;
}

//destructor
StackList::~StackList()
{
    destroyStack();
}

//size
int StackList::size() const
{
    return count;
}

//push
void StackList::push(int newVal)
{
    topOfStack = new Node(newVal, topOfStack);
    count++;
}

//top
int StackList::top() const
{
    return topOfStack->getData();
}

//pop
void StackList::pop()
{
    if (topOfStack != nullptr)
    {
        Node * temp = topOfStack;
        topOfStack = topOfStack->getNext();
        delete temp;
        count--;
    }
    else
        std::cerr << "Stack is empty. No value to pop." << std::endl;
}

//empty
bool StackList::empty() const
{
    return count == 0;
}

This only works with int. Did you consider taking a template parameter so it can work with other types too?
Don't compare to nullptr. Instead use if (node) or if (!node).
You're very inconsistent with how you declare pointers. You have
Node* foo, Node * foo and Node *foo. Generally in C++ this is seen as part of the type so you should prefer the first variant.
You're using a member initialization list for Node but not for StackList. Why?
Prefer an early out when possible to avoid the build-up of arrow code.
Prefer prefix (++foo) over postfix (foo++) operator
Your comments add nothing to the code and can be removed.
Opinion based but you should not omit braces as it can lead to hard to find bugs.
The destructor can be implemented in terms of pop().
Node should be part of StackList as no one outside the class needs to access it. You could also simplify it by making it a struct and directly accessing the members.
You're violating the rule of three/five/zero by having a destructor/copy assignment operator but no move constructor or operator.
Your copy constructor does too much work. You can just iterate over the passed list and push(). Same for your assignment operator, look into the copy and swap idiom.


Getting all the master nodes in an elasticsearch cluster I am trying to get all the master nodes in an elasticsearch cluster using this code. Can I reduce/simply this or optimize further?

#!/usr/bin/env ruby
require 'elasticsearch'

client_node = ARGV[0]

client = Elasticsearch::Client.new host: client_node

clients = client.nodes.info process: true

clients['nodes'].each do |node|
        node_id = node[0]
        puts clients['nodes'][node_id]['host'] if clients['nodes'][node_id]['attributes']['master']== "true"
end

Fix your indentation. Ruby uses 2 spaces of indentation.
Your naming is confusing. You have client_node, client and clients, which are all very different things (string, object, hash as far as I can tell). The only one that's well-named is client since that is indeed an instance of Client. But client_node you can skip entirely since you can just as well write ARGV.first (which is more Rubyesque than [0]) in the one place you need it. Or you can call it host since that what it is. And clients could be called client_info or something similar. Name it for what it is.

Note: In the following I keep your names for simplicity's sake, but you should really reconsider the naming in your code.
You can iterate keys and values in loops:

clients['nodes'].each do |name, info|
  puts info['host'] if info['attributes']['master'] == "true"
end

Things will break if the info hash doesn't have an attributes key - your code is assuming it's there. A way to avoid this is to use Hash#fetch to absorb nil values:

puts info['host'] if info.fetch('attributes', {})['master'] == 'true'

Since all you want is the master node, it'd be more expressive to find that node first - if it exists - and then do what you want with it:

master_node = clients['nodes'].detect do |name, info|
  info.fetch('attributes', {})['master'] == 'true'
end

puts master_node['host'] if master_node

Beyond that, I feel confident the Elasticsearch library exposes a bunch of convenience methods you can use instead of accessing values with string keys. There may also be a way to fetch just the master node, instead of looping through stuff to find it. But I don't know the library, so it's just a guess.


Javascript progress bar in succession In the below code snippet, on click of a button, progress bars are added one by one. The bar shows up for 3 seconds. If you continuously click on the button, it will keep adding progress bars. The next bar will start after the previous bar finishes animating.

Is there anyway to make the code better?

;(function(window, document, undefined) {

    'use strict';

    var container = document.getElementsByClassName('container')[0];
    var button = document.getElementsByTagName('button')[0];
    var progressBar = document.getElementsByClassName("bar-container")[0];

    var promise = Promise.resolve();

    button.addEventListener('click', function() {
        var newProgressBar = progressBar.cloneNode(true);
        container.appendChild(newProgressBar);

        promise = promise.then(function() {
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                                      newProgressBar.classList.add('active');
                    setTimeout(function() {
                        resolve();
                    }, 3000);
                }, 0);
            });
        })
    });

})(window, document);

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <button id="button">click me</button>

emphasized text

Your code already looks pretty clean. Good work! There are only a few things I would recommend changing.

Don't define timings in CSS that should be defined in JavaScript. In this specific case using a transition made it possible to simplify the code significantly, however in a more involved example it would become problematic. What happens if one progress bar takes 2 seconds to complete, and another takes 5?
Instead of using getElementsByClassName('cls')[0], you can use querySelector('.cls') for more readable code. Though this can be slower, it really isn't an issue unless it is being run thousands of times per second.
There is a built in <progress> element that you may want to use.
It is a good idea to wrap template elements in a <template> element.

Here's a simple demo that defines the timing in the JavaScript.

function Loader(element, time) {
  return new Promise(resolve => {
    let intervalId;
    function tick() {
      element.value = parseInt(element.value, 10) + 1
      if (element.value == element.max) {
        clearInterval(intervalId)
        resolve()
      }
    }
    setInterval(tick, time / element.max)
  })
}

let promise = Promise.resolve()
let container = document.querySelector('.container')
let template = document.querySelector('template')

function addProgress() {
  let progress = document.importNode(template.content, true)
  container.appendChild(progress)
  // progress is a document fragment, not the template element
  return container.querySelector('progress:last-child')
}

document.querySelector('button').addEventListener('click', () => {
  let bar = addProgress()
  promise = promise.then(() => Loader(bar, 3000))
})
progress {
  display: block;
  width: 100%;
}
<template>
  <progress max="100" value="0"></progress>
</template>

<button>Click me!</button>


Archiving an SQL table of sessions and statistics What my query is doing:

I have two SQL tables and I want to copy datarows from the one table to the other table. I am doing this for statistics. The source table includes all current member-sessions/logins and with my statistics table I also want to see member-logins of the past. Thus I want to store these data into my bot_sessions_statistics table as well to make sure they are not being updated anymore:

The original query:

INSERT INTO bot_sessions_statistics (member_id, session_token, username, ip_address)
SELECT sessions.member_id, sessions.session_token, sessions.username, sessions.ip_address
FROM bot_sessions AS sessions
LEFT JOIN
(
    SELECT stats.member_id, stats.session_token, stats.username, stats.ip_address
    FROM bot_sessions_statistics as stats
    WHERE date_active >= date(NOW())
) AS stats
ON sessions.member_id = stats.member_id
WHERE latest_renewal >= date(NOW())
AND stats.member_id IS NULL

The performance of the original query:

Query_time: 86.364613  Lock_time: 0.000085 Rows_sent: 0  Rows_examined: 1088312551

The table structures:

Table bot_sessions:

Table bot_sessions_statistics:

The performance of single queries:

SELECT sessions.member_id, sessions.session_token, sessions.username, sessions.ip_address
FROM bot_sessions AS sessions
WHERE latest_renewal >= date(NOW())

Returns 44.2k rows (Duration: 0.078s / Fetch: 1.607s)

SELECT stats.member_id, stats.session_token, stats.username, stats.ip_address
FROM bot_sessions_statistics as stats
WHERE date_active >= date(NOW())

Returns 23.3k rows (Duration: 0.047s / Fetch 0.920s)

I have much more experience with SQL Server than with MySQL, but I think that some things very similar:

LEFT JOIN replacement - you are using only member_id from stats inner query. You could just have a direct LEFT JOIN with the bot_sessions_statistics table.
Cluster index candidate - bot_sessions_statistics.date_active looks like it is assigned one time with current time. As time always goes up, it should not create re-orderings. This is particularly useful when fetching multiple columns (index has all the columns) with conditions like >= date(NOW()) (faster seeks).
Possible use of partitioning - I have never used this in MySQL, but this functionality can provide increased performance when seeking data in very large tables. Partitioning by date columns might gain you some performance.
NOT EXISTS instead of LEFT JOIN / IS NULL - generally, it seems that LEFT JOIN with IS NULL is slower that NOT EXISTS.


Checking for intersection points The aim of the program is to find those points which comes under the intersection of at least 2 circles.(space is a 1000x1000 matrix)

n=input()
mat=[[0 for i in range(1005)] for i in range(1005)]
circles=[]

for i in range(n):
    circles.append(map(int,raw_input().split()))

ans=0
for circle in circles:
    minx=circle[0]-circle[2]
    maxx=circle[0]+circle[2]
    miny=circle[1]-circle[2]
    maxy=circle[1]+circle[2]
    for i in range(minx,maxx+1):
        for j in range(miny,maxy+1):
            if mat[i][j]<=1:
                if ((i-circle[0])**2+(j-circle[1])**2)<=(circle[2]**2):
                    mat[i][j]+=1
                    if mat[i][j]>1:
                        ans+=1
print ans

n denoted the number of circle circles contain circle center and radius in the format [x,y,r]. For example, let circles = [[3,2,4],[2,5,2]]. Then it contains two circles centered at (3,2) and (2,5) with radius 4 and 2 respectively.

Is the logic correct? Will it trigger any exceptions?

Bad things will happen if any part of any circle strays outside the 0-to-1005 bounds.  It's up to you to decide whether error handling for straying out of bounds is essential.

Mild rewrite

Representing each circle as a list is not quite appropriate.  Using indexes circle[0], circle[1], and circle.[2] to mean x, y, and r, respectively, is awkward.  As a remedy, I strongly recommend namedtuple.

from collections import namedtuple

Circle = namedtuple('Circle', ['x', 'y', 'r'])
n = int(raw_input())
circles = []
for i in range(n):
    circles.append(Circle(*map(int, raw_input().split())))

Initialization of a 1005 × 1005 grid is better written as:

mat = [[0] * 1005] * 1005

The rest of the program is straightforward.  You should avoid switching nomenclature from x, y to i, j.  To reduce nesting, you can eliminate one nested if by using and.

ans = 0
for circle in circles:
    minx, maxx = circle.x - circle.r, circle.x + circle.r
    miny, maxy = circle.y - circle.r, circle.y + circle.r
    for x in range(minx, maxx+1):
        for y in range(miny, maxy+1):
            if mat[x][y] <= 1 and (x-circle.x)**2 + (y-circle.y)**2 <= circle.r**2:
                mat[x][y] += 1
                if mat[x][y] == 2:
                    ans += 1
print ans

Going further

The nesting of for: for: for: if: if is still rather overwhelming.  I think it would be beneficial to split out some of that complexity.

class Circle (namedtuple('Circle', ['x', 'y', 'r'])):
    def contains(self, x, y):
        return (x - self.x)**2 + (y - self.y)**2 <= self.r**2

    def grid_points(self):
        for x in xrange(self.x - self.r, self.x + self.r + 1):
            for y in xrange(self.y - self.r, self.y + self.r + 1):
                if self.contains(x, y):
                    yield x, y

def read_ints():
    return map(int, raw_input().split())

n = int(raw_input())
circles = [Circle(*read_ints()) for _ in xrange(n)]

mat = [[0] * 1005] * 1005
ans = 0
for circle in circles:
    for x, y in circle.grid_points():
        mat[x][y] += 1
        if mat[x][y] == 2:
            ans += 1
print ans

The way I've written it, I've removed the optimization of skipping grid points that are already known to be in the intersection of previously analyzed circles.  I think it's probably a worthwhile tradeoff in favour of readability.


Struct inheritance in C++ I started learning programing with C++. It runs perfectly, but I wonder what things I can improve following the principles of class inheritance, access, overwriting, virtual functions and destructors, and why.
#include <iostream>  // allows program to output data to the screen
using namespace std;

struct Base {
    virtual void do_something() {};
    virtual ~Base(){};

};

struct Derived1 : public Base {
    Derived1():Base(){}
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
    virtual~Derived1(){};
};

struct Derived2 : public Base {
   Derived2():Base(){}
    virtual void do_something() {
        std::cout << "Derived2!!!" << std::endl;
    }
    virtual ~Derived2(){};
};

// function main begins program execution
int main(int argc, const char *argv[]) {
    std::cout << "Welcome" << std::endl;

    Derived1 derived1;
    derived1.do_something();

    Derived2 derived2;
    derived2.do_something();

    return 0;

}  // end function main

Don't add meaningless comments.
#include <iostream>  // allows program to output data to the screen

There is a real issue with code and comment rot. So your comments should always be meaningful as you have to maintain them with the code. It is best to reserve comments to "WHY" you are doing something. The code will explain "HOW".

Don't do this:
using namespace std;

There are definitely issues with pulling the whole standard namespace into the global namespace.
See: Why is “using namespace std;” considered bad practice?
In my opinion the best answer is the second one: sbi though the first one is good.

If Base does no real work you can make the virtual functions abstract:
struct Base {
    virtual void do_something() {};
    virtual ~Base(){};
};

// If the user should not be able to instantiate a `Base` then do this:

struct Base {
    virtual void do_something() = 0;
    virtual ~Base() {}
};

If your functions do not alter the standard behavior then don't include them:
struct Derived1 : public Base {
    Derived1():Base(){}
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
    virtual~Derived1(){};
};

Here the constructor and destructor are useless. Do not bother to specify them
struct Derived1 : public Base {
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
};

Don't use std::endl.
        std::cout << "Derived2!!!" << std::endl;

This is the major cause of C++ code running slowly. The problem is that std::endl forces the stream to flush. The stream will automatically flush when it is need and any extra flushes are likely to be inefficient (humans are bad at working out when to flush the stream).
It is better simply to use "\n"
        std::cout << "Derived2!!!" << "\n";

From C++11 we introduced the override specifier.
In the derived class you should mark any overridden methods with it.
struct Derived1 : public Base {
    virtual void do_something() override;
};

struct Derived2 : public Base {
    virtual void do_something() override;
};

The advantage here is that if in the future somebody changes the Base class and renames or alters the virtual functions in the base the compiler will not warn you that these functions no longer align with the base class version.


Validate that a relative path exists or is an external URI I sent a PR to a repo the other day and want to make sure I have the right idea for URI validation.

function validateURI(files) {
    //...
    // files can be either a string or an array of paths
    // validates the relative path exists or is an http(s) URI
    // returns a filtered list of valid paths
    // (e.g.) ["../dne.js", "//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"] => ["//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"]
    if(typeof files !== "object") files = [files]; //wrap string
    var local = grunt.file.expand(opt, files),
        remote = _.map(files, path.normalize).filter(function(path) { //for loading from cdn
            return /^((http|https):)?(\\|\/\/)/.test(path); //is http, https, or //
        });
    return _.uniq(local.concat(remote));
}

Very interesting,

I only have 1 snarky comment, if files is an array of 'paths', maybe you should call it paths ;)

Also, as a user of this function, I might want to override your regex so you might want to provide support for that.


Int-Enum to String and vice a versa in Swift I have a situation in my client-server app where I have to send my network strength to server and also receive other clients' strength from server.

So I created enum as:

enum NetworkType: Int {
    case none, gprs, two_g, three_g, four_g, lte, wifi
}
extension NetworkType: Comparable {
    public static func < (a: NetworkType, b: NetworkType) -> Bool {
        return a.rawValue < b.rawValue
    }
}

I can use this as:

if NetworkType.two_g < NetworkType.three_g {
    print("low network")
}

But for sending to server, I have to convert it to String and vice a versa.
So I added one more extension as:

extension NetworkType {

    static var networkDict: [String: NetworkType] = ["gprs": .gprs,
                                                     "2g": .two_g,
                                                     "3g": .three_g,
                                                     "4g": .four_g,
                                                     "lte": .lte,
                                                     "wifi": .wifi];
    init(rawString: String) {
        let loweredStr = rawString.lowercased()
        self = NetworkType.networkDict[loweredStr] ?? .none
    }

    func rawString() -> String? {
        return NetworkType.networkDict.allKeys(forValue: self).first
    }
}

//Dictionary extension for 'key for value'
extension Dictionary where Value: Equatable {
    func allKeys(forValue val: Value) -> [Key] {
        return self.filter { $1 == val }.map { $0.0 }
    }
}

let network = NetworkType(rawString: "gprs") //gprs, while receiving from server
let rawString = NetworkType.gprs.rawString() //"gprs", while sending to server

It is working fine, no issues.
Jus curious to know if theres any better way to achieve this.

Is the .none case really needed? It serves as a "fallback" in init(rawString: String)
if an unknown string is received from the network. But it is not listed in
the mapping dictionary, i.e. it can not be converted back to a string.

My suggestion is to remove that case, and use a failable initializer for the
conversion from a string:

init?(rawString: String) {
    let loweredStr = rawString.lowercased()
    guard let type = NetworkType.networkDict[loweredStr] else {
        return nil
    }
    self = type
}

Using a custom extension for the conversion to a string is not really necessary,
the same can be achieved directly with

func rawString() -> String? {
    return NetworkType.networkDict.first(where: { $1 == self }).map { $0.0 }
}

But the real question is: Why does this return an optional? It would return nil
if one of the enum cases is not covered in the dictionary. Let us assume that
you add another case five_g in the enumeration and forget to update the dictionary.
Now NetworkType.five_g.rawString() returns nil. What string do you send to the
server?

One possible approach would be to force-unwrap the string, so that this
programming error is detected early:

func rawString() -> String {
    return NetworkType.networkDict.first(where: { $1 == self }).map { $0.0 }!
}

But there is still a chance that the error remains undetected during development
and the deployed application crashes later.

A safer (and actually shorter and easier) approach is to define a string-based
enumeration, which implicitly defines the conversion to strings
and back:

enum NetworkType: String {
    case gprs
    case two_g = "2g"
    case three_g = "3g"
    case four_g = "4g"
    case lte
    case wifi
}

To make the comparison work, an ordinal number is associated with
each case:

extension NetworkType: Comparable {
    var ordinal: Int {
        switch self {
        case .gprs: return 1
        case .two_g: return 2
        case .three_g: return 3
        case .four_g: return 4
        case .lte: return 5
        case .wifi: return 6
        }
    }

    public static func < (a: NetworkType, b: NetworkType) -> Bool {
        return a.ordinal < b.ordinal
    }
}

Now the conversion is done using the built-in methods:

// String to NetworkType:
if let network = NetworkType(rawValue: "gprs") {
    // ..
} else {
    // unknown string from network
}

// NetworkType to String:
let rawString = NetworkType.gprs.rawValue

The conversion to a string cannot fail anymore. If another case is added, the compiler ensures that it is added to var ordinal as well.


Is my Node/Express-based authentication implementation with session properly done? I know that Passport.js exists, however, I wanted to code my own implementation using express-session module.

I'm using:

Express
Mongoose
express-session

So I basically have 2 routes for handling auth, POST /signup and POST /login.

This is what I've got, which I think is actually working but what I'm more concerned about is the session-handling.

var Account = require('../models/account');

app.route('/login')

    .post(function (request,response,next) {

        var email = request.body.email
        var password = request.body.password
        var login = new Account({"local.email":email,"local.password":password})

        Account.findOne({"local.email":email}, function (err,user) {

            if (err) {
                                response.send(500).end()
                                next();
            }

            if (!user) {
                                response.send(404).end();
                                next();
            }

            user.validPassword(password, function (err,matched) {

                if (err) {

                                response.status(500).end();
                                next();
                }

                if (matched) {

                                var session = request.session
                                session.name = email
                                response.redirect('/start')
                                next();
                }
                else {
                                response.redirect('/')
                                next();
                }
            })
        })
    })

    .delete(function (request,response) {

        request.session.destroy(function (err) {
            response.redirect('/')
        })
    })

app.route('/signup')

    .post(function (request,response) {

        var doc = new Account({"local.email":request.body.email,"local.password":request.body.password})

        doc.save(function (err,saved) {

            if (err) response.status(500).end();

            response.status(200).end();
        })
    })

Heyo!

This is pretty good, but doesn't have any password hashing (storing your passwords in plain text is bad).

You might want to instead consider using an authentication library like either passportjs or stormpath.

If you're really set on rolling your own auth stuff, you could use this project I wrote as an example (it's using the same tools you are): https://github.com/rdegges/svcc-auth

UPDATE: Since I was asked to show a Stormpath example, here ya go!

var express = require('express');
var stormpath = require('express-stormpath');

var app = express();
app.use(stormpath.init(app, {
  apiKeyId: 'xxx',  // get this from your stormpath account
  apiKeySecret: 'xxx',  // get this from your stormpath account
  secretKey: 'some_long_random_string',  // this is used to encrypt sessions
  application: 'xxx',  // create a stormpath app, then copy the href here
}));

app.listen(3000);

That's it! The above code will automatically generate a registration, login, and logout page at /register, /login, and /logout, respectively.


Is there a performance difference using AS keyword in SQL? I'm working on a project in which the previous programmer seems to have loved using the AS keyword in the SELECT part of queries. I really don't like how it's written but if there is no performance difference I won't change existing code.

My tests did give a slight advantage to not using the AS keyword but I'm clueless on how to properly test it(I ran the different queries using Navicat)

And maybe there is also a difference between different types of databases and engines. I'm using MySQL InnoDB.

Simplified query:

SELECT DISTINCT
    `sometable`.`id` AS `id`,
    `sometable`.`name` AS `name`,
    `sometable`.`description` AS `description`,
    `sometable`.`price` AS `price`,
    `sometable`.`size` AS `size`,
    `sometable`.`area` AS `area`,
    `sometable`.`center` AS `center`
FROM `sometable`

I wouldn't expect much if any noticeable overhead as all that is doing is aliasing the name of the column in the result set.

The question I would ask however, is why it's being done in the first place? All I can think of is to prevent the code which uses the query breaking if a column is renamed (as long as the alias isn't changed).