texts:
Since almost all C functions designed to get data from stdin are bad / flawed:

gets - the less said about this the better
scanf - no checks for buffer overflow and '\n' constantly remaining in stdin, screwing up next scanfs
scanf_s - pretty much the same, but with buffer overflow checks
fgets appends a '\n' to the string
gets_s doesn't have the previous problem, but useless for other streams

I decided to write my own function that would at least be usable to read numbers from stdin:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void *scano(char mode);

int main()
{

  // int *num = (int *) scano(sData, 'd');
   float *num = (float *)scano('f');
   printf("Half: %f", *(num)/2);

    return 0;
}

void *scano(char mode){

    char sData[20];
    fgets(sData, 20, stdin);
    *(sData + strlen(sData) - 1) = '\0'; //get rid of the '\n' before the '\0'
   switch(mode){
       case 'd':{
           int *dataI = (int *)malloc(sizeof(int));
           *dataI = atoi(sData);
           return dataI;
       }
       case 'f':{
           float *dataF = (float *)malloc(sizeof(float));
           *dataF = atof(sData);
           return dataF;
       }
       case 'D':{
           //double...
       }
   }

}

The function is of type void * because that's the only convenient way to have it return different data types.

The function is obviously unfinished for other data types, but I have some questions first:

How can the algorithm of the function be improved?
Don't I need to free() in every case? I'm aware allocated memory needs to be freed, but when working with lists, free() was only used to delete Nodes, when creating Nodes, no free() was called after a malloc().
Is it fully safe? If not, how can it be made safe?


texts:
I am on my second iteration of the famous "Number Of Islands" graph problem on Leetcode.
https://leetcode.com/problems/number-of-islands/
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

My approach is to iterate through each cell in the grid, incrementing a counter when the value == 1. Then, do a breadth-first search of the cell's neighbors, adding them to the queue if their value == 1. Once the queue is empty, keep iterating through all the cells.
To avoid infinite loops, I first used a set() to keep track of a list of tuple coordinates. This seemed to jack up my memory usage, so I then improved the algorithm by removing the set and simply setting the value of visited cells to 0.
I passed all the test cases but still can't figure out how to get a better runtime. I'm currently slower than ~90% of python submissions.
I would appreciate if anyone can help speed this thing up!

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        """
        Gets the neighbors of a coordinate in a grid. Returns a list of tuples.
        """
        m = len(grid)
        n = len(grid[0])

        def get_neighbors(coord: Tuple[int, int]) -> List[Tuple]:
            delta_row    = [0, 1, 0, -1]
            delta_column = [1, 0, -1, 0]

            neighbors = []
            for i in range(len(delta_row)):
                new_x = coord[0] + delta_row[i]
                new_y = coord[1] + delta_column[i]

                if -1 < new_x < m and -1 < new_y < n:
                    neighbors.append((new_x, new_y))

            return neighbors

        # loop through the entire grid and set coords to 0 as we visit them
        # if val == 1, do a breadth-first search for neighbors and increment islands
        # if val == 0, continue to next coordinate.

        islands = 0

        for i in range(len(grid)):
            for j in range(len(grid[0])):
                coord = (i, j)
                if grid[coord[0]][coord[1]] == "1":
                    islands += 1

                    # breadth-first search
                    q = deque([coord])
                    while len(q) > 0:
                        c = q.popleft()
                        grid[c[0]][c[1]] = "0"
                        for neighbor in get_neighbors(c):
                            if grid[neighbor[0]][neighbor[1]] == "1":
                                q.append(neighbor)
                                grid[neighbor[0]][neighbor[1]] = "0"

        return islands


texts: Boolean expression complexity and bitwise operators

texts:
Given this kind of code:

public static final int DEFAULT_MASK = Mask.BASE
    | Mask.SECTOR
    | Mask.GROUP
    | Mask.INDUSTRY
    | Mask.NAME
    | Mask.COUNTRY;

Sonar raises a warning:

  Boolean expression complexity is 5 (max allowed is 3).

What would be a good way to deal with this?

I suppose the warning might go away if I rewrite like this:

public static final int DEFAULT_MASK;
static {
    int tmp = Mask.BASE;
    tmp |= Mask.SECTOR;
    tmp |= Mask.GROUP;
    tmp |= Mask.INDUSTRY;
    tmp |= Mask.NAME;
    tmp |= Mask.COUNTRY;
    DEFAULT_MASK = tmp;
}

... but this smells (too many mutations, ugly).

UPDATE

In addition to the default mask above, I have a few other masks as well, using different sets of bits, for different purposes. Every bitmask with more than 3 bits would raise a Sonar violation.


texts: fix ugly initialisation in while loop over queue

texts:
I have a loop structure, that I really don't like. It's the initialisation I find appalingly ugly. Is there a nicer way to do the following?

Queue<Integer> queue = getMyQueue();
Integer element = queue.poll();
while (element != null){
  calculate_smart_stuff(element);
  element = queue.poll();
}

A for loop is slightly better, but still has the ugly repetition of the assignment of element in the initialiser and the 'incrementer' I also prefer my for loops to be really easy, and only to be reserved for counting and adding (or substracting in corner cases) 1, as this is how I expect a for loop to behave.

Queue<Integer> queue = getMyQueue();
for (Integer element = queue.poll(); element != null; element = queue.poll()){
  calculate_smart_stuff(element);
}

Or should I just keep checking the size before assignment like so?

Queue<Integer> queue = getMyQueue();
while (queue.size() > 0){
  Integer element = queue.poll();
  calculate_smart_stuff(element);
}

What I don't like about this is that I have to check the size every time before getting an element, which itself has a clear indication that the queue was empty.

Are there any better constructs I can use here, or am I just being picky with the last two options?


texts:
I want to develop a simple in-memory web request rate limiting module, I am allowed to have 50 requests from each unique cookie ID every 60 seconds.

I am wondering if the following code is an optimal way of implementing such functionality:

class RateLimiter {

    private static final int MAX_REQUESTS = 50;

    private Map<String, List<Long>> cookieMap = new HashMap<>();

    private boolean isRateLimited(String cookieId) {
      long time = System.currentTimeMillis();
      long oldestTime = time - 60000;
      List<Long> timestamps = cookieMap.getOrDefault(cookieId, new LinkedList<>());
      timestamps.add(0, time);
      int count = 0;
      int tooOldIndex = -1;
      for (int i = 0; i < timestamps.size(); i++) {
          if (timestamps.get(i) >= oldestTime) {
              count++;
          } else {
              tooOldIndex = i;
              break;
          }
      }
      List<Long> newTimestamps = new LinkedList<>();
      // clean up timestamps older than the 60 second window
      for (int i = 0; i < tooOldIndex; i++) {
          newTimestamps.add(timestamps.get(i));
      }
      cookieMap.put(cookieId, newTimestamps);
      if (count >= MAX_REQUESTS) {
         return false;
      } else {
         return true;
      }
  }
}


texts:
I have written the following code, and it works great, but I'm not satisfied. I really love the book "Clean Code" by Uncle Bob and I try to apply all his principles when coding, but I'm having a tough time cleaning this abomination. I call it an abomination because I'm sure everyone new to this method will spend more than 10 seconds trying to figure out what's going on. It's not easy to read. So I'm hoping for input on how to make it easier to read.

private void CopyFileDependencies(FileInfo fileInfo, string destinationPath, int recoveryAttempts = 1)
{
  try
  {
    foreach (var file in Directory.GetFiles(fileInfo.DirectoryName, "*.*", SearchOption.AllDirectories))
    {
      File.Copy(file, file.Replace(fileInfo.DirectoryName, destinationPath), true);
    }
  }
  catch (IOException)
  {
    if (recoveryAttempts > 0)
    {
      KillProcess(fileInfo);
      CopyFileDependencies(fileInfo, destinationPath, --recoveryAttempts);
    }
    else
    {
      throw;
    }
  }
}


texts:
I am coming from a Ruby background and I am learning Python. This is a method I've created to generate a URL safe unique key:

import random;

def generate_unique_key():
    array = []
    for letter in range(97,123):
        array.append(chr(letter))
    for letter in range(65,91):
        array.append(chr(letter))
    for number in range(0,10):
        array.append(number)
    for char in ["-", ".", "_", "~"]:
        array.append(char)

    random_values = random.sample(array, 15)
    random_values = map(lambda x: str(x), random_values)
    return "".join(random_values)

print(generate_unique_key())

Coming from a Ruby background I was certainly puzzled first at not being able call join directly on my list, but having to call it from a string instance.

Also in Ruby I would have written something similar to random.sample(array, 15).join("") directly without having to convert them all to string, but this I believe this is how join() works.

While this works, how can this function be more Pythonic?


texts: Methods to add and check elements in a Bloom Filter

texts:
I have a working Java implementation of Bloom Filter.

These are the methods to addElement and check for an element.

private void addElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    writeLock.lock();
    try {
        int offset = 0;
        long hash = hash1;
        int index;
        int mod;

        for (int i = 1; i <= filterParams.k; i++) {
            hash +=hash2;
            mod = ( int ) ( hash % filterParams.bucketLength );
            index = offset + mod;
            bitSet.set(index);
            offset += filterParams.bucketLength;
        }

        elementsAdded++;
    } finally {
        writeLock.unlock();
    }

}

public boolean containsElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    readLock.lock();
    try {
        long hash = hash1;
        int offset = 0;
        int index;
        int mod;

        for (int i = 1; i <= filterParams.k; i++) {
            hash += hash2;
            mod = ( int ) ( hash % filterParams.bucketLength );
            index = offset + mod;
            offset += filterParams.bucketLength;
            if (!bitSet.get(index)) {
                return false;
            }
        }
    } finally {
        readLock.unlock();
    }

    return true;
}

I was thinking of changing this code above like this.

private void addElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    int offset = 0;
    long hash = hash1;
    int index;
    int mod;

    int[] indexArray = new int[filterParams.k];

    for (int i = 1; i <= filterParams.k; i++) {
        hash += hash2;
        mod = (int) (hash % filterParams.bucketLength);
        index = offset + mod;
        indexArray[i - 1] = index;
        offset += filterParams.bucketLength;
    }

    writeLock.lock();
    try {
        Arrays.stream(indexArray).forEach(bitSet::set);
        elementsAdded++;
    } finally {
        writeLock.unlock();
    }
}

public boolean containsElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    long hash = hash1;
    int offset = 0;
    int index;
    int mod;
    boolean result;
    int[] indexArray = new int[filterParams.k];

    for (int i = 1; i <= filterParams.k; i++) {
        hash += hash2;
        mod = (int) (hash % filterParams.bucketLength);
        index = offset + mod;
        indexArray[i - 1] = index;
        offset += filterParams.bucketLength;
    }

    readLock.lock();
    try {
        result = Arrays.stream(indexArray).allMatch(bitSet::get);

    } finally {
        readLock.unlock();
    }

    return result;
}

My idea was to get more concurrency by minimizing the time spent inside the locks ( both the read and write locks ) for an increase in memory ( initializing an int[] array ) and reduced speed ( Instead of a single 'for' loop, I now have an extra parallel iteration with the  forEach  method ).

Is this a viable tradeOff ?


texts: Unit testing the code that is written using repository pattern

texts:
I have implemented my business logic using the repository pattern. I have an Approve method in my controller. I am calling the service method ApproveUserChangeRequest, which in turn invokes GetUserChangeRequest and ApproveUserChangeRequest in the UnitofWork class. I would like to know if this is standard practice or if there are better ways of doing it.
Please bear in mind in to test the service methods.

UserConroller

[HttpPost]
[AllowAnonymous]
[Route("approve-change-request")]
public IActionResult ApproveUserChangeRequest([FromBody] ApproveUserChangeRequests approveUserChangeRequests)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(new ResponseModel()
        {
            ResponseMessages = new Dictionary<string, string[]>
            {
                { "Errors", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToArray() }
            }
        });
    }

    var result  = _userService.ApproveUserChangeRequest(approveUserChangeRequests);
    var message = string.Empty;
    if (result.Succeeded)
    {
        return Ok(new ResponseModel()
        {
            ResponseMessages = new Dictionary<string, string[]>
            {
               { "Info", new string[] { $"True" } }
            }
        });
    }
    message = string.Join(";", result.Errors.Select(x => $"Code: {x.Code}. Description: {x.Description}"));
    _logger.Error(new IdentityException($"Error approving user change requests. Message: {message}"));
    return BadRequest();

}

UserService class

public  IdentityResult ApproveUserChangeRequest(ApproveUserChangeRequests approveUserChangeRequests)
{
    var userChangeRequest = _userUow.GetUserChangeRequest(approveUserChangeRequests.UserChangeRequestID);

    IdentityResult result =  _userUow.ApproveUserChangeRequest(userChangeRequest, approveUserChangeRequests.ApprovedByAuthUserId, approveUserChangeRequests.AuthApplicationName);
    return result;
}

UnitofWork class (uow)

public UserChangeRequest GetUserChangeRequest(int userChangeRequestId)
{
    return UserChangeRequestRepository.GetQueryable(x =>
        x.Id == userChangeRequestId)
        .FirstOrDefault();
}

  public IdentityResult ApproveUserChangeRequest(UserChangeRequest userChangeRequest, int approvedByAuthUserId, string authApplicationName)
{
    var idResult = IdentityResult.Success;

    // Check if UserChangeRequest is still Pending
    bool isUserChangeRequestPending = UserChangeRequestRepository.GetQueryable(x => x.Id == userChangeRequest.Id && x.ChangeStatus == "Pending").Any();

    if (isUserChangeRequestPending && approvedByAuthUserId > 0)
    {
        // Inserting record in the UserChangeRequestApproval table
        InsertUserChangeRequestApproval(userChangeRequest);
        SaveContext();

        //Updating the user details in IdentityDB, ClientCompanyContact and AuthUser tables
        UpdateUserDetails(userChangeRequest, authApplicationName);
    }
    else
    {
        idResult = IdentityResult.Failed(new IdentityError { Description = "No userchange request to approve" });
    }
    return idResult;
}


texts: Construct intervals from a sequence of numbers and vice versa

texts:
What is a Pythonic way to construct intervals from a sequence of integer numbers? E.g. sequence [1, 2, 3, 6, 7, 9] could be converted to ['1-3', '6-7', '9']. I have implemented it like this:

def sequence_to_intervals(seq):
    intervals = []
    interval_start = None
    interval_end = None
    for i in sorted(seq):
        if interval_start is None:
            interval_start = i
            interval_end = i
        elif interval_end + 1 >= i:
            interval_end = i
        else:
            if interval_start == interval_end:
                intervals.append(str(interval_start))
            else:
                intervals.append(f'{interval_start}-{interval_end}')
            interval_start = i
            interval_end = i
    else:
        if interval_start == interval_end:
            intervals.append(str(interval_start))
        else:
            intervals.append(f'{interval_start}-{interval_end}')
    return intervals

Simple test:

seq = [1, 2, 3, 6, 7, 9]
sequence_to_intervals(seq)
['1-3', '6-7', '9']

Converting intervals back to sequence:

def intervals_to_sequence(intervals):
    seq = []
    for interval in intervals:
        if '-' in interval:
            start, stop = interval.split('-')
            seq += list(range(int(start), int(stop) + 1))
        else:
            seq += [int(interval)]
    return seq

Simple test:

intervals = ['1-3', '6-7', '9']
intervals_to_sequence(intervals)
[1, 2, 3, 6, 7, 9]


texts:
I implemented an algorithm that gives me a list of points that should be drawn in order the get a line between two points. Please note: it works only in a coordinate system whose origin (0,0) is in the upper left corner.

I'd like to get some review on my Haskell code, could it be improved in terms of the language constructs used?
Could it be more readable, more straight forward?

module DrawLine where

data Point = Point Float Float deriving (Show)

getRange :: Int -> Int -> [Int]
getRange a b
    | a <= b = [a..b]
    | otherwise = [b..a]
{-|
 - Get the slope of a line described by the two points received as arguments

-}
getSlope :: Point -> Point -> Float
getSlope (Point x1 y1) (Point x2 y2) = (y2-y1)/(x2-x1)

{-|
 - Get a list of points where pixels should be filled to draw a line
 - (Inspired from Bresenham's line algorithm)
 - Takes two Point arguments representing the end points of the line, the points
 - will be located on a line between these two points
 -}
getLinePoints :: Point -> Point -> [Point]
getLinePoints f@(Point fx fy) l@(Point lx ly)
    -- vertical line
    | fx == lx = [(Point fx (fromIntegral y)) | y <- getRange (round fy) (round ly)]
    | otherwise =
        -- generate points by mapping on the "longer side" of the line
        if m > 1.0 || m < -1.0 then
            -- the rise if higher than the run
            map (\y ->
                    (Point
                        ((1/m) * ((fromIntegral y) - fy) + fx)
                        (fromIntegral y)
                    )
                )
                (getRange (round fy) (round ly))
        else
            map (\x ->
                    (Point
                        (fromIntegral x)
                        (m * ((fromIntegral x) - fx) + fy)
                    )
                )
                (getRange (round fx) (round lx))
        where
            m = getSlope f l


texts: Whitelist HTML tags Microsoft Sanitizer and custom Regex

texts:
I have the following code which I have written due to the fact the Microsoft's Sanitizer is now to aggressive.

What I'm trying to do is as follows.

Create a whitelist of HTML tags I want to keep
After the tags have been converted, run the text through the sanitizer and remove any tags I do not require.
After that, remove any tags that have either id's or classes inside them
Finally convert the tags back.

My code is below, and it would be much appreciated if someone with more experience can have a look over it and give me some feedback.

string txt = "
Keep as sanitizer removes

keep

remove class

";
            var whiteList = new List<Word>();
            whiteList.Add(new Word() { SearchWord = "
", ReplaceWord = "&lt;p&gt;" });
            whiteList.Add(new Word() { SearchWord = "
", ReplaceWord = "&lt;/p&gt;" });
            whiteList.Add(new Word() { SearchWord = "
", ReplaceWord = "&lt;h1&gt;" });
            whiteList.Add(new Word() { SearchWord = "
", ReplaceWord = "&lt;/h1&gt;" });
            whiteList.Add(new Word() { SearchWord = "
", ReplaceWord = "&lt;br/&gt;" });

            whiteList.ForEach(w => txt = txt.Replace(w.SearchWord, w.ReplaceWord));

            var remove = Sanitizer.GetSafeHtmlFragment(txt);

            whiteList.ForEach(w => remove = remove.Replace(w.ReplaceWord, w.SearchWord));

            var again = RegexHelpers.StripHtmlAttributes(remove);

            var tt = again;

public static string StripHtmlAttributes(string s)
    {
        const string pattern = @"\s.+?=[""'].+?[""']";
        var result = Regex.Replace(s, pattern, string.Empty);
    return result;
}


texts: Python 2.7 Tower of Hanoi game with ASCII graphics

texts:
The game generates a fixed, "animated" game board via ASCII characters that is reprinted and cleared after each valid move. The format of the input for making moves is described in the script. You select the "difficulty" via a commandline parameter, so the game requires you enter a number (>=3) for the disc count after the filename.

I'm new to classes, so I wasn't sure how to retrieve the latest "top occupied position" on a rod following each addition/removal of a piece besides what I have here and maybe one other way. I'm guessing that I could have had a default self.topindex and self.top for a rod, and then updated this upon each call of the methods add() and remove().

import os
import sys
level = int(sys.argv[1])

class rod:
    def __init__(self,n):
        self.n=n
        if n==1: self.state= list(range(1,level+1))
        else: self.state=[0]*level
    def pos(self, height): #This generates one chunk of the rod and any pieces at that height
        width=self.state[height-1]
        return " "*(level+1-width)+"-"*width+"|"+"-"*width+" "*(level+1-width)
    def topindex(self): #This is meant to return the index of the top occupied position on the rod
        for index,i in enumerate(self.state):
            if i!=0: return index
            elif index==level-1: return index #But if there are no occupied positions (empty rod) it should return the bottom
    def top(self):
        return self.state[self.topindex()]
    def add(self, piece):
        if self.top()==0: self.state[level-1]=piece
        else: self.state[self.topindex()-1]=piece
    def remove(self):
        self.state[self.topindex()]=0

rod1=rod(1) #This seems like a waste of lines
rod2=rod(2)
rod3=rod(3)

gamestate=["Welcome to the game. ", "first"]

def printgame():
    print gamestate[0]+"The objective is to move all the pieces from rod 1 to another rod."
    print "Pieces must be placed in ascending order of size from top to bottom."
    print 'Move pieces by typing "n m" (where n and m denote the numbers of the source and destination rods) when requested.'
    print ""
    for i in range(1,level+1):
        print rod1.pos(i)[1:]+rod2.pos(i)+rod3.pos(i)
    spacing=(level-3)*" " #Add each block of each rod at the same height to one line, then print the line
    print spacing+" Rod 1    "+2*spacing+"Rod 2    "+2*spacing+"Rod 3\n"

def hasdigit(string):
    return any(char.isdigit() for char in string)

os.system("clear")

def movepiece():
    global rod1 #Too many globals here
    global rod2
    global rod3
    global gamestate
    move=raw_input("Which piece will you move {}? ".format(gamestate[1]))
    if " " in move and hasdigit(move.split(" ")[0]) and hasdigit(move.split(" ")[1]):
        gamestate[0]=""
        gamestate[1]="next"
        source=move.split(" ")[0]
        destination=int(move.split(" ")[1])
        piece=eval("rod"+str(source)+".top()")
        if (piece<eval("rod"+str(destination)+".top()") or eval("rod"+str(destination)+".top()")==0) and piece!=0:
            eval("rod"+str(source)+".remove()")
            eval("rod"+str(destination)+".add("+str(piece)+")")
        elif piece==0:
            print "There's nothing to move from rod {}!\n".format(source)
            movepiece()
        else:
            print "You can't move that there!\n"
            movepiece()
    elif move=="exit": gamestate=move
    else:
        print "Please use the specified format: n m (where n and m denote the numbers of the source and destination rods).\n"
        movepiece()

steps = 0
while rod2.state!=list(range(1,level+1)) and rod3.state!=list(range(1,level+1)):
    if gamestate=="exit": break
    printgame()
    movepiece()
    steps+=1
    os.system("clear")

if gamestate!="exit":
    printgame()
    print "Congratulations, you've finished the game in {} steps.".format(steps)


texts: Minimum number of flight segments using breadth-first search

texts:
I'm practising with graphs, and trying to solve a problem of calculating the minimum number of flight segments, applying breadth-first search.

The code is working, but I think, that it's not clean.

Can anyone suggest how I refactor it to make it cleaner?

def distance(adj, s, t):

    n = len(adj)
    queue = []
    visited = set()
    path = []

    queue.append([s])

    dist = 0

    while (len(queue) > 0):
        path = queue.pop(0)

        last_vertex = path[-1]

        if last_vertex == t:
            # print(path)
            dist = len(path)-1

        elif last_vertex not in visited:
            for w in adj[last_vertex]:
                new_path = list(path)
                new_path.append((w))
                queue.append(new_path)
            visited.add(last_vertex)

    if dist != 0:
        return dist
    else:
        return -1

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n, m = data[0:2]
    data = data[2:]
    edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
    adj = [[] for _ in range(n)]
    for (a, b) in edges:
        adj[a - 1].append(b - 1)
        adj[b - 1].append(a - 1)
    s, t = data[2 * m] - 1, data[2 * m + 1] - 1

    print(distance(adj, s, t))

I represent graph in such way. The first line contains non-negative integers n and m — the number of vertices and the number of edges respectively. The vertices are always numbered from 1 to n. Each of the following m lines defines an edge in the format u v where 1 ≤ u, v ≤ n are endpoints of the edge :

4 5
2 1
4 3
1 4
2 4
3 2
1 3

The last two digits stands for two vertices, we need to find path between.


texts: Base 26 (letters) and Base 10 using recursion

texts:
I was messing around with base conversion between decimal and Base26 (alphabet) with no 0th case because I needed it for the Google Sheets API in order to find specific cell values from a 3 dimensional list of all of the entered cell values on a spreadsheet. Remember that with spreadsheets, the columns are counted with no 0th case and A == 1 Z == 26 BA == 53.

Some test cases for conversion between the two bases would be

"zyz" == 18252, "aa" == 27, "zz" == 702

When I went to go write the code, I looked for simple solutions, but could not find anything using recursion so I wrote this in Python:

def base10ToBase26Letter(num):
    ''' Converts any positive integer to Base26(letters only) with no 0th
    case. Useful for applications such as spreadsheet columns to determine which
    Letterset goes with a positive integer.
    '''
    if num <= 0:
        return ""
    elif num <= 26:
        return chr(96+num)
    else:
        return base10ToBase26Letter(int((num-1)/26))+chr(97+(num-1)%26)

def base26LetterToBase10(string):
    ''' Converts a string from Base26(letters only) with no 0th case to a positive
    integer. Useful for figuring out column numbers from letters so that they can
    be called from a list.
    '''
    string = string.lower()
    if string == " " or len(string) == 0:
        return 0
    if len(string) == 1:
        return ord(string)-96
    else:
        return base26LetterToBase10(string[1:])+(26**(len(string)-1))*(ord(string[0])-96)

I am aware that the first function outputs lowercase letters which can be bypassed by using base10ToBase26Letter(num).upper().

I used this to test the consistency of the values being output:

for x in range(0,100000):
    if x == base26LetterToBase10(base10ToBase26Letter(x)):
        print(x)

Is recursion the best way to approach this problem efficiently, or should I be looking for something else?
If I were to look at readability, is this way the easiest to read?
Does this problem have a shorter solution?
It seems that after about 11 letter digits, this program is no longer accurate, is there a way to make the functions accurate further? (Even if such numbers will never be used in a spreadsheet)


texts:
I'm writing a small Python script which needs to fetch live data from a database (I'm using SQLite 3 for now). I may reuse this function for a lot of scripts. Can this code be made better?

def fetch_database(database, table, filter_dict, case=None):
    """
    Takes filter parameter as a dict
    dict = {'column_name':['filter', 'filter2'], 'column_name2'=[], ..}
    case = wrap around the dictionary key(UPPER, LOWER, etc..), None
    database (with pathname ex: database.db
    table
    column = dict.keys()
    """

    conn = sqlite3.connect(database)
    c = conn.cursor()
    filter_dict = dict_format(filter_dict) # A separate function deletes empty keys from dictionary
    keys_list = filter_dict.keys()
    statement = 'SELECT * FROM ' + table
    if len(keys_list) > 0:
        statement += ' WHERE '
        for keys in keys_list:
            if case == None:
                key = keys
            else:
                key = case + '(' + keys + ')'
            temp_data = filter_dict[keys]
            temp_size = len(temp_data)
            if keys_list.index(keys) != 0:
                statement += ' AND '
            if temp_size > 0:
                for data in temp_data:
                    if temp_data.index(data) == 0:
                        statement += key + '="' + data + '"'
                    else:
                        statement += ' OR ' + key + '="' + data + '"'
    dataset = c.execute(statement)
    dataset = dataset.fetchall()
    return dataset


texts: Regex detection for Puppet configuration

texts:
I've got a PR to add a feature to a Ruby application (Puppet) to allow Regex detection.

Right now, the method only does comparison on exact string matching:

defaultfor :operatingsystem => :fedora, :operatingsystemmajrelease => ['22', '23', '24']

This is annoying, as we have to add in new values everytime a new Fedora release comes out, for example.

I've extended it to match on a Regex:

defaultfor :operatingsystem => :fedora, :operatingsystemmajrelease => /^2[2-9]$/

The old method looks like this:

def self.fact_match(fact, values)
  values = [values] unless values.is_a? Array
  values.map! { |v| v.to_s.downcase.intern }

  if fval = Facter.value(fact).to_s and fval != ""
    fval = fval.to_s.downcase.intern

    values.include?(fval)
  else
    false
  end
end

This is my current proof-of-concept code, which will match both regex and strings, but it feels off.

def self.fact_match(fact, values)

  values = [values] unless values.is_a? Array

  values.map! do |v|
    if v.is_a? Regexp
      v
    else
      v.to_s.downcase.intern
    end
  end

  if fval = Facter.value(fact).to_s and fval != ""
    fval = fval.to_s.downcase.intern
    if values.any? {|v| v.is_a? Regexp }
      regex_match = Regexp.union(values)
      fval =~ regex_match
    else
      values.include?(fval)
    end
  else
    false
  end
end

I feel like there's a much easier way of detecting if it's a Regex or not.


texts:
I'm currently writing a python script which needs some simple networking. After some playing around with sockets, this emerged, but as this is my first foray into sockets I'd really like a second opinion.

Edit: I know my script is not PEP8 compliant, as this is just an experiment. I posted it here to get Feedback about my usage of Sockets, and if there are any pitfalls or corner cases I overlooked.

Package Format:

  datalength+1 \0 data \0

import socket

sep: bytes = b'\0'

minpacketsize: int = 10

def sendpacket(sock: socket.socket, data: bytes) -> None:
    send: bytes = str(len(data) + 1).encode('utf-8') + sep + data + sep

    if len(send) < minpacketsize:
        raise ValueError("Packet too small!")

    sock.sendall(send)

def recivepacket(sock: socket.socket) -> bytes:
    datalen = 0
    header: bytearray = bytearray()
    while not datalen:
        header += sock.recv(1)
        if header.endswith(sep):
            try:
                datalen = int(header[:-1].decode('utf-8'))
            except UnicodeDecodeError or ValueError as e:
                raise ValueError("Error while decoding header!") from e

        if len(header) == 10:
            raise ValueError("Could not find Header!")

    rawdata: bytes = sock.recv(datalen)

    if rawdata.endswith(sep):
        return rawdata[:-1]
    else:
        raise ValueError("Could not find Packet end!")


texts: Reading groups of files and concatenating them

texts:
I have made some adjustments to some code that you can see on this thread:

Read daily files and concatenate them

I would like to make some further refinements and make sure I am on the right track organize some of my files better. I added some functions and made some other changes to prevent errors and make my code easier to reuse (and to be more Pythonic).

#got rid of import *
import pandas as pd
import numpy as np
import datetime as dt

ftploc = r'C:\Users\FTP\\'
loc = r'C:\Users\\'
splitsname = 'Splits'
fcrname = 'fcr_report_'
npsname = 'csat_report_'
ahtname = 'aht_report_'
rostername = 'Daily_Roster'
vasname = 'vas_report_'
ext ='.csv'

#had to create some periods and date format parameters
start_period = '13 day'
end_period = '1 day'
fcr_period = '3 day'
date_format1 = '%m_%d_%Y'
date_format2 = '%Y_%m_%d'
start_date = dt.date.today() - pd.Timedelta(start_period)
end_date = dt.date.today() - pd.Timedelta(end_period)
fcr_end_date = end_date - pd.Timedelta(fcr_period)
daterange1 = pd.Timestamp(end_date) - pd.Timestamp(start_date)
daterange2 = pd.Timestamp(fcr_end_date) - pd.Timestamp(start_date)
daterange1 = (daterange1 / np.timedelta64(1, 'D')).astype(int)
daterange2 = (daterange2 / np.timedelta64(1, 'D')).astype(int)
print('Starting scrubbing file...')

#AHT files have a different date format in the filename so I made this function
def dateFormat(filename):
    if filename == ahtname:
        return date_format2
    else:
        return date_format1

#FCR is 3 days delayed (72 hour window) so I needed to create some logic to adjust for it
def dateRange(filename):
    if filename == fcrname:
        return daterange2
    else:
        return daterange1

#this function works on all of my files now. I just wonder if there is a better way to refer to the other functions? Is having a separate function for the date range and format ideal?
def readAndConcatFile(filename, daterange):
    df_list = []
    try:
        for date_range in (pd.Timestamp(startdate) + dt.timedelta(n) for n in range(dateRange(filename))):
            df = pd.read_csv(ftploc + filename + date_range.strftime(dateFormat(filename)) + ext, parse_dates = True)
            df_list.append(df)
        return pd.concat(df_list)
    except IOError:
        print('File does not exist: ', filename + date_range.strftime(dateFormat(filename)) + ext)

#this appears to work great. I lose the ability to read certain columns though or to specify dtypes for specific columns
nps = readAndConcatFile(npsname, daterange)
vas = readAndConcatFile(vasname, daterange)
fcr = readAndConcatFile(fcrname, daterange)
aht = readAndConcatFile(ahtname, daterange)


texts:
I have the following function and I was wondering if anyone could come up with something more efficient.

It just has to split both the content and the search string and determine how many words are required to be matched before being true.

For example,

"A dog can run.".ContainsV2("Red Dog Run", 4) = false

"A dog can run.".ContainsV2("Red Dog Run", 2) = true

"A dog can run.".ContainsV2("Red Dog Run") = true

"A dog can run.".ContainsV2("Red Dog Run", MatchAllWords: true) = false

/// <summary>
/// Checks to see if any of the words are contained in the string.
/// </summary>
/// <param name="content"></param>
/// <param name="SearchString">Search string</param>
/// <param name="NumberOfMatches">Specify how many words have to match in the search string.
///  This value is automatically dropped when the user searches less words.
/// I.e. NumberOfMatches = 3 and the user searches 'Bob', NumberOfMatches gets set to 1.</param>
/// <param name="MatchAllWords">If set to true, all of the words in the search string must be contained in what's being checked</param>
/// <returns></returns>
public static bool ContainsV2(this string content, string SearchString, int NumberOfMatches = 1, bool MatchAllWords = false)
{
    var matches = 0;
    var numberOfWords = SearchString.Split(' ').Length;
    // Update required number of matches
    NumberOfMatches = NumberOfMatches > numberOfWords ?
                    numberOfWords :
                    NumberOfMatches;

    if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(SearchString))
    {
        SearchString.Split(' ')
            .ToList()
            .ForEach(w => //Gets the index of each word after being split
                matches += content
                    .IndexOf(
                        StripNonAlphaNumeric(w),
                        StringComparison.OrdinalIgnoreCase
                    ) >= 0 ? 1 : 0
            );
    }
    if (MatchAllWords)
    {
        return matches == numberOfWords;
    }
    return matches >= NumberOfMatches;
}


texts: C++ Not-So-Simple Entire HTML Generating Code v0.3

texts:
As a follow-up to my code's v0.1 revision, we now introduce V0.3, with capability for storage of attributes and a struct for each HTML tag. Just start the struct, call its functions, change its variables then use <fstream> to make the complete HTML file using generateHTML()!

#include <iostream>
#include <fstream>
#include <vector>

struct HtmlTag {
    std::string tagname;
    std::string tagcontent;
    std::vector<std::string> tagattributes;
    std::vector<std::string> tagattrcontent;
    void addAttribute(std::string attrName, std::string attrCont) {
        tagattributes.push_back(attrName);
        tagattrcontent.push_back(attrCont);
    }
    int removeAttribute(int pos) {
        tagattributes.erase(tagattributes.begin() + pos);
        tagattrcontent.erase(tagattrcontent.begin() + pos);
        return tagattributes.size();
    }
    std::string returnTag() {
        std::string attributes = "";
        if (tagattributes.size() != tagattrcontent.size()) {
            return "ERR:UNMATCHINGLENGTH";
        }
        unsigned short i;
        if(tagattributes.size() > 0 && tagattrcontent.size() > 0) {
            for(i = 0; i < tagattributes.size(); i++) {
                attributes = attributes + " " + tagattributes[i] + "=\"" + tagattrcontent[i] + "\"";
            }
        }
        else {
            return "<" + tagname + ">" + tagcontent + "</" + tagname + ">";
        }
        return "<" + tagname + attributes + ">" + tagcontent + "</" + tagname + ">";
    }
};

std::string generateHTML(std::string doctype, std::string head, std::string body) {
    return "<!DOCTYPE " + doctype + " />\n\n<html>\n    <head>\n        " + head + "\n    </head>\n    <body>\n        " + body + "\n    </body>\n</html>";
}

int main()
{
    HtmlTag myHTML;
    myHTML.addAttribute("spam", "eggs");
    myHTML.tagcontent = "bar";
    myHTML.tagname = "foo";
    unsigned int i2;
    for(i2 = 0; i2 < myHTML.tagattrcontent.size(); i2++) {
        std::cout << myHTML.tagattrcontent[i2] << ":" << myHTML.tagattributes[i2] << std::endl;
    }
    std::cout << myHTML.returnTag() << std::endl;
    std::cout << generateHTML("html", "<title>Hello World!</title>", myHTML.returnTag()) << std::endl;
}


texts: Implementing a custom iterator by inheriting from an existing iterator class and overriding operator*

texts:
My goal is to write very little code and I want a custom iterator that only changes the behavior of the dereference operator* but copies the rest of the behavior from the underlying container iterator.

The following code works but is it correct?

#include <iostream>
#include <unordered_map>

using namespace std;

template <typename K, typename V>
class KeyValueStore
{
    using base_iterator = typename unordered_map<K, V>::iterator;

public:
    struct iterator : public base_iterator
    {
        iterator(base_iterator it) : base_iterator(it)
        { }

        // The custom behavior for the dereference operator.
        V& operator*()
        {
            return base_iterator::operator*().second;
        }
    };

    V& get(const K& key)
    {
        return store.at(key);
    }

    void put(K key, V value)
    {
        store[key] = value;
    }

    iterator begin() { return iterator {store.begin()}; }

    iterator end() { return iterator {store.end()}; }
private:
    unordered_map<K, V> store;
};

int main()
{
    KeyValueStore<string, int> store;
    store.put("aa", 5);
    store.put("vf", 4);

    for (auto item : store)
        cout << item << endl;

    return 0;
}


texts:
I'm currently working on the library BigPicture.js with live demo here.

There surely are lots of little improvements possible in the main .js file (< 300 lines of code), here are some little questions :

Is it common to use something like :

(function() {
  // code here
} ) ();

to launch the code and to be able that return; will work ? Or are there more common schemes ?
Should I place this at the end of the <body> in the mail .html file or in the <head> part?  Should I launch this code on something like DOMContentLoaded ?
When zooming to much (using the zoom feature I provide with mousewheel or double-click or PGUP/DOWN etc.) with Chrome (for example when a single letter uses full browser height, i.e. the text is really big), then panning (with CLICK+DRAG ) is really slow.  It is not true at all on Firefox, not on IE. What could be the reason (and solution) for this slowness with Chrome only?
Are there some other obvious improvements? I taught myself JavaScript (but with help of SO questions/answers of course), so there are surely some bad coding habits in my code, right?

Code for panning (a little bit shortened, see the project's page for real code)

  dragging = false;

  bpContainer.onmousedown = function(e) {
    dragging = true;
    previous_mouse = {x: e.pageX, y: e.pageY};
  }

  window.onmouseup = function() {
    dragging = false;
  }

  bpContainer.ondragstart = function(e) {
    e.preventDefault();
  }

  bpContainer.onmousemove = function(e) {
    if (dragging) {
      bp.style.transitionDuration = "0s";
      bp.x += e.pageX - previous_mouse.x;
      bp.y += e.pageY - previous_mouse.y;
      bp.style.left = bp.x + 'px';
      bp.style.top = bp.y + 'px';
      current.x -= (e.pageX - previous_mouse.x) * current.zoom;
      current.y -= (e.pageY - previous_mouse.y) * current.zoom;
      previous_mouse = {x: e.pageX, y: e.pageY};
    }
  }


texts: Converting the integers to their equivalent string representations

texts:
I have the following function which converts an integer (such as 103) to its string representation ("one hundred three"):

NumberToString = (function ()
    local floor, abs, num, tens, bases = math.floor, math.abs, {
        [0] = '',
        'one',
        'two',
        'three',
        'four',
        'five',
        'six',
        'seven',
        'eight',
        'nine',
        'ten',
        'eleven',
        'twelve',
        'thirteen',
        'fourteen',
        'fifteen',
        'sixteen',
        'seventeen',
        'eighteen',
        'nineteen',
        'twenty'
    }, {
        [0] = 'and',
        [3] = 'thirty',
        [4] = 'forty',
        [5] = 'fifty',
        [6] = 'sixty',
        [7] = 'seventy',
        [8] = 'eighty',
        [9] = 'ninety',
    }, {

        [10^2] = ' hundred',
        [10^3] = ' thousand',
        [10^6] = ' million'
    }
    return function(n)
        local n = floor( abs(n) )
        local str = {}
        if n > 10^6 then
            table.insert( str, NumberToString(n / 10^6)..bases[10^6] )
            n = n % 10^6
        end
        if n > 10^3 then
            table.insert( str, NumberToString(n / 10^3)..bases[10^3] )
            n = n % 10^3
        end
        if n > 10^2 then
            table.insert( str, NumberToString(n / 10^2)..bases[10^2] )
            n = n % 10^2
        end
        if num[n] then
            table.insert( str, num[n] )
        else
            table.insert( str, tens[floor(n/10)]..' '..(n % 10 > 0 and num[n % 10] or '') )
        end
        return table.concat(str, ' ')
    end
end)()

Can I improve the performance somehow? Or does some other (and better method) exist for the desired results?

I think that the segment between line #43 to #53 is quite redundant and can be modified?


texts: calloc, malloc, free and realloc wrappers to store the size being allocated

texts:
I'm currently building a node.js addon for libcurl. Right now I'm trying to correctly use v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory to update v8 on the amount of memory being allocated by libcurl, and to do that I need to wrap the above mentioned functions that libcurl uses, using curl_global_init_mem().

I saw the following code being used here that basically does the same thing, but for another lib.

I currently have the following code (almost identical to the one above):

struct MemWrapper {
    size_t size;
    double data;
};

#define MEMWRAPPER_SIZE offsetof( MemWrapper, data )

inline void* MemWrapperToClient( MemWrapper* memWrapper ) {
    return static_cast<void*>( reinterpret_cast<char*>( memWrapper ) + MEMWRAPPER_SIZE );
}

inline MemWrapper* ClientToMemWrapper( void* client ) {
    return reinterpret_cast<MemWrapper*>( static_cast<char*>( client ) - MEMWRAPPER_SIZE );
}

void AdjustMem( ssize_t diff )
{
    Nan::AdjustExternalMemory( static_cast<int>( diff ) );
}

void* MallocCallback( size_t size )
{
    size_t totalSize = size + MEMWRAPPER_SIZE;
    MemWrapper* mem = static_cast<MemWrapper*>( malloc( totalSize ) );
    if ( !mem ) return NULL;
    mem->size = size;
    AdjustMem( totalSize );
    return MemWrapperToClient( mem );
}

void FreeCallback( void* p )
{
    if ( !p ) return;
    MemWrapper* mem = ClientToMemWrapper( p );
    ssize_t totalSize = mem->size + MEMWRAPPER_SIZE;
    AdjustMem( -totalSize );
    free( mem );
}

void* ReallocCallback( void* ptr, size_t size )
{
    if ( !ptr ) return MallocCallback( size );
    MemWrapper* mem1 = ClientToMemWrapper( ptr );
    ssize_t oldSize = mem1->size;
    MemWrapper* mem2 = static_cast<MemWrapper*>( realloc( mem1, size + MEMWRAPPER_SIZE ) );
    if ( !mem2 ) return NULL;
    mem2->size = size;
    AdjustMem( ssize_t( size ) - oldSize );
    return MemWrapperToClient( mem2 );
}

char* StrdupCallback( const char* str )
{
    size_t size = strlen( str ) + 1;
    char* res = static_cast<char*>( MallocCallback( size ) );
    if ( res ) memcpy( res, str, size );
    return res;
}

void* CallocCallback( size_t nmemb, size_t size )
{
    size_t totalSize = size + MEMWRAPPER_SIZE;
    MemWrapper* mem = static_cast<MemWrapper*>( calloc( nmemb, totalSize ) );
    if ( !mem ) return NULL;
    mem->size = nmemb * size;
    AdjustMem( nmemb * totalSize );
    return MemWrapperToClient( mem );
}

I hook it up with libcurl calling:

curl_global_init_mem( CURL_GLOBAL_ALL, MallocCallback, FreeCallback, ReallocCallback, StrdupCallback, CallocCallback );

I compiled the add-on, and from what I can see, it's working fine, but as I'm unexperienced with C++, I need to know if this is correct. What kind of bad things can happen from modifying the pointer returned by calloc, malloc and prealloc like that? Is there any way to improve it?


texts:
I have the following java class which has many private variables and methods:

package gui;
import java.awt.Color;
import java.io.File;
import java.util.*;
import java.util.stream.Stream;
import javax.swing.*;
import messages.Message;
import net.miginfocom.swing.MigLayout;
import utils.*;
public class FileCopyManager extends JFrame {
    public static String appName  = "File Copy Manager v1.6.4.0";
    private PreferencesManager pManager             = new PreferencesManager(this);
    private JCheckBoxMenuItem allowDuplicatesOption = new JCheckBoxMenuItem("Allow dupliactes in list");
    private Controller controller = new Controller();
    private StatusFrame status    = new StatusFrame();
    private FileHandler fHandler  = new FileHandler(status);
    private Message      msg      = new Message();
    private JMenuBar menuBar      = new JMenuBar();
    private JMenu   fileMenu      = new JMenu("File"),
                    editMenu      = new JMenu("Edit");
    private JMenuItem saveList    = new JMenuItem("Save queue"),
            exit                  = new JMenuItem("Exit"),
            loadList              = new JMenuItem("Load queue"),
            openAppDirectory      = new JMenuItem("Open app folder"),
            showPreferences       = new JMenuItem("Preferences"),
            exportPreferences     = new JMenuItem("Export Preferences"),
            deleteApp             = new JMenuItem("Delete app settings"),
            restartApp            = new JMenuItem("Restart Application");
        private File      selectedFile = null;
    private String destinationPath = null;
    private ArrayList<File> files  = new ArrayList<>();
    private JPanel panel = new JPanel();
    private JFileChooser chooser = new JFileChooser();
    private JButton addFiles, selectDestination, copyFile, copyFiles,
            deleteFile, deleteAll, openDestinationFolder,stopCopy;
    private JComboBox<String> fileNames;
    private DefaultComboBoxModel<String> model;
    private int selectedFileIndex = -1;
    private JTextField dragPanel = new JTextField(20);
    private JLabel dragLabel;
    private File listFile = new File("app"+PreferencesManager.sep+"userList.dat");
    private boolean allowDuplicates = false;
    private Thread[] copyThreads = new Thread[2];
    private boolean isNull(Object...t){
        /*
         * Check if any of the arguments is null
         */
    }
    private void allowCopy(){
        /*
         * Enables certain buttons based on certain criteria
         */
    }
    private void allowDelete(){
        /*
         * Enables certain buttons based on certain criteria
         */
    }
    private void allowEdits(){
        /*
         * Enables certain buttons based on certain criteria
         */
    }
    private void createList(){
        //Create a list with some random names
    }
    private void initDragAreas(){
        /*
        * Create some drag and drop ares in the GUI
        */
    }
    public void updateList(){
        // Update a lst in the CUI with some names
    }
    public void showFiles() {
        //Show some file names in the GUI
    }
    public void restart(){
        //Code that restarts the GUI
    }
    @SuppressWarnings("deprecation")
    private void initUIElements() {
        /***
        * Create some UI elements
        */
        initDragAreas();
    }
    public JLabel[] getLabels() {
        // return some labels
    }
    public JButton[] getButtons() {
        // return some buttons
    }
    public void preload() {
        /*
        * See if we need to change the main UI(change colors or font size)
        * and if we need do it first and then show the app
        */
    }
    public FileCopyManager) {
        initUIElements();
        preload();
    }
}

This application is a small project I made for fun during summer.
I was wondering: Is it a bad thing to use too many private members and methods?

Would it be bad for a production code?


texts:
One of my first projects. I present to you - Android Flashlight app!

public class MainActivity extends AppCompatActivity {
    Camera cam = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onBtn(View view) {
        if (checkCameraHardware(this)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
               if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
                    handleFlash();
               }else {
                   handleFlash();
                   System.out.println("Check : has permission");
               }
            }
        }
    }
    public void handleFlash() {
            if (cam == null){
                cam = getCameraInstance();
            }
            Camera.Parameters parameters = cam.getParameters();
            if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                cam.setParameters(parameters);
                cam.startPreview();
            } else if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camEnd();
            }
    }

    public static Camera getCameraInstance(){
        Camera camera = null;
        try {
            camera = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
            e.printStackTrace();
        }
        return camera; // returns null if camera is unavailable
    }
    private boolean checkCameraHardware(Context context) {
        if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    public void camEnd() {
        cam.release();
        cam = null;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        camEnd();
    }
}

I have tested this on my Marshmallow device and it works as expected (but no on my lollipop device for some reason). Any suggestions would be great!


texts: JavaScript Boilerplate - Review comments required

texts:
I am in between to create JavaScript Boilerplate (collection of best practices around) for low/medium complex project and will host on GitHub in sometime once finalized it.

Have divided the JavaScript modules in 3 parts

project.config.js - Would have all the required configuration
project.main.js - the JS Boilerplate
project.helper.js - would have most commonly used functions, user may or may not want it

project.config.js

/* MODULE (our namespace name) and undefined are passed here
 * to ensure 1. namespace can be modified locally and isn't
 * overwritten outside of our function context
 * 2. the value of undefined is guaranteed as being truly
 * undefined. This is to avoid issues with undefined being
 * mutable pre-ES5.
*/
(function (MODULE, undefined) {
    MODULE.config = {
        language: 'english',
        debug: true,
        etc...
    }
}(window.MODULE = window.MODULE || {}))

project.main.js:

/* MODULE (our namespace name) and undefined are passed here
 * to ensure 1. namespace can be modified locally and isn't
 * overwritten outside of our function context
 * 2. the value of undefined is guaranteed as being truly
 * undefined. This is to avoid issues with undefined being
 * mutable pre-ES5.
*/

(function( MODULE, $, undefined ){
/**
 * Logging function, for debugging mode
 */
jQuery.log = function(message) {
    if( (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') && console.debug ) {
        console.debug(message);
    } else {
        //alert(message);
    }
};

/**
 * Private properties
 */
var foo = "foo",
    bar = "bar";

/**
 * Public methods and properties
 */
MODULE.foobar = "foobar";
MODULE.sayHello = function () {
    speak("hello world");
};

/**
 * Private method
 */

/* Benefits:
 * 1. Makes it easier to understand "functions as an object".
 * 2. It enforces good semicolon habits.
 * 3. Doesn't have much of the baggage traditionally associated with functions and scope.
 */
var getData = function () {
};

/* Singleton with Privileged Methods */
MODULE.subModule = (function () {
    function _subModule() {
        /**
         * Init call
         */
        var _this = this;   /* Store this to avoid scope conflicts */

        /**
         * facebookLogin - FB.login prompts the user to authorize your application
         */
        this.facebookLogin = function () {
        }

        /**
         * private method
         */
        var privateMethod = function() {
        };

        this.init = function () {
            _this.facebookLogin();
            return this;
        };

        return this.init();
    }

    return new _subModule();
}());
})(window.MODULE = window.MODULE || {}, jQuery)

Though it's pretty straight forward with comments and all but anyway let me elaborate it further, have been using Global Abatement using namespace, singleton inside the SIAF (to protect the scope and follow encapsulation) and using privileged private methods inside it and executing the privileged one in init().

And essentially returning the submodule in the last to available to the window level using namespace (MODULE).

Looks pretty neat but still looking to make it better and robust.

Would appreciate code review comments here.

Thanks for your time.


texts: Simplifying and optimizing factors and prime factorization generator

texts:
My first algorithm for finding the factors of a number was pretty slow and horrible (it started at \$O(n^2)\$, where n was not even the inputted number), but I eventually came up with this new code.  I just want the first factors of a number (not the duplicates), so I used sqrt(n) instead of n for the loop.  As for the prime factorization, it appears to be efficient but it could probably be improved.

Could this program be written simpler and more efficiently?
Are all of these std::stringstreams even necessary?
Is there a better way of having findPrimeFactorization() output in the form of w^x * y^z?

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

using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::stringstream;

string findFactors(unsigned, vector<unsigned> &factors);
string findPrimeFactorization(unsigned posInt);

int main()
{
    unsigned positiveInteger;

    cout << "\n\n> Pos. Integer: ";
    cin >> positiveInteger;

    vector<unsigned> factors;

    cout << "\n\n  * Factors:\n\n";
    cout << findFactors(positiveInteger, factors);

    cout << "\n  * Prime Factorization:\n\n      ";
    cout << findPrimeFactorization(positiveInteger) << "\n\n\n";

    system("PAUSE"); // I use Visual C++
}

string findFactors(unsigned posInt, vector<unsigned> &factors)
{
    std::stringstream factorsStr;
    double sqrtInt = sqrt(static_cast<double>(posInt));

    for (unsigned i = 1; i <= sqrtInt; i++)
    {
        if (posInt % i == 0)
        {
            factors.push_back(i);
            unsigned x = posInt / i;
            factorsStr << "      " << i << " x " << x << "\n";
        }
    }

    return factorsStr.str();
}

string findPrimeFactorization(unsigned posInt)
{
    std::stringstream primesStr;

    for (unsigned i = 2; i <= posInt; i++)
    {
        int powerDegree = 0;

        while (posInt % i == 0)
        {
            posInt /= i;
            powerDegree++;
        }

        if (powerDegree >= 1)
        {
            primesStr << i;

            if (powerDegree > 1)
                primesStr << '^' << powerDegree;
            if (i <= posInt)
                primesStr << " x ";
        }
    }

    return primesStr.str();
}


texts: Checking if a string parameter contains only digits

texts:
public void setMobile(String mobile) {
      char[] mobileList = mobile.toCharArray();
      boolean isValid = true;
      for(char x : mobileList)
      {
          if(!Character.isDigit(x))
          {
              isValid = false;
          }
      }
      if(isValid)
      {
          this.mobile = mobile;
      }
    }

Is this the best way of doing things? Cheers.


texts: JavaScript - Difference between two dates in days or less

texts:
I have 2 dates that I would like to have the difference between them in days and if less than a one day simply show "less than a day".

remainingTime() {
  // Scientific notation of 8.64e+7
  const DAY_IN_MILLISECONDS = 8.64 * (10 ** 7);

  const date1 = new Date('2019-02-28T01:22:06.671Z').getTime();
  const date2 = new Date('2019-02-28T04:01:06.671Z').getTime();

  const differenceInMS = date2 - date1;

  const days = Math.floor(differenceInMS / DAY_IN_MILLISECONDS);
  return (days > 1) ? `They have ${days} days` : (days === 1) ? `They have ${days} day` : `you have less than a day left`;
}

Is this way correct if localization is taken into account?

what exactly is the difference between getTime (), getMilliseconds () and getUTCMilliseconds ()?


texts:
So I've written a class for storing user/device specific settings, but I've written the Kotlin pretty much like I would in Java:

import android.content.Context
import android.content.SharedPreferences
import java.util.*

class UserSettings {

    private lateinit var _prefs :SharedPreferences

    fun UserSettings(ctx : Context) {
        _prefs = ctx.getSharedPreferences("UserSettings", Context.MODE_PRIVATE)
    }

    private val KEY_DEVICEID = "deviceId"
    var deviceId :String
        get() {
            var value = _prefs.getString(KEY_DEVICEID, null)
            if (null == value) {
                value = UUID.randomUUID().toString()
                this.deviceId = value
            }
            return value
        }
        set(it) {
            _prefs.edit()
                .putString(KEY_DEVICEID, it)
                .apply()
        }

}

This feels really verbose. I've considered writing a helper library to simply store all values from a class in SharedPreferences via reflection, but I'm not sure if that's overkill. The above code obviously only has one value at the moment, but I'll be adding a couple more that will look very similar to the above.


texts: Wrath Cookie Switch for Auto Golden Cookie Clicker

texts:
Sometimes you feel like a wrath cookie and sometimes you don't.

Here is a function that I created that will run on an interval, so all I have to do is set a boolean when I want to switch between Wrath + Gold cookies and just Gold cookies.

// allows me to turn on and off the clicking of the Wrath Cookies
var wrathCookieSwitchOn = false;

var SpecialCookieClicker =
    setInterval(function() {
        if (wrathCookieSwitchOn){
            Game.shimmers.forEach(function(shimmer) {
                if (shimmer.type == "golden") { shimmer.pop() }
            })
        } else {
            Game.shimmers.forEach(function(shimmer) {
                if(shimmer.type == "golden" && shimmer.wrath == 0)
                {
                    shimmer.pop()
                }
            })
        }
    }, 500);

All I have to do is change the variable value in the Developer Console in order to affect this code.

How could I do this a little better?


texts:
Yesterday, I gave an interview after a long time, and I was asked a question which I couldn't solve on the spot.

I had to implement a sort function for a Array of strings in JavaScript, with the following requirements:

The Array will always contain Strings
For sorting, Upper Case has higher priority than Lowe Case Letters, with Numbers having the Least.
Assume that Array.sort() cannot be used
The performance of the sorting is not a factor; i.e. Bubble sort is fine.

I was thinking of the solution today, and came up with this:

function sortArray(items) {
  let itemcount = items.length;
  for (var i = 0; i < itemcount; i++) { //number of passes
    for (var j = 0; j < (itemcount - 1 - i); j++) { //for checking all pairs in a given pass
      let a = items[j];
      let b = items[j + 1];
      if (compareCaseSenitiveStrings(a, b) < 0) {
        console.log("Switch", a, b)
        items[j + 1] = a;
        items[j] = b;
      }
    }
  }
  //return
  return items;
}

//Function to compare two given strings, and return the index of the higher priority one
function compareCaseSenitiveStrings(a, b) {

  //Inner functions
  function compareCharacters(a, b) {
    //check the case first()
    if (a.getFirstCase() == b.getFirstCase()) {
      let charDiff = a.codePointAt(0) - b.codePointAt(0);
      return -Math.sign(charDiff)
    } else {
      //different cases
      //We need to pass the id of the one which is higher;
      let requiredCaseOrder = ["NONE", "LOWER", "UPPER"];
      return requiredCaseOrder.indexOf(a.getFirstCase()) - requiredCaseOrder.indexOf(b.getFirstCase());
    }
  }

  function isNumeric(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    //End of inner functions
    //===============================================

  //Start of function here

  //First check if both are numbers
  if (isNumeric(a) && isNumeric(b)) {
    //return the index of smaller number (since it has higher priority)
    return -Math.sign((parseFloat(a) - parseFloat(b)));
  }

  //Now check that lengths of both is greater than 0
  if ((a.length > 0) && (b.length > 0)) {
    //check the first elements of this string
    let result = compareCharacters(a[0], b[0]);
    if (result != 0) {
      //this means one input has higher priority, lets return that
      return result;
    } else {
      //both are equal
      //get the result of remaining characters
      return compareCaseSenitiveStrings(a.substring(1), b.substring(1));
    }
  } else {
    //length of atleast one of these strings is zero.
    //return the index of the longer element
    let lengthDiff = a.length - b.length;
    return Math.sign(lengthDiff);
  }
}

String.prototype.getFirstCase = function() {
  let caseEnum = ["LOWER", "NONE", "UPPER"];
  var caseIndex = 1;
  if (this == this.toLowerCase()) {
    caseIndex--;
  }
  if (this == this.toUpperCase()) {
    caseIndex++;
  }
  return caseEnum[caseIndex];
};

Is this code readable enough?
Are there any other Design Patterns that could be applied? Any other points which could be improved?


texts: Processing a collection of objects, one at a time, with an asynchronous method.

texts:
I currently use setInterval and a wait flag to process this collection. Is there a cleaner way?

var wait = false;
var processInterval = setInterval(function(){
    if(!wait){
        var currentVideo = videos.shift();

        if(currentVideo){
            wait = true;

            validateSongById(currentVideo.videoId, function(result){
                wait = false;
                if(result){
                    clearInterval(processInterval);
                    callback(currentVideo);
                    return;
                }
            });
        }
    }
}, 200);


texts: Longest consecutive sequence of ascending, descending, or equal integers

texts:
Given an array of integers, find the longest consecutive sequence, where a sequence is defined as being either (strictly) ascending, (strictly) descending, or all-equal.

836926 then has the longest sequence 369, which happens to be ascending. 241455556 has the longest sequence 5555, which happens to be all equal.

Please comment on the algorithm (correct? complexity?) and how it can be improved.

#include <iostream>
#include <vector>

int sign(int someInt)
{
    if (someInt > 0) { return 1; };
    if (someInt < 0) { return -1; };
    return 0;
}

bool isSequence(int a, int b, int c)
{
    if (sign(a - b) == sign(b - c))
    {
        return true;
    }

    return false;
}

void findSeq(const std::vector<int> &vect)
{
    int maxLength = 0;
    int startingIndex = 0;

    int currentLength = 2;
    int findIndex = 0;

    for (int i = 0; i < vect.size() - 2; i++)
    {

        if (isSequence(vect[i], vect[i + 1], vect[i + 2]))
        {
            currentLength++;
            if (currentLength > maxLength)
            {
                startingIndex = i - findIndex;
                maxLength = currentLength;
            }
            findIndex++;
        }

        else
        {
            findIndex = 0;
            currentLength = 2;
        }
    }

    for (int j = startingIndex; j < startingIndex + maxLength; j++)
    {
        std::cout << vect[j];
    }

}


texts: Resize the hash table and rehash every element

texts:
I'm trying to increase my hash table size by two if the table is filled more than half of it. I tried to rehash every single element from the old table and put it back to my new table, then assign my old table as the new table again. What do you guys think of my own created function? I'm practicing for my final exam and only creating this in paper. I haven't tried yet using compiler and so forth.

I'm using quadratic probing to insert the keys, and once more than half of the table is filled, resize the hash table by calling the function resize().

//find index
int HashingTable::hash(int x, int size){
     return x % size;
}

//insert value to the array, but using quadratic probing
void HashingTable::insertQuadratic(int x, int T[]) {
    int index = hash(x, size);
    int i = 1;
    //the quadratic probing
    while (T[index] != empty) {
        index = (index + (i*i)) % size; //increment quadraticly
        i = i + 1;
    }
    T[index] = x;
    numOfItems = numOfItems + 1;
    double loadFactor = numOfItems / size;
    if (loadFactor >= 0.5) {
        resize(T);
    }
}

void HashingTable::resize(int T[]) {
    int newSize = 2 * size;
    int* newTable = new int[newSize];
    for (int i = 0; i < newSize; i++) {
        newTable[i] = empty;
    }
    for (int i = 0; i < newSize; i++) {
        if (T[i] != empty) {
            int index = hash(T[i], newSize);
            int i = 1;
            while (newTable[index] != empty) {
                index = (index + (i*i)) % newSize;
            }
            newTable[index] = T[i];
        }
    }
    T = newTable;
    delete newTable;
}


texts: VIm function that runs file through shfmt

texts:
I've written a Vim function that formats the file using shfmt. I'd like to know if there is a way I can improve this script.

I am bothered by the fact that I can't think of a way to do this without editing the file in the subprocess and reloading the file. Is there a way to do the equivalent of %!shfmt -options?

if exists("g:loaded_shfmt") || &compatible || ! executable('shfmt')
  finish
endif

let s:save_cpoptions = &cpoptions
set cpoptions&vim

let s:switches = join(['-w', '-s', '-i', '2', '-bn', '-ci', '-sr'])

function! s:shFormat()
  let l:filename = @%
  let l:out = system('shfmt ' . s:switches . ' ' . l:filename)
  edit!
endfunction

nnoremap <silent> <Leader>fb :call <SID>shFormat()<CR>

let &cpoptions = s:save_cpoptions

let g:loaded_shfmt = 1


texts: Simple REST-API using Python with falcon

texts:
I have a basic example of a REST API that I've done to control LEDs. I've read Dr. Dobbs article about REST and how to do it but I feel that my example doesn't look professional for some reason. Particularly the main menu on GET / request. Could anyone please suggest improvements?

import falcon
import json

LEDS = {"red": "RED COLOR",
        "green": "GREEN COLOR"}

class LedsResource(object):
    def on_get(self, req, resp):
        """
        Return main menu
        """
        resp.status = falcon.HTTP_200  # This is the default status

        resp.set_header('Powered-By', 'Falcon')
        resp.body = (json.dumps({"led_url": req.url + "led/{green | red}/"
                                    ,"led_url_POST": {"state": "{1 | 0}"}}))

class LedsResourceTwo(object):
    def on_get(self, req, resp, color):
        """
        Return current state for LED indicated by the color parameter
        """
        resp.status = falcon.HTTP_200
        resp.set_header('Powered-By', 'Falcon')

        if color in LEDS:
            resp.body = (json.dumps({color: "simulated_state"}))
        else:
            resp.body = (json.dumps({"error": "color_not_found"}))

    def on_post(self, req, resp, color):
        """
        Change state of LED indicated by the color parameter
        """
        if color in LEDS:
            print("Received:", color, req.get_params("state"))
        resp.body = (json.dumps({"response": "all_ok"}))

app = falcon.API()

app.add_route('/', LedsResource())
app.add_route('/led/{color}', LedsResourceTwo())

if __name__ == "__main__":
    pass

Outputs:

GET /

HTTP/1.1 200 OK
Connection: close
Date: Mon, 21 Nov 2016 22:20:48 GMT
Server: gunicorn/19.6.0
content-length: 93
content-type: application/json; charset=UTF-8
powered-by: Falcon

{
    "led_url": "http://localhost:8000/led/{green | red}/",
    "led_url_POST": {
        "state": "{1 | 0}"
    }
}

POST /led/green state=1

HTTP/1.1 200 OK
Connection: close
Date: Mon, 21 Nov 2016 22:22:02 GMT
Server: gunicorn/19.6.0
content-length: 22
content-type: application/json; charset=UTF-8

{
    "response": "all_ok"
}


texts:
i have this code that is suppose to work with at starting the minimum number of threads, say 5. when it starts the first five threads, it automatically replaces any thread that is finished  making sure that there is always five threads working.

the problem here is that, am finding it difficult to manage where am suppose perform locks

Private Sub StartProcess()
        intNextItemIndex = intMaxThreadCount
        ' start the first five threads
        For i = 0 To intMaxThreadCount
            If i < ListWorkItems.Count Then
                StartNextItem(i)
            End If
        Next
        ' update running threads
    End Sub

    Private Sub StartNextItem(ByVal index As Integer)
        Dim tt As New ThreadTask
        If index < ListWorkItems.Count Then

            ' start parsing thread
            Dim t As New Thread(AddressOf DoWork)
            With tt
                .Index = index
                .Task = "count"
                .Data = CStr(index * index)
            End With
            With t
                .IsBackground = True
                .Name = "Thread " & index
                .Start(tt)
            End With
            Thread.Sleep(100)
        End If
    End Sub

    Private Sub DoWork(ByVal data As Object)
        Dim tt As ThreadTask = CType(data, ThreadTask)
        Dim sTemp As String = Nothing
        Dim objLock As Object = New Object()
        Dim t As Double = 0
        myWatch = New Stopwatch
        Try
            Debug.Print("Incoming index: " & CInt(tt.Index))
            myWatch.Start()

                    SyncLock (objLock)
                        sTemp = PerformWork(ListWorkItems(CInt(tt.Index)).ToString)
                        'sTemp = CountTo()
                    End SyncLock

            myWatch.Stop()
            t = myWatch.ElapsedMilliseconds / 1000
            AddItem(tt.Index, t.ToString & " = " & sTemp)
            'AddItem(index, t.ToString)
        Catch ex As Exception
            ' catch error
            Debug.Print( ex.Message)
        End Try
 end sub

Public Sub AddItem(ByVal index As Integer, ByVal item As String)

    If Me.InvokeRequired Then
        Me.Invoke(New AddItemDelegate(AddressOf AddItem), index, item)
    Else
        Dim objLock As Object = New Object()
        Dim lvItem As New ListViewItem

        SyncLock (objLock)
            count += 1
            intNextItemIndex += 1
        End SyncLock

        With lvItem
            .Text = index.ToString
            .SubItems.Add(ListWorkItems(index).ToString)
            If item.Length < 100 Then
                .SubItems.Add(item.ToString)
            Else
                .SubItems.Add(item.Length.ToString)
            End If
        End With
        listView1.Items.Add(lvItem)

        If count = ListWorkItems.Count Then
            Button1.Enabled = True
            tsslStatus.Text = "Finished!!"
            Debug.Print("Finished: " & index.ToString)
        Else
            tsslStatus.Text = "Processing item (" & count + 1 & ")"
        End If

        StartNextItem(intNextItemIndex)
    End If

End Sub

can someone help me review it and tell me whats wrong with it?

Are the loks ok?

Is this way of doing it ok?

What possible improvements can i make

thanks all


texts:
I'm learning a little Scala by writing a little card game. What I want to do here is check that the Traversable[Team] supplied has the same number of team members for each team.

How can I clean this up?

val teamSizes = teams.map(_.members.size)
require(teamSizes.foldLeft((true, teamSizes.head)) {
  (tuple, lastSize) =>
    val (b, size) = tuple
    (b && size == lastSize, lastSize)
}._1)


texts:
My Rails apps need to connect to several external services to perform some functions.

Now, I realize that some of the services I need might also be reused outside Rails (like in Capistrano deployment), so I want to find the best compromise I can so I can reuse those services across several Ruby apps.

Simple example : during the deployment of my application with Capistrano, I want to send a notification to a slack channel when it's done. Similarly inside my Rails app, I might want to send some slack notification at some point

And because I like bullet points

Decoupled from Rails - can be used eg. during a Capistrano deployment
Service is made of a client that usually requires to be initialized with some app/secret keys
We're talking single Threads, so it does (or not ?) make sense to have a singleton/static service that we do not need to instanciate everytime
The service must survive/restart automatically when there's a crash or a console/web reload!
The service should be able to report its status at application start/anytime

Here's my attempt. With the below code I'm having problems after a code reload from the console or from the development rails console

# Define common structure for third party API connectors
# based on Singleton#module pattern https://github.com/nslocum/design-patterns-in-ruby/tree/master/singleton/module_as_singleton

# Include this module and implement the following class methods
# - #credentials_present?
# - #should_be_activated?
# - #service_client

module ServiceConnector
  extend ActiveSupport::Concern

  included do
    @activated = false
    @activation_attempt = false
    @client = nil

    attr_reader :client, :activated

    def self.report_activation_successful
      puts "SUCCESS - Service #{service_name} is activated"
    end

    def self.report_missing_credentials
      puts "ERROR - Service #{service_name} should be activated " \
            'but credentials are not available'
    end

    def self.report_not_activated
      puts "INFO - Service #{service_name} is deactivated "
    end

    def self.client
      @client ||= service_client
    end

    def self.service_name
      name.gsub('Connector', '')
    end

    def self.activate
      @activation_attempt = true
      if credentials_present?
        @client = service_client
        @activated = true
      end
    end

    def self.activated?
      @activated
    end

    def self.status_report
      if @activated
        report_activation_successful
      elsif @activation_attempt
        report_missing_credentials
      else
        report_not_activated
      end
    end

    def self.nothing
      puts "WARNING - Service #{service_name} deactivated " \
          'no communication with remote API'
      nil
    end

    def self.secretize(value)
      half = (value/2).floor
      value[0..half].to_s + '*'*value.siz
    end
  end
end

And here's how I implement a service (eg Slack)

module SlackConnector
  include ServiceConnector
  @webhook = nil

  def self.webhook=(webhook)
    @webhook = webhook
  end

  def self.credentials_present?
    @webhook != nil
  end

  def self.service_client
    ::Slack::Notifier.new(
      @webhook,
      username: "MyBot-#{ENV['RAILS_ENV']}",
    )
  end

  def self.ping(message, opts = {})
    return nothing unless activated?
    @client.ping(message, {
      icon_url: 'https://example.com/image.png,
    }.merge(opts))
  end

On the Rails side, I'm initializing in an initializer

# initializers/slack.rb
slack = ::SlackConnector
def slack_should_be_activated?
  Rails.env.production? or
  Rails.env.staging? or
  (Rails.env.development? and ENV['ENABLE_SLACK_DEV'] == 'true')
end

if slack_should_be_activated?
  slack.webhook = Rails.application.secrets.slack.dig('webhooks', 'some_webhook')
  slack.activate
  slack.status_report
end


texts: Find all multiples of a number in given range in reverse order

texts:
I have a problem set which requires me to print all the multiples of a number in given range in reverse order.

So far I have tried this but not sure it is optimized or not!

#import <objc/objc.h>
#import <objc/Object.h>

@implementation TestObj

int main()
{
    int limit = 0;
    int divisor = 5;
    printf("enter a number : ");
    scanf("%d",&limit);

    printf("enter divisor : ");
    scanf("%d",&divisor);

    printf("Multiples of %d in reverse order till limit %d are : ",divisor, limit);
    for(int i = limit/divisor; i > 0 ; i--){
        printf("%d ",i*divisor);
    }

    return 0;
}

@end


texts:
Java program uses the following construction: (provided mainly for context)

public class Utils {
  public static final byte PROVIDER_FOO = 0;
  public static final byte PROVIDER_MOO = 1;
  public static final byte PROVIDER_BAR = 2;
  public static final byte PROVIDER_FUR = 3;
  public static final byte PROVIDER_BOO = 4;
  public static final byte PROVIDER_ANOTHER_FOO = 5;
  public static final byte PROVIDER_YET_ANOTHER = 6;

  public static String [] PROVIDERS = {"FOO", "MOO", "BAR", "FUR", "BOO",
    "PROVIDER_ANOTHER_FOO", "PROVIDER_YET_ANOTHER"};

  ...

}

So, each element of array has a number. And each array index in range 0..6 has text representation. Text representation is using in outer world: reading configs, printing results. Number representation is using in internal tasks. So, there a problem to transform text representation to number and vice versa. Number is transferring to string as following:

// someObject.getProviderNumeric() returns numeric value for someObj's provider
String strProvider = Utils.PROVIDERS[someObj.getProviderNumeric()]

String is transferring to number like this:

int getNumericByText(String strProvider) {
  for (int i = 0; i < Utils.PROVIDER_YET_ANOTHER; ++i) {
    if (strProvider.equals(Utils.PROVIDERS[i])) {
      return i;
  }
  return -1;
}

It looks pretty bulky. What is the best way to rewrite?


texts:
I have an application which log file has most lines start with a time/date, followed by a debugging level and the actual log message. Often I want to watch the output live and colors make it a lot better readable. This is what I use at the moment for piping the logs:

while read line; do
echo "$line" |
sed -e "s,^.* DEBUG,$(tput setaf 2)&$(tput sgr0)," \
    -e "s,^.* INFO,$(tput setaf 2)&$(tput sgr0)," \
    -e "s,^.* WARN,$(tput setaf 3)&$(tput sgr0)," \
    -e "s,^.* ERROR,$(tput setaf 1)&$(tput sgr0)," \
    -e "s,^.* SEVERE,$(tput setaf 1)$(tput bold)&$(tput sgr0),"
done

The call on the command line looks like this:

tail -fn 200 /path/server.log | ./logparser

This all works as expected but when many lines are printed at once the parser lags behind. I think this is because I run sed once for every single line. Is there a better solution?


texts:
I have an array of values of the form:

configs = ["26W", "27W", "28W"...]

They correspond to some of the a elements in a list:

...

...
...

When the data in the list does correspond to an existing a, I need to set the parent li class to "available" and not "unavailable". If there is an a with a value not in the list, I need to set the class to "unavailable" and not "available". (Edit: I realize that having both classnames is redundant, but I don't have the option to change that right now.)

I can think of two ways to do this:

Iterate

var $allSwatchItems = $("#value-list > li");
$allSwatchItems.each(function () {
  var $this = $(this);
  var $a = $this.children("a");
  if (configs.indexOf($a.attr("data-value")) === -1) {
    $this.addClass("unavailable").removeClass("available");
  } else {
    $this.addClass("available").removeClass("unavailable");
  }
});

Two-step

var $allSwatchItems = $("#value-list > li");
// Set everything to unavailable at first.
$allSwatchItems.removeClass("available").addClass("unavailable");
// Build the selector for the swatch anchors.
var swatchSelector = configs.map(function (val, idx, arr) {
  return "a[data-value='" + val + "']";
}).join(", ");
// Set the matching list items to available.
var $availSwatchItems = $allSwatchItems.children(swatchSelector).parent();
$availSwatchItems.removeClass("unavailable").addClass("available");

I know there are pros and cons to both approaches, but is one significantly better than the other (and how), or is there a third approach I should consider?

Update: Here's how I finally did it:

function checkAvailable() {
    if (-1 !== $.inArray($(this).children("a").attr("data-value"), configs)) {
        return "available";
    } else {
        return "unavailable";
    };
}
$("ul#value-list > li").removeClass("unavailable available").addClass(checkAvailable);


texts:
Input

  The input for this problem is a String of sorted numbers and a special number. The syntax of the input would be 1,2,3,4;5

  Output

  The program will output all of the possible sums that equate to the special number. The output for the example would be 1,4;2,3

I solved the problem by using some simple subtraction. The program will begin at the greatest value and work its way to the lowest value. For each value the program will subtract it from the pre-set value and search the array for that value. I want to know what I could do better for this.

import java.util.*;
public class NumPairs {
    static String line = "1,2,3,4;5";
    public static void main(String[] args) {
        String fina = "";
        if(!line.equals("")){
        String a = line.substring(line.indexOf(";")+1,line.length());
        String[] valu = line.substring(0,line.indexOf(";")).split(",");
        for(int h = valu.length-1; h >0; h--){
            int need = Integer.parseInt(a) - Integer.parseInt(valu[h]);;
            if(Arrays.asList(valu).indexOf(need + "") != -1 && fina.indexOf(need +"") == -1 && need != Integer.parseInt(valu[h])){
                if(need > Integer.parseInt(valu[h]))
                fina += valu[h] +","+need +";";
                else
                fina += need +","+ valu[h] + ";";
            }
        }
        }
        if(fina.equals(""))
        System.out.println("NULL");
        else
        System.out.println(fina.substring(0,fina.length()-1));
    }
}


texts: Scrape every Java themed codingbat problem set and your personal solutions

texts:
I made the switch from JavaScript to Python lately. This is my first Python project and my first web-scraper. Do I have good practices? And could this be optimized?
from bs4 import BeautifulSoup
import requests

urlHalf = 'codingbat.com'

print("what is your email")
inputOne = input(">")
print("password")
inputTwo = input(">")

post_params = {
    "uname": inputOne,
    "pw": inputTwo,
}

# urls to use
base_url = "https://codingbat.com"
login_url = "https://codingbat.com/login"
java_url = "https://codingbat.com/java/"

def get_href():
    print("Getting directories")
    href_array = []
    initial = requests.get(base_url)
    soup = BeautifulSoup(initial.content, "lxml")
    tab_data = soup.find(class_="floatleft")
    hrefs = tab_data.find_all(class_="h2")
    for href in hrefs:
        href_array.append(href.text)
    return(href_array)

def gather_links():
    directories = get_href()
    print("Getting problem links")
    link_array = []
    for directory in directories:
        r = requests.get(java_url + directory)
        # get links to problems
        content = BeautifulSoup(r.content, "lxml")
        links = content.find_all(
            "a", href=lambda href: href and "prob" in href)
        link_array.append(links)
    return(link_array)

def join_links():
    linkList = gather_links()
    new_link_list = {}
    print("Joining links")
    for link in linkList:
        for each in link:
            text = each.text
            backUrl = each.get("href")
            realUrl = "http://" + urlHalf + backUrl
            new_link_list.update({text: realUrl})
    return new_link_list

def scrape_data():
    f = open('answers/answers.java', 'w')
    linkList = join_links()
    with requests.Session() as session:
        post = session.post(login_url, data=post_params)
    for i in linkList:
        print("Scraping: " + i)
        response = session.get(linkList[i])
        content = BeautifulSoup(response.content, "lxml")
        indentDiv = content.find(class_="indent")
        table = indentDiv.find("form", {"name": "codeform"})
        aceDiv = table.find("div", id="ace_div")
        f.write("//" + i + ": " + linkList[i] + "\n\n")
        f.write(aceDiv.text + "\n")
    print("done")

if __name__ == "__main__":
    scrape_data()


texts: Too many parentheses to format a percentage in SELECT

texts:
This query seems to have way too many parentheses.

SELECT
CAST(ISNULL(ROUND(CAST((SUM(product1) + SUM(product2)) AS FLOAT) / CAST(salescalls.visits AS FLOAT) * 100, 2), 0) AS VARCHAR) + '%' AS avrg
FROM sales, salescalls
WHERE sales.salescallId = salescalls.id


texts:
What would be the shortest way to capture folder structure in code? I would like to have a more or less reusable strictly typed approach to use in scripts instead of stringly typed paths we all usually deal with. Here is how a part of my simple “system info” utility looks like:

static void Main(string[] args)
{
    foreach(var cursor in SystemDisk.Windows.Cursors.Animated)
        Console.WriteLine(cursor);
}

Where:

using static System.IO.Directory;

public static class SystemDisk
{
    public static string Drive { get; set; } = "C:";
    public static string AutoexecBat => $"{Drive}\\Autoexec.bat";
    public static class Windows
    {
        public static string Path => $"{Drive}\\Windows";
        public static string SystemIni => $"{Path}\\System.ini";
        public static class Cursors
        {
            public static string Path => $"{Windows.Path}\\Cursors";
            public static IReadOnlyList<string> Animated => GetFiles(Path, "*.ani");
        }
    }
}


texts: Checking if variable is defined before accessing its properties

texts:
I didn't write this but I noticed it in our codebase at work.

var data = object && object.attribute && object.attribute.data ? object.attribute.data : {};

I get that the programmer is trying to check that the variable object.attribute.datais defined before using it, but is seems like so much repeated code. What's the best way to assign data the value of object.attribute.data if it's defined, otherwise giving it a value of {}?


texts: Find first threshold crossing in numpy array

texts:
Given the following artificially generated data:

t_steps = 30

data = np.array([
    np.arange(t_steps) * .05,
    np.arange(t_steps) * .1,
    np.arange(t_steps) * .2,
    np.arange(t_steps) * .3

])

I find the time-step the each line of data has passed a threshold. If it does not pass the given threshold, I assign a time-step of -1:

react_tms = []
thresh = 3.5

for dat in data:
    whr = np.where(dat > thresh)
    if len(whr[0]) == 0:
        react_tms.append(-1)
    else:
        react_tms.append(whr[0][0])

This gives:

[-1, -1, 18, 12]

Is there some way to do this without the for-loop? Even before the for-loop is removed, should I be using something other than np.where to find the threshold crossing?


texts: Angular 8: Scroll spy implementation for a timeline Contents

texts:
I have made a timeline component that can have multiple milestone/major/minor as sub components nested within timeline container component. I have also added a side navigation for that lists all Milestones. Therefore I append range property to TimelineMilestoneComponent which contains the top position value(offestTop) of its and consecutive element. like below

arr[i + 1] ? arr[i + 1].htmlEl.offsetTop - 1 : Infinity

Scroll Listener checks scroll position with with range values to decide if that is current viewed milestone.

Is the implementation correct?
What is better way of accomplishing this?

Here is the component Class

export class TimelineComponent implements OnInit, AfterContentInit {
  milestones: Array<ExtendedTimelineMilestoneComponent>;
  visbleMilestone: ExtendedTimelineMilestoneComponent;

  @Input()
  themeColor = "#254267";

  @HostBinding("attr.style")
  public get valueAsStyle(): any {
    return this.sanitizer.bypassSecurityTrustStyle(
      `--theme-color: ${this.themeColor}`
    );
  }

  @HostListener("window:scroll", ["$event.target"])
  public scrollListener(doc: HTMLDocument): void {
    //avoid update visbleMilestone if scroll is within its scope
    if (
      window.scrollY < this.visbleMilestone.range[0] &&
      window.scrollY > this.visbleMilestone.range[1]
    ) {} else {
      this.milestones.every(m => {
        if (window.scrollY >= m.range[0] && window.scrollY < m.range[1]) {
          this.visbleMilestone = m;
          return false;
        }
        return true;
      });
    }

  }

  @ContentChildren(TimelineMilestoneComponent)
  set _milestones(milestones: QueryList<TimelineMilestoneComponent>) {

    this.milestones = milestones.map((m, i, arr) =>
      Object.assign(m, {
        range: [
          m.htmlEl.offsetTop,
          arr[i + 1] ? arr[i + 1].htmlEl.offsetTop - 1 : Infinity
        ],
      })
    );
  }

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {}

  ngAfterContentInit() {
    this.visbleMilestone = this.milestones[0] ? this.milestones[0] : null;
  }

  scrollToMilestone(m: TimelineMilestoneComponent) {
    m.htmlEl.scrollIntoView({ behavior: "smooth" });
  }
}


texts:
In order to reduce redundancy in my app, I have added the method self.find_or_keep(object) to many of my models in order to find existing records with the same values, so I can reference the already existing ones instead of creating new records. Basically, this method checks most attributes for equality between two objects; id, created_at and updated_at are always excluded for obvious reasons.

class IPv4 < ActiveRecord::Base
  # returns its param or an already existing record
  def self.find_or_keep(ipv4)
    # create new object in memory, if param is a Hash
    ipv4 = IPv4.new(ipv4) if ipv4.is_a?(Hash)
    return (entry = IPv4.find_by(address: ipv4.address, subnetmask: ipv4.subnetmask)) ? entry : ipv4
  end
end

class Service < ActiveRecord::Base
  # returns its param or an already existing record
  def self.find_or_keep(service)
    # create new object in memory, if param is a Hash
    service = Service.new(service) if service.is_a?(Hash)
    return (entry = Service.find_by(protocol: service.protocol, port_from: service.port_from, port_to: service.port_to)) ? entry : service
  end
end

As you can see, it's not very DRY. The problem here is that the method each time has to check for different parameters, so I have to rewrite the find_by every time I want to use the method in another class. What I have in mind for DRYing it up is something like this:

class IPv4 < ActiveRecord::Base
  implement_find_or_keep_with(:address, :subnetmask)
end

class Service < ActiveRecord::Base
  implement_find_or_keep_with(:protocol, :port_from, :port_to)
end

class ActiveRecord::Base
  # whatever is need
end

Is something like this possible? If so, how would I implement it?


texts: Should I be using Regex to uppercase uncommon characters?

texts:
I've written a function for converting strings to upper case. It currently works by replacing each character using a Regex pattern with a hash:

# Special upcase function that handles several Norwegian symbols.
def norwegian_upcase(string)
    string.upcase.gsub(/[æøåäâãàáëêèéïîìíöôõòóüûùúý]/, {
        'æ' => 'Æ',
        'ø' => 'Ø',
        'å' => 'Å',
        'ä' => 'Ä',
        'â' => 'Â',
        'ã' => 'Ã',
        'à' => 'À',
        'á' => 'Á',
        'ë' => 'Ë',
        'ê' => 'Ê',
        'è' => 'È',
        'é' => 'É',
        'ï' => 'Ï',
        'î' => 'Î',
        'ì' => 'Ì',
        'í' => 'Í',
        'ö' => 'Ö',
        'ô' => 'Ô',
        'õ' => 'Õ',
        'ò' => 'Ò',
        'ó' => 'Ó',
        'ü' => 'Ü',
        'û' => 'Û',
        'ù' => 'Ù',
        'ú' => 'Ú',
        'ý' => 'Ý'
    })
end

I have the feeling that it's horribly inefficient to be using Regex like this, and that I should probably be using another method. Can anyone suggest a better way to replace single characters, or is Regex fit for the task?