texts:
Here is an example of how I solved this problem (though this is not the only nor the best way by any means) for an assignment where it was also requisite to determine if a string was a reverse prefix of the other. Obviously a palindrome is a reverse prefix of itself so if you can determine a reverse prefix then you can determine a palindrome.

I would love some feedback on my code as well as any thoughts on my implementation/solution.

int main()
{
    char string1[50];
    char string2[50];

    printf("Please enter a string: ");
    gets(string1);
    if (strlen(string1) == 1)
        exit(1);
    printf("Please enter a second string: ");
    gets(string2);
    printf("\nString 1 = %s", string1);
    printf("\nString 2 = %s\n", string2);
    if (isReversePrefix(string1, string2))
        printf("String 2 is a reversed prefix of string 1\n");
    if (isPalindrome(string1))
        printf("String 1 is a palindrome\n");
    else
        printf("String 1 is not a palindrome\n");
    if (isPalindrome(string2))
        printf("String 2 is a palindrome\n");
    else
        printf("String 2 is not a palindrome\n");
    return 0;
}
/************************************************
 isReversePrefix - Receives two string pointers
 and determines if the second is a reverse
 prefix of the first. Returns either true or
 false.
 The word 'HIM' has the following prefixes 'H', 'HI',
 'HIM'. All of these can be reversed to 'H', 'IH', 'MIH'
 ************************************************/
int isReversePrefix(char *str1, char *str2)
{
    char *temp1 = str1;
    char *temp2 = str2;

    if (strlen(str2) > strlen(str1))
        return 0;

    strrev(temp2);
    while ((*temp1 == *temp2) && (*temp2 != '\0'))
    {
        temp1++;
        temp2++;
    }
    if (*temp2 == '\0')
        return 1;
    else
        return 0;
}
/************************************************
 isPalindrome - receives one string parameter and
 checks if it is a palindrome or not. Returns
 true if it is and false if not.
************************************************/
int isPalindrome(char *str1)
{
    char *start = str1;
    char *end = str1 + strlen(str1) - 1;
    if (isReversePrefix(start, end))
        return 1;
    else
        return 0;
}


texts: Writing to file using TPL with ConcurrentQueue

texts:
Here is a sample code to explain the approach I am going for.

public class LogWriter
{
    #region Private Members

    // If writer is not static class, still need to keep single message list; same for other members
    private static ConcurrentQueue<string> _logMessages = new ConcurrentQueue<string>();
    private static object locker = new object();
    private static bool _stopAfterCurrentQueue = false;
    private static bool _discardQueueAndStop = false;

    private static CancellationTokenSource _tokenSource = new CancellationTokenSource();
    #endregion

    public void Write(string text)
    {
        if (!_stopAfterCurrentQueue && !_discardQueueAndStop)
        {
            Task.Run(() =>
           {
               _logMessages.Enqueue(text);

           });

            Task.Run(() =>
            {
                while (!_logMessages.IsEmpty)
                {
                    foreach (var item in _logMessages)
                    {

                        _logMessages.TryDequeue(out string current);
                        lock (locker)
                        {
                            // Will be replaced by StreamWriter
                            File.AppendAllText("Log_" + DateTime.Now.ToString("yyyyMMMdd") + ".txt", current + Environment.NewLine);
                        }
                    }
                }
            }, _tokenSource.Token);
        }
    }

    public void ProcessCurrentAndStop()
    {
        // Only stops accepting new messages, will process the current queue
        _stopAfterCurrentQueue = true;
    }

    public void DiscardQueueAndStop()
    {
        // Cancels subsequent Enqueue
        _tokenSource.Cancel();

        // No more writing even if there is something in the queue
        _discardQueueAndStop = true;
    }

    public void RestartLogging()
    {
        _stopAfterCurrentQueue = false;
        _discardQueueAndStop = false;

        _tokenSource.Dispose();
        _tokenSource = new CancellationTokenSource();
    }
}

The idea is to write to file in asynchronous way. I am trying to make it thread safe as well. There is not much to process here except to write message to a file.

I would like to understand what could be potential issues with this approach and also if it would be better to keep class static.


texts:
I wrote codes that listener and callback function like this:

struct MyListener
{
    virtual void callback1(int value) = 0;
    virtual void callback2(string value) = 0;
    ...
};

vector<weak_ptr<MyListener>> _listeners;

void MyClass::fireCallback1(int value)
{
    vector<weak_ptr<MyListener>>::iterator iter = _listeners.begin();
    while (iter != _listeners.end())
    {
        if ((*iter).expired())
        {
            iter = _listeners.erase(iter);
        }
        else
        {
            shared_ptr<MyListener> listener = (*iter).lock();
            listener->callback1(value);
            ++iter;
        }
    }
}

void MyClass::fireCallback2(string value)
{
    vector<weak_ptr<MyListener>>::iterator iter = _listeners.begin();
    while (iter != _listeners.end())
    {
        if ((*iter).expired())
        {
            iter = _listeners.erase(iter);
        }
        else
        {
            shared_ptr<MyListener> listener = (*iter).lock();
            listener->callback2(value);
            ++iter;
        }
    }
}

But as you see, when I add more functions on MyListener struct, I have to add fireCallbackN functions on MyClass, and it has too many duplicated codes.

Is there best way to make simplify these duplicate codes in C++?


texts: Condensing code that generates Pascal's triangle

texts:
I recently started learning Java for a class and my teacher gave us an assignment in which we had to write up code which would print out the Pascal's triangle to an amount of rows decided by the user, and use recursion to do so. I believe that I'm done with the assignment, but wanted to know, for myself, as to how I could improve and condense this messy code (the array complicates things but I wanted to use it for a different program that expands polynomials (\$(x+b)^n)\$).

import java.io.*;
import java.util.*;

public class PascalTriangleYar
{
private static int[][] xArr;
private static int g =2;

public void printArray(int[][] xArray)
{

  for(int r=0; r<xArray.length; r++){
  System.out.println("");
     for(int c=0; c<xArray[r].length; c++)
        if(xArray[r][c]==0)
           System.out.print("\t");
        else
           System.out.print(xArray[r][c]+"\t");}

}

public int[][] getTri()
{
return xArr;}

public void pTriangle(int r)
{
  int n=r;
  xArr = new int[r][2*r-1];
  xArr[0][r-1]=(1);
  p2T(r, 1);
  printArray(xArr);
}

private void p2T(int r, int n)
{
  int z=0;

  int p=r-g;

    xArr[n][p]=(1);

  for(int fd=0; fd<xArr[0].length-1; fd++){
  if(fd==0)
     xArr[n][fd]= xArr[n-1][0]+xArr[n-1][1];
  else
     xArr[n][fd]= xArr[n-1][fd-1] + xArr[n-1][fd+1];

     xArr[r-1][2*r-2]=1;

  }

  g++;
  if(n<r-1)
  {
     p2T(r,n+1);
  }
 // else
 // {return;}

}

public static void main(String [] args)
{
  PascalTriangleYar tri = new PascalTriangleYar();
  Scanner inputReader = new Scanner(System.in);
  System.out.println("Enter a number (x). A pascal's triangle of x rows will be printed.");
  int x = inputReader.nextInt();
  tri.pTriangle(x);
}
}


texts: Semantically structured HTML5 for a news page

texts:
I'm developing a website and I cut the images that I will use:

CSS contains the top image

CSS contains the center image (repeat-y)

CSS contains the bottom image

And inside news-center class I have .news-content class. Inside .news-content I have this structure:

CodeReview

Semantic HTML5

But I want to use HTML5 markup, so I made this. Is it right?

CSS contains the top image

News Title

Lorem ipsum doler si amet

          News autor, news tags, etc..

CSS contains the bottom image


texts: Hackerrank: Fraudulent Activity Notifications

texts:
I'm having trouble on a question from Hackerrank, this solution works for smaller lists but seems to collapse when the list grows to 200,000 where I get the error "Wrong Solution". The problem is here so you could reproduce it. Im not sure if there is an error in my code whereby it would fail. Is there anyway to improve the efficiency of my solution?
When I encounter these sort of issues where it fails at very high lists or anything of the sort, how should I react? What kind of issue should I expect to solve?
Problem text  (Incase link doesnt work):
If the amount spent by a client on a particular day is greater than or equal to 2x the client's median spending for a trailing number of days, they send the client a notification about potential fraud.
The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data (d) for a period of n days. Determine the number of times the client will receive a notification over all n days.
The following is the whole Hackerrank Code required to run the problem, I wrote the functions "Median" and "activityNotifications":
#include <iostream>
#include <algorithm>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);

double Median(vector<int> arr)
{
    int d = arr.size();

    double Even = (arr[(d/2)-1] + arr[((d/2)+1)-1]) / (double)2;
    double Odd = arr[((d+1)/2)-1];

    return (d%2==0)? Even: Odd;
}

int activityNotifications(vector<int> expenditure, int d) {

    int Notices = 0;

    vector<int> SpendData = vector<int>(expenditure.begin(),expenditure.end());
    sort(SpendData.begin(),SpendData.end());

    vector<int> SpendDataMedian = vector<int>(SpendData.begin(),SpendData.begin() + d);

    for (int i = d; i < expenditure.size();++i)
    {
        if ((Median(SpendDataMedian)*2) <= expenditure[i])
            {Notices++;}

        SpendDataMedian.erase(SpendDataMedian.begin());
        SpendDataMedian.push_back(SpendData[i]);

    }
    return Notices;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string first_multiple_input_temp;
    getline(cin, first_multiple_input_temp);

    vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));

    int n = stoi(first_multiple_input[0]);

    int d = stoi(first_multiple_input[1]);

    string expenditure_temp_temp;
    getline(cin, expenditure_temp_temp);

    vector<string> expenditure_temp = split(rtrim(expenditure_temp_temp));

    vector<int> expenditure(n);

    for (int i = 0; i < n; i++) {
        int expenditure_item = stoi(expenditure_temp[i]);

        expenditure[i] = expenditure_item;
    }

    int result = activityNotifications(expenditure, d);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}

Sample input is:
9 5
2 3 4 2 3 6 8 4 5

Expected output is:
2


texts:
I've written a program that finds the difference between data and gives output.
Here's the code:
import json
import numpy as np
print("This is a basic machine learning thing.")
baseData = {"collecting":True,"x":[],"y":[]}
while baseData["collecting"]:
  baseData["x"].append(float(input("X:")))
  baseData["y"].append(float(input("Y:")))
  if input("Do you want to keep feeding data? Press enter for yes, or type anything for no.") != "":
    baseData["collecting"] = False
if len(baseData["x"]) == len(baseData["y"]):
  xdata = baseData["x"]
  ydata = baseData["y"]
  nums = []
  for i in range(len(xdata)):
    nums.append(xdata[i] - ydata[i])
  median = np.median(nums)
else:
  print("malformed data")
def getY(x):
  pass
while True:
  data = input("X/Data:")
  print(int(data)-median)

To work the program, give it X and Y data, then give it X data and it will predict Y data.


texts: How would I make this bubble sort more pythonic?

texts:
I have this code:
Sorted=False
while not Sorted:
    Sorted=True
    for x,y in enumerate(List[:-1]):
        if List[x]>List[x+1]:
            List[x],List[x+1]=List[x+1],List[x]
            Sorted=False

However the use of
Sorted=True/False

being repeated is quite ugly and it would be much nicer to write the code is something similar to:
while True:
    for x,y in enumerate(List[:-1]):
        if List[x]>List[x+1]:
            List[x],List[x+1]=List[x+1],List[x]
            break
    else:break

The only problem is that breaking from the loop this early causes the loop to be repeated many more times taking up more time overall. Are there any ways around this to make the code more pythonic or do I just need to leave it as ugly as it is?


texts: Calculate volume of a cylinder with user input

texts:
I'm looking for a fast OR simple way to calculate the volume of a user-entered cylinder.  Here is my solution:

#include <iostream>
using namespace std;
#include <math.h>

int main()
{
    long double pi = acos(-1);
    cout.precision(1000);
    long double radius;
    long double volume;
    long double height;
    cout << "Hello to the cylinder volume solver!" << endl;
    cout << "Please enter the cylinder's radius: ";
    cin >> radius;
    long double radius_sq = radius * radius;
    cout << endl << "Please enter the cylinder's height: ";
    cin >> height;
    volume = pi * radius_sq * height;
    cout << endl << "The cylinder's volume is " << volume << "." << endl;
    return 0;
}

It's obvious to see that I'm a new programmer from the way I wrote this....which is why I want to learn from your remarks.


texts:
I would like to build a common helper for my application that will manage all the amqplib calls from all of my nodeJS microservices.

I would like to import my amqplibHelper to every microservice and use only my helper commands that they will call internally to the amqplib node.js library so I will be able to use different library in the future of to make changes regarding the amqp commands more easily in one central place.

I created a new npm package for that and tried to write something from scratch but since I don't have too much experience in amqp. I am looking for a "bootstrap" or a template as starting point.

I started with this but I feel I am not going in the right way.

class commonAmqp {
   amqp = require('amqplib');
   connection = start();

   constructor(rabbitmqClientm, validQueues) {
      this.rabbitmqClient = rabbitmqClient;
      this.validQueues = validQueues;

      const { queuesLocal, queuesRemote } = rabbitmqClient;
      const isLocal = queuesLocal.includes(queue);
      const isRemote = queuesRemote.includes(queue);
   }

   async initQueue(queue, data) {
      if (!validQueues.includes(queue)) throw HttpError(g.f('Not valid queue'));

      const { connection, queue } = this;
      const valid = queueValidator(queue, data);
      const channel = connection.then(conn => (conn.createChannel()));

      if (!channel || !valid)
        throw new Error('Not valid queue || queue-data');

      channel.then(function(ch) {
        return ch.assertQueue(queue).then(function(ok) {
          return ch.sendToQueue(queue, new Buffer.from(JSON.stringify(data)));
        });
      });

    };

    async start() {

      const connection = await this.amqp.connect(rabbitmqClient.url);
      console.log('Connected to RabbitMQ-server');

      connection.on('error', (err) => {
         console.log('rabbitmq-err', err);
         setTimeout(start, 2000);
      });

      connection.on('close', () => {
         console.log('rabbitmq-connection closed');
         setTimeout(start, 5000);
      });

      return connection;
    }

    config(config) {
       this.config = config;
       console.log('config: ' + this.config);
    }

 }

 module.exports = {
   commonAmqp
};


texts: Simple GUI using tabs to separate application windows

texts:
I'm designing a simple GUI using tabs to separate each 'window' of the application. There are 3 main tabs, each with 2 sub-tabs.

In one class I create the entire hierarchy of panes and panels:

mainPane = new JTabbedPane();
mainPane.setBounds(0, 0, WIDTH, HEIGHT);

//instantiate main tabs, get panes added to them
createTab = new JPanel();
createTab.setLayout(null);

customizeTab = new JPanel();
customizeTab.setLayout(null);

viewTab = new JPanel();
viewTab.setLayout(null);

//instantiate main panes, get sub-tabs added to them
createPane = new JTabbedPane();
createPane.setBounds(0, 0, WIDTH, HEIGHT);

customizePane = new JTabbedPane();
customizePane.setBounds(0, 0, WIDTH, HEIGHT);

viewPane = new JTabbedPane();
viewPane.setBounds(0, 0, WIDTH, HEIGHT);

//instantiate sub-tabs, get elements added to them
createEntityTab = new JPanel();
createEntityTab.setLayout(null);

createDealTab = new JPanel();
createDealTab.setLayout(null);

customizeEntityTab = new JPanel();
customizeEntityTab.setLayout(null);

customizeDealTab = new JPanel();
customizeDealTab.setLayout(null);

viewEntityTab = new JPanel();
viewEntityTab.setLayout(null);

viewDealTab = new JPanel();
viewDealTab.setLayout(null);

//add sub-tabs to main panes
createPane.addTab("Create Entity",null, createEntityTab);
createPane.addTab("Create Deal", null, createDealTab);

customizePane.addTab("Customize Entity", null, customizeEntityTab);
customizePane.addTab("Customize Deal", null, customizeDealTab);

viewPane.addTab("View Entity", null, viewEntityTab);
viewPane.addTab("View Deal", null, viewDealTab);

//add main panes to main tabs
createTab.add(createPane);
customizeTab.add(customizePane);
viewTab.add(viewPane);

//add main tabs to mane pane
mainPane.addTab("Create", null, createTab, "");
mainPane.addTab("Customize", null, customizeTab, "");
mainPane.addTab("View", null, viewTab, "");

and now to add elements to each sub-tab, I would like to do something like this:

new CreateEntity(createEntityTab);
new CreateDeal(createDealTab);

i.e., passing the "sub-tab" and then adding elements in the CreateEntity class.

This seems to work, but my question is the following:

Is using a constructor to pass a JPanel, and then adding elements in the new class considered bad coding?

I know using null in layout is bad practice. It's just for the question.


texts:
I would like to ask for a code review as I feel like it's not the most efficient way of doing it. For context I have a add-ins with all the code in module and then the SheetChangeevent is in ThisWorkbook. Also in the add-ins I have 2 sheets that will have data on it so that the ActiveWorkbook will be able to read this info when running code form module the events will fire and do a vlookup against the sheet in the add-ins.

Private Sub ExcelApp_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim KeyCells As Range
    Dim wsMyList As Worksheet
    Set wsMyList = ThisWorkbook.Sheets(2)

    Set KeyCells = [B3,B5] 'I only need this 2 cells to fire events
    If Sh.Name <> "Response" Then
         If Not Intersect(Target, Sh.Range("B3:B5")) Is Nothing Then 'not too sure how to do it here so I put 3 cells instead of 2
            If Target.Row = 3 Then
                If Range("B3").Value = vbNullString Then Exit Sub
                Application.EnableEvents = False
                If Sh.Range("B3").Value <> vbNullString Then
                    Sh.Range("B4").Value = Application.WorksheetFunction.VLookup(Sh.Range("B3").Value, wsMyList.Range("A:B"), 2, False)
                    Sh.Range("B6").Value = "Type or Select a transaction"
                Else
                    Sh.Range("B4").Value = "Type or Select a program"
                End If
                Columns.ClearColumns
                Transactions.FetchTransactions
                Application.EnableEvents = True
            ElseIf Target.Row = 5 Then
                If Range("B5").Value = vbNullString Then Exit Sub
                Application.EnableEvents = False
                If Range("B5").Value <> vbNullString Then
                    Sh.Range("B6").Value = Application.WorksheetFunction.VLookup(Sh.Range("B5").Value, wsMyList.Range("D:E"), 2, False)
                    Columns.ClearColumns
                    Columns.PopulateFields
                End If
                Application.EnableEvents = True
            End If
        End If
    End If
End Sub


texts: change a string and apply changes to other similar strings

texts:
I'm trying to get the changes that were made in a string and apply them to similar strings.

string are similar if they are equal from 0 to index of change.

let's say I have this strings:

let a = "123.1/1";
let b = "123.1/2";
let c = "124.1/1";

now we make these changes:

let newA = "123.22/1"; // was "123.1/1", indexOfChange = 3 in this case.

then when we want to apply changes to similar strings I want the changes to apply only to similar strings:

a = "123.22/1";
b = "123.22/2";
c = "124.1/1";

The way I tackled it is by taking these steps:

get the index of change by comparing old a with the new value.

let len = max(a.length, newA.length);
let changeStartsAt = 0;
for(let i = 0; i < len; i++){
  if(a[i] != newA[i]){
    changeStartsAt = i;
    break;
  }
}

get the "suffix" (couldn't find a better name for it) and where it starts in a.

let changeOldEndsAt= 0;
let changeNewEndsAt = 0;
let k = a.length - 1;
let j = newA.length - 1;

while(k >= 0 && j >= 0){
  if(a[k] != newA[j]){
    changeOldEndsAt = k;
    changeNewEndsAt = j;
    break;
  }
  k--;j--;
}

get the similar string (as defined above) and apply the changes.

let arr = [a,b,c];
let rep = a.substring(0, changeStartsAt + 1);

for(let str of arr){
  // this is how I defined 'similar'
  if(str.length != str.replace(rep, '').length){
    console.log(
      str.substring(0, changeStartsAt) +
      newA.substring(changeStartsAt, changeNewEndsAt + 1) +
      str.substring(changeOldEndsAt, str.length)
    )
  }
}

Is there a more efficient/"good practice" to achieve this?


texts: Recursive LinkedList. Which implementation is better and why?

texts:
class Node:

    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:

  def __init__(self):
      self.head = None

def insert(self, data):
    self.head = self.insertHelper(self.head, data)

def insertHelper(self, head, data):
    if(head == None):
        return Node(data)
    else:
        head.next = self.insertHelper(head.next, data)
    return head

  or

def insertR(self, data):
    self.insertRHelper(self.head, data)

def insertRHelper(self, head, data):
        if(head == None):
            self.head = Node(data)
        elif(head.next == None):
            head.next = Node(data)
        else:
            self.insertRHelper(head.next, data)

Any reason why one of these implementations would be better? Personally think the insertR version is easier to look at.


texts:
Printing the lyrics of "Twelve Days of Christmas" seems to be a fairly popular programming challenge.

As I've successfully attempted it, I was wondering if the code can be simplified even further (say no loops)?

Any feedback in regards to style and/or logic would be greatly appreciated.

#!/usr/bin/env python3

verses = {
        1: ["first", "and a Partridge in a Pear Tree."],
        2: ["second", "two Turtle Doves, "],
        3: ["third", "three French Hens, "],
        4: ["fourth", "four Calling Birds, "],
        5: ["fifth", "five Gold Rings, "],
        6: ["sixth", "six Geese-a-Laying, "],
        7: ["seventh", "seven Swans-a-Swimming, "],
        8: ["eighth", "eight Maids-a-Milking, "],
        9: ["ninth", "nine Ladies Dancing, "],
        10: ["tenth", "ten Lords-a-Leaping, "],
        11: ["eleventh", "eleven Pipers Piping, "],
        12: ["twelfth", "twelve Drummers Drumming, "]
        }

def get_verses(line):
    verse = f"On the {verses[line][0]} day of Christmas " + \
        "my true love gave to me: "
    for i in range(line, 0, -1):
        verse += f"{verses[i][1]}"
    return verse.replace("and ", "") if line == 1 else verse

def recite(start_verse, end_verse):
    return "\n".join([get_verses(line) for line
            in range(start_verse, end_verse + 1)])

print(recite(1, 12))


texts: Project Euler: #36 Binary and Base 10 Palindromes

texts:
Here is the Euler problem referenced, it says:

  The decimal number, 585 = 1001001001\$_2\$ (binary), is palindromic in both
  bases.

  Find the sum of all numbers, less than one million, which are
  palindromic in base 10 and base 2.

  (Please note that the palindromic number, in either base, may not
  include leading zeros.)

My solution is as follows:

def check_palindrome_base_ten(num):
    a = str(num)
    return a == a[::-1]

def check_palindrome_base_two(num):
    a = str(bin(num))[2:]
    return a == a[::-1]

def check_palindrome(num):
    return check_palindrome_base_ten(num) and check_palindrome_base_two(num)

def sum_palindrome_in_a_range(lower_limit, upper_limit):
    return sum(x for x in xrange(lower_limit, upper_limit+1, 2) if check_palindrome(x))

%timeit sum_palindrome_in_a_range(1,1000000)
1 loops, best of 3: 247 ms per loop

I noticed by the end of the solution after just brute forcing it that the step could be changed to 2 to use only odd numbers because the binary 1st digit should always be 1 if the number was greater than 1 and a palindrome. This cut my execution time in literal half from ~480ms to 247ms.

In addition I thought that perhaps writing mini functions and then running a reverse index on that number would be faster than doing say:

str(a) == str(a)[::-1]

Because I get to avoid running str and bin twice. Is that correct logic?

Are there any such other optimizations that I have missed that I can use to reduce runtime and in general make my code more useful. I feel as though I may be stuck in a for loop / list comprehension trap and perhaps am not thinking creatively enough when approaching these solutions. I'm scared that's going to cause my solutions when I code actual problems to be inefficient. So perhaps it's also a code methodology review in that respect.


texts: Macro to convert an indented hierarchy to a database format

texts:
Our business intelligence suite outputs data as an indented hierarchy, as below:

Level 1            1000
   Level 2a        600
      Level 3a     500
      Level 3b     100
   Level 2b        400
      Level 3c     400

I've written a macro that converts this into a 'database' format, where only rows with the base (most granular) level are preserved, and the parents are listed to the left as below (this way the # column is summable):

   1         2          3         #
Level 1   Level 2a   Level 3a    500
Level 1   Level 2a   Level 3b    100
Level 1   Level 2b   Level 3c    400

The problem I've been running into is that it takes 5-10 minutes to process a file with ~8000 rows. Although my code works, I'm convinced there's a faster way. See below for my code:

Sub Database()

Application.ScreenUpdating = False

Dim WS      As Worksheet
Dim SR      As Range
Dim Rows    As Integer
Dim Indent  As Integer
Dim TR      As Integer
Dim BR      As Integer

Set WS = ActiveWorkbook.ActiveSheet
'StartCell is a function that returns the address of the first cell in the hierarchy
Set SR = WS.Range(StartCell())
Rows = SR.End(xlDown).Row - SR.Row
BR = SR.End(xlDown).Row
TR = SR.Row

'Insert 4 columns & add headers (Level 1, Level 2, etc.)
For x = 0 To 3
    SR.EntireColumn.Insert
    SR.Offset(-1, -1) = "Level " & x + 3
Next x

x = 0
q = 0

'The main code
Do While x < Rows + 1
    'Identifies a row with base-level indentation & sets indent value to this level
    If Left(SR.Offset(x, 0), 5) = "P_PC7" Then
        Indent = SR.Offset(x, 0).IndentLevel
    End If
    i = 0
    'Loop while the indentation level is greater than one
    Do While Indent > 1
        'Move upwards and check whether indentation of new cell is one less than initial cell
        If SR.Offset(x - i, 0).IndentLevel = Indent - 1 Then
            'If so, this cell is the parent of the initial cell - copy it into the appropriate spot to the left of the base level cell
            SR.Offset(x - i, 0).Copy SR.Offset(x, -1 * (6 - Indent))
            'Set new indent level - the next loop will now look for the parent of the new cell
            Indent = SR.Offset(x - i, 0).IndentLevel
        'If indent level is not one less than initial cell, continue moving upward
        Else: i = i + 1
        End If
    Loop
    x = x + 1
Loop

'Remove all rows that are not base-level
For q = BR To TR Step -1
    If WS.Cells(q, 6).IndentLevel <> 5 Then
       WS.Cells(q, 6).EntireRow.Delete
    End If
Next q

WS.UsedRange.IndentLevel = 0

Application.ScreenUpdating = True

End Sub


texts:
I want to get a map of all the fields in a class (aka value object) in a generic way.  The following works fine for me:

class Baz {
  String foo = "foo2"
  int bar = 2

  public Map asMap() {
    def map = [:] as HashMap
    this.class.getDeclaredFields().each {
      if (it.modifiers == java.lang.reflect.Modifier.PRIVATE) {
        map.put(it.name, this[it.name])
      }
    }
    return map
  }
}

But this doesn't feel like the proper way.  Is there a better approach?


texts: Stack implementation using a singly linked list

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

StackList.h:

#ifndef STACKLIST_H
#define STACKLIST_H

#include <iostream>

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

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

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

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

    //destroyStack
    void destroyStack();

    //destructor
    ~StackList();

    //size
    int size() const;

    //push
    void push(int newVal);

    //pop
    void pop();

    //top
    int top() const;

    //empty
    bool empty() const;

private:
    Node * topOfStack;
    int count;
};

#endif

StackList.cpp:

#include "StackList.h"

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

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

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

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

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

    return *this;
}

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

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

    count = 0;
}

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

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

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

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

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

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


texts: Speeding up OpenCL matrix-vector multiplication

texts:
So I'd like to get a performance boost above and beyond standard Julia matrix-vector multiply, using my Intel HD Graphics 4000 1536 MB GPU, but I can't do better than an order of magnitude worse performance.

The kernel I'm using is based on this approach.  I don't know how ArrayFire gets such fast speeds, they're clearly using some sort of black magic, but I don't know what it is.  Anyways here is the test code:

using OpenCL
const cl = OpenCL

function mvmulJulia(M::Int32, N::Int32)
    srand(1)
    A = rand(Float32, M, N)
    x = rand(Float32, N)
    t = @elapsed A * x
    println(t, " seconds for Julia")
    nothing
end

function mvmulGPU(M::Int32, N::Int32, P::Int32)
    @assert N % P == 0

    srand(1)
    TPG = div(N, P)
    A = rand(Float32, M, N)
    x = rand(Float32, N)

    device, ctx, queue = cl.create_compute_context()
    ctx = cl.Context(device)
    queue = cl.CmdQueue(ctx, :profile)

    A_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=A)
    x_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=x)
    y_buff = cl.Buffer(Float32, ctx, :w, M)

    const mvmulkernel = """
    kernel void mvmul(int M,
                        int N,
                        int P,
                        int TPG,
                        const global float *A,
                        const global float *x,
                        global float *y)
        {
            int i = get_global_id(0);
            int j = get_global_id(1);
            int tpg = get_local_id(1);

            local float sums[$(TPG)];
            float sum = 0.0f;

            for (int p=0; p<P; p++)
            {
                sum += A[M * (TPG * p + tpg) + i] * x[TPG * p + tpg];
            }

            sums[tpg] = sum;
            barrier(CLK_LOCAL_MEM_FENCE);

            if (j == 0)
            {
                float sumtotal = 0.0f;
                for (int t=0; t<TPG; t++)
                {
                    sumtotal += sums[t];
                }

                y[i] = sumtotal;
            }
        }
    """

    program = cl.Program(ctx, source=mvmulkernel) |> cl.build!
    kernel = cl.Kernel(program, "mvmul")
    evt = cl.call(queue, kernel, (M, N), (1, P), M, N, P, TPG, A_buff, x_buff, y_buff)

    t = round(evt[:profile_duration] * 1e-9, 6)
    println(t, " seconds on GPU")
    y = cl.read(queue, y_buff)
    println(isapprox(y, A * x))
    nothing
end

M = Int32(4000)
N = Int32(300)
P = Int32(50)

mvmulJulia(M, N)
mvmulGPU(M, N, P)

You can try out different M, N, and P at your leisure.


texts: Multi-threaded utility that logs some audit trails

texts:
I'm trying to write a multi-threaded utility that logs some audit trails to the DB every 30 minutes, or whenever my storage data structure (a list in this case) exceeds a certain limit.

The code works well, but having said that, my manager said there could potentially be some issues in the method LogUserUsageData(...) where one thread tries to add a UserUsage object while another thread is in the lock trying to initialize the same list.

Should I be declaring my list as volatile?
Should I be thinking about double-locking techniques?

Can anybody throw more light on this?

namespace Utilities
{
    public class UserUsageStatistics
    {
        private SynchronizedCollection<UserUsage> _statisticsList;
        private readonly Thread _persistenceThread;
        private readonly string _flag = String.Empty;

        public UserUsageStatistics()
        {
            _statisticsList = new SynchronizedCollection<UserUsage>();
            _persistenceThread = new Thread(ThreadWork);
            _persistenceThread.Start();
        }

        public void LogUserUsageData(UserUsage userUsage)
        {
            if (_statisticsList.Count >= 100) PersistToDataStore();
            _statisticsList.Add(userUsage);
        }

        void ThreadWork()
        {
            while (true)
            {
                PersistToDataStore();
                Thread.Sleep(1800000);
            }
        }

        /// <summary>
        /// Persist the data to the data store.
        /// </summary>
        void PersistToDataStore()
        {
            if (_statisticsList.Count == 0) return;
            try
            {
                SynchronizedCollection<UserUsage> tempList;
                lock (_flag)
                {
                    if (_statisticsList.Count == 0) return;

                    tempList = _statisticsList;
                    _statisticsList = new SynchronizedCollection<UserUsage>();
                }
                //TODO: Save to database
            }
            catch (Exception ex)
            {
            }
        }

    }
}


texts: Getting a substring of a delimited string

texts:
I have some underscore-delimited strings like abc_def_ghi.  I would like to get a substring out of the string made of one or more delimited substrings, so that if I call:

getUnderscoreSubstring("abc_def_ghi",2)

then I get:

abc_def

This is the C# code I'm using:

public string getUnderscoreSubstring(string fullStr,int substringCount)
{
    string[] splitArray = fullStr.Split('_');
    if (substringCount>splitArray.Count())
    {
        return null;
    }
    else
    {
        string output = "";
        for(int c=0;c<substringCount;c++)
        {
            output += splitArray[c];
            if (c<substringCount-1)
            {
                output += "_";
            }
        }
        return output;
    }
}

I'm wondering if there's a simpler way to rewrite this, possibly using extension methods.


texts: Is my code Declarative (RxSwift) ? Please help me to explain why not?

texts:
I'm newbie in Swift and Rx programming. Is my below code is declarative ? If not, please rewrite it and explain to help me more understanding about declarative :( (my English is so bad)

// MARK: RxSwift
func processPhotoApiService(target: PhotoService) -> Observable<[String: Any]> {
    return RxMoyaProvider<PhotoService>().request(target).map { try $0.mapJSON() as! [String: Any] }
}

.....

ApiServiceManager.shared.processPhotoApiService(target: .getNews(consumerKey: ApiConstants.CONSUMER_KEY, page: 1, imageSize: ApiConstants.MEDIUM_IMG_SIZE))
    .map {
        NewsJson(json: $0)!.photos
    } .flatMap { photos in
        Observable.from(photos).flatMap { photo in
            Observable.from(optional: PhotoItem(name: photo.name, URL: photo.imageUrl, viewCount: photo.viewCount, ratingCount: photo.ratingCount))
        }.toArray()
    }.subscribe { event in
    switch event {
    case .next(let dictionary):
        print("onNext:", dictionary)
        break
    case .error(let error):
        print("onOtherError:", error)
        break
    default:
        break
    }
}


texts:
I'm currently processing xml messages with C#. It is working But I'm not confident that my code is fast enough. There are 3 possible messages I can receive. When I receive one the message an event is triggered and I can access the object outside of this thread and do the necessary processing. The method start is running in a separate thread.
    public void Start()
    {
        NameTable nt = new NameTable();
        object frameAck = nt.Add("frameack");
        object alarmResponse = nt.Add("alarmresponse");
        object watchdog = nt.Add("watchdog");
        StreamReader sr = new StreamReader(_tcpClient.GetStream());
        XmlReaderSettings settings = new XmlReaderSettings
        {
            NameTable = nt,
            ConformanceLevel = ConformanceLevel.Fragment
        };
        XmlReader xr = XmlReader.Create(sr, settings);
        while (!_requestStop)
        {
            try
            {
                while (xr.Read())
                {
                    if (xr.NodeType == XmlNodeType.Element)
                    {
                        object localName = xr.LocalName; // Cache the local name to prevent multiple calls to the LocalName property.
                        if (watchdog == localName)
                            OnWatchdogComplete(new CustomEventArgs(xr.ToClassFromXmlStream<WatchdogFrame>()));
                        if (alarmResponse == localName)
                            OnAlarmResponseComplete(new CustomEventArgs(xr.ToClassFromXmlStream<AlarmResponse>()));
                        if (frameAck == localName)
                            OnAckComplete(new CustomEventArgs(xr.ToClassFromXmlStream<FrameAck>()));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        xr.Close();
        sr.Close();
        Console.WriteLine("Stopping TcpXmlReader thread!");
    }

This is my extensionmethod to deserialize to an object.
    public static T ToClassFromXmlStream<T>(this XmlReader xmlStream)
    {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(xmlStream);
    }

When I close the program I always get the errors:

There is an error in XML document (9, 12).
Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.

When I was string processing this it would seem that is was going a lot faster. But it was very complex and this very easy.


texts:
I made a simple Hangman game in Python:
import random

class Hangman:

    def __init__(self):
        self.words = ["bike", "monkey", "planet"]
        self.random_word = random.choice(self.words)
        self.lenght = len(self.random_word)
        self.no_of_try = int(self.lenght) + 3
        self.empty_word = ["_"] * self.lenght

    @staticmethod
    def user_input():
        print("Enter a guess: ")
        user_input = input()
        return user_input

    def find_index(self):
        letter = self.user_input()
        possition = self.random_word.index(letter)
        return (letter, possition)

    def substitue(self):
        try:
            guess_letter, guess_index = self.find_index()
            self.empty_word[guess_index] = guess_letter
            print(self.empty_word)
            return True
        except ValueError as e:
            return False

    def play_game(self):
        while self.no_of_try > 0:
            print("no: " + str(self.no_of_try))
            game = self.substitue()
            if game:
                print("Bravo")
                self.no_of_try -=  1
            else:
                self.no_of_try -=  1
                print("Wrong")

            if "_" not in self.empty_word:
                print("You win")
                break
            if self.no_of_try == 0:
                print("Game over")
                break

if __name__ == "__main__":
    h = Hangman()
    h.play_game()


texts: Return list of common email ids from a list of lists

texts:
Input: ArrayList of ArrayLists with email ids.
Output: Return ArrayList of email ids which appears in each inner ArrayList.

Ex: Input: [[abc@gmail.com, bca@gmail.com],[abc@gmail.com,bca@gmail.com,bca@gmail.com],[abc@gmail.com,xyz@gmail.com]]
Output: [abc@gmail.com]

I have written the code using HashSet and HashMap and could get the required output but I'm not sure how optimized and efficient my method is.

public static List<String> Common(List<List<String>> email1){

        List<String> res= new ArrayList<String>();
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        Set<String> set ;
        int cou = 0;
        for( List list : email1)
        {
            set = new HashSet<String>();
            List<String> temp = list;
            for(String i: temp){
                if(!set.contains(i)){
                    if(map.get(i) !=null){
                        map.put(i, map.get(i)+1);
                    }else{
                        map.put(i, 1);
                    }
                }
            }
            cou++;
        }

        int size = email1.size();

        for(String count: map.keySet()){
            if(map.get(count)== size)
            {
                System.out.println(count);
                res.add(count);
            }
        }

        return res; // << this
    }


texts: Is my async websocket python code correct?

texts:
This is the first time I am posting here, so please go easy on me : ).

I am also writing for the first time python code which uses async / await for streaming web-socket information.

My main goal is to:

Connect to a web-socket
Stream info from web-socket
Continuously save the streaming info somewhere (to DB for example).

My main concerns are:

Whether the code below is streaming information from a web-socket correctly - to be clear: the code is working, but I am not 100% certain it's doing what I want it to do, albeit showing results as expected. There's a lot happening under the hood, hence my concern.
Whether it's also closing the connection to the web-socket.
How to wrap a function over it (i.e. the function that save the data somewhere).

If you see other problems with it, please let me know.

msg = {'message': 'subscribe'}

async def stream_websocket_info():
    async with websockets.connect(WEBSOCKET_URL) as websocket:
        await websocket.send(json.dumps(MESSAGE))
        while True:
            print(await websocket.recv())

# This is how I run it:
asyncio.get_event_loop().run_until_complete(stream_websocket_info())


texts:
For practicing reasons I would like to write a method which inserts a character into a string.

I would like to know:

What is the best practice concerning placement of a comment within methods?  For example, is the way that I commented about what raises an exception fine, or are there better practices?  Would I need more comments, and if so, where?
In this particular example, are throwing unchecked exceptions preferred or checked?
How can I make this method more reliable?
How can I make this method more scalable?
While dealing with immutable strings there are always discussions around performance. Can I make this method run faster?
Is this code thread safe?

/**
 * Inserts the character ch at the location index of string st
 * @param st
 * @param ch
 * @param index
 * @return a new string
 */
    public static String insertCharAt(String st, char ch, int index){
        //1 Exception if st == null
        //2 Exception if index<0 || index>st.length()

        if (st == null){
            throw new NullPointerException("Null string!");
        }

        if (index < 0 || index > st.length())
        {
            throw new IndexOutOfBoundsException("Try to insert at negative location or outside of string");
        }
        return st.substring(0, index)+ch+st.substring(index, st.length());
    }


texts:
The class helps to determine the exact output log message, taking in account the conversionPattern that log4net uses for layout. Current usage is you have to attach the listener, then call your BL or a wrapper method which your code uses to write to log, then call the GetRenderedMessage() method. The purpose is to make sure that even if I modify my wrapper method (I have a wrapper method which adds some properties to log4net's ThreadContext.Properties and also formats the message in a certain way) the rendered log would remain the same. Are there any improvements or suggestions to make it more "friendly" so someone would know how to use it without reading this intro?

using log4net;
using log4net.Appender;
using log4net.Config;
using System;
using System.IO;
using System.Linq;

namespace TestUtils
{
    public class Log4netListener
    {
        MemoryAppender memAppender;

        /// <summary>
        /// Attaches the listener so it would capture any log messages written.
        /// </summary>
        /// <param name="appenderName"></param>
        public void AttachLogListener(string appenderName)
        {
            var appender = LogManager.GetRepository().GetAppenders().Where(a => a.Name == appenderName);
            var patternLayout = ((log4net.Layout.PatternLayout)((AppenderSkeleton)(appender.First())).Layout);
            memAppender = new MemoryAppender();
            memAppender.Layout = patternLayout;
            BasicConfigurator.Configure(memAppender);
        }

        /// <summary>
        /// Gets the message written to log. Use this method only after AttachLogListener() was called
        /// and a message was written to log4net afterwards.
        /// </summary>
        public string GetRenderedMessage()
        {
            if (memAppender == null)
            {
                throw new InvalidOperationException("The listener was not attached. Make sure you call AttachLogListener() before writing to log.");
            }
            var events = memAppender.GetEvents();
            string logMessage = "";
            using (StringWriter writer = new StringWriter())
            {
                foreach (var ev in events)
                {
                    memAppender.Layout.Format(writer, ev);
                }
                logMessage = writer.ToString();
            }
            return logMessage;
        }
    }
}

Usage:

[TestClass]
public class LoggingTests
{
    [AssemblyInitialize]
    public static void Configure(TestContext tc)
    {
        XmlConfigurator.Configure(); // must use this line to make log4net work from test  if "configSource" is used in app.config
    }

    [TestMethod]
    public void LogLayout()
    {
        var listener = new Log4netListener();
        listener.AttachLogListener("MyLogFileAppender");

        // Call business logic here that writes to log...

        string logMessage = listener.GetRenderedMessage();
        // Assert...
    }
}


texts: Wrapping IMemoryCache with SemaphoreSlim

texts:
I need simple caching for one of my web-services so I use the Microsoft.Extensions.Caching.Memory package. I wrapped it with SemaphoreSlim to make sure reading and writing are safe. I'm not sure what I'm doing here is entirely correct. What do you think? Is this wrapper OK or can I turn GetOrCreateAsync into an extension for IMemoryCache and it'll handle everything?

public class CacheService
{
    private static readonly SemaphoreSlim Locker = new SemaphoreSlim(1, 1);

    private readonly IMemoryCache _cache;

    public CacheService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public async Task<T> GetOrCreateAsync<T>(object key, Func<Task<T>> create)
    {
        await Locker.WaitAsync();
        try
        {
            if (_cache.TryGetValue(key, out var entry))
            {
                return (T)entry;
            }
            else
            {
                return _cache.Set(key, await create(), new MemoryCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(17)
                });
            }
        }
        finally
        {
            Locker.Release();
        }
    }
}


texts: Connecting to EC2 instances using the instance name instead of IP

texts:
I'm an intensive user of AWS EC2 instances, many instances are launched, stopped, repurposed, etc.

To connect to any instance using SSH I must keep track of their IPs.

The bash script I wrote (following the question I asked on SO) uses aws-cli to do the heavy lifting for me, leaving me to remember only the logical names I've given to my instances.

Here is the main code, including the auto-completion code:

# connect to machine
function sash {
  if [ -z $1 ]; then
    echo "Please enter machine name"
    return 1
  fi
  local instance ip pem
  instance=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[].[KeyName,PublicIpAddress]' --output text)

  if [ -z "${instance}" ]; then
    echo Could not find an instance named $1
    return 1
  else
    ip=$(echo $instance | awk '{print $2}')
    pem=$(echo $instance | awk '{print $1}')

    echo "Connecting to $1 ($ip)"
    ssh -i ~/.aws/$pem.pem ubuntu@$ip
  fi
}

function clear_sash {
  unset -v _sash_instances
}

# completion command
function _sash {
  if [ -z "${_sash_instances}" ]; then
    _sash_instances="$( aws ec2 describe-tags --filter Name=key,Values=Name Name=resource-type,Values=instance --query Tags[].Value --output text )"
  fi

  local curw
  COMPREPLY=()
  curw=${COMP_WORDS[COMP_CWORD]}
  COMPREPLY=($(compgen -W "${_sash_instances}" -- $curw))
  return 0
}

complete -F _sash sash

The main function (sash) takes the first parameter, and queries aws ec2 for a machine with a 'Name' tag with that value, extracts its public ip and pem file, and calls the proper ssh command.

The auto-completion command (_sash) enumerates the names of all EC2 machines, and keeps them in a cache in the scope of the shell.

A small helper command (clear_sash) is used to clear the cache for the auto-complete.

Since this is the first function I've written in bash, I would love to hear some opinions on the code, style, caching decisions, etc.


texts: Mocking config data in JavaScript unit tests

texts:
I'd really like someone to sanity check my approach for unit testing the summarise() function and mocking its dependencies.

Background

Each option has a set of values, which come from the app state
Options also each have a config, which are defined in configs.js (potentially a large list, with 'dynamic' data-like variations)

The tests

I'm testing the summarise function. To isolate my tests, I've mocked the option configs. This means I don't have to couple the test to certain option configs, which allows settings to be changed freely.

My tests work, but I feel it has a few issues:

I can't directly spy on a config object, so I've exported a function getOptionConfig() which I can spy on. I feel like it would be cleaner to avoid an API; and just spy on the object if possible.
I feel it'd be much cleaner to pass the _optionConfigs object to summarise() (to avoid mocks completely). However, this would only pass the same issue to any functions which call summarise().
Because I'm forcing a return value in the spies, I'm not testing the parameter that I'm passing to getOptionConfig(). Is this bad?

configs.js

const _optionConfigs = {
  exampleOption: {
    type: 'red',
  },
  exampleOption2: {
    type: 'blue',
  },
  exampleOption3: {
    type: 'red',
    exclude: true,
  },
  exampleOption4: {
    type: 'red',
  },
  // ... the list goes on...
};

export const getOptionConfig(id) {
  return _optionConfigs[id];
}

summarise.js

import { getOptionConfig } from './config';

/**
 * Summarise an option's values
 * @param {string} optionName - an option name, used for referencing its config data
 * @param {array} optionValues - application state. values of a particular option
 * @returns {string} a summary of the option's values
 */
export const summarise(optionName, optionValues) {
  const optionConfig = getOptionConfig(optionName);
  if (optionConfig.exclude) {
    return '';
  }
  if (optionConfig.type === 'red') {
    return optionValues.map(value => value + ' with a dash of red').join(', ');
  } else (optionConfig.type === 'blue') {
    return optionValues.map(value => value + ' with a bit of blue').join(', ');
  }
}

summarise.test.js

// ENV - jasmine

import * as configs from './configs';

describe('summarise', () => {
  it('ignores when excluded', () => {
    spyOn(configs, 'getOptionConfig').and.returnValue({
      exclude: true,
      type: 'blue',
    });
    const summary = summarise('testOption3');
    expect(summary).toBe('');
  });
  it('summarises blue types', () => {
    spyOn(configs, 'getOptionConfig').and.returnValue({
      type: 'blue',
    });
    const summary = summarise('testOption2', [
      'Value 1',
      'Value 2',
    ]);
    expect(summary).toBe('Value 1 with a bit of blue, Value 2 with a bit of blue');
  });
  it('summarises red types', () => {
    spyOn(configs, 'getOptionConfig').and.returnValue({
      type: 'red',
    });
    const summary = summarise('testOption', [
      'Value 1',
      'Value 2',
    ]);
    expect(summary).toBe('Value 1 with a dash of red, Value 2 with a dash of red');
  });
});


texts:
I have a process, let's call it Proc1. It is installed in two different directories and one instance of each is running:

C:\DirA\Proc1.exe
C:\DirB\Proc1.exe

When iterating through all currently running processes, I need to be able to differentiate one from the other. I do this by looking at the full path to the process.

Unfortunately, a little piece of documentation from MSDN has forced me to make this code pretty ugly:

MSDN

  If the function fails with ERROR_BAD_LENGTH when called with TH32CS_SNAPMODULE or TH32CS_SNAPMODULE32, call the function again until it succeeds.

Please assume that C++11 is not available for this project.

bool MyClass::IsCorrectPath (const DWORD dwPid, const std::string &strPath) const
{
    DWORD dwError = 0 ;
    NormalHandle hModSnap ; // RAII wrapper for HANDLE

    do {
        hModSnap = ::CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, dwPid) ;
        if (hModSnap == INVALID_HANDLE_VALUE) {
            dwError == ::GetLastError () ;
            if (dwError == ERROR_PARTIAL_COPY) {
                // This occurs when trying to read a 64 bit process from a 32 bit process.
                return false ;
            }

            else if (dwError == ERROR_BAD_LENGTH) {
                // We have to repeatedly call ::CreateToolhelp32Snapshot () if we get this error
                continue ;
            }

            else {
                ThrowFunctionFailure ("MyClass::IsCorrectPath ()",
                    "::CreateToolhelp32Snapshot ()", ::GetLastError ()) ;
            }
        }

    } while ((hModSnap == INVALID_HANDLE_VALUE) && (dwError == ERROR_BAD_LENGTH)) ;

    MODULEENTRY32 me ;
    me.dwSize = sizeof (me) ;
    if (::Module32First (hModSnap.Get (), &me) == FALSE) {
        ThrowFunctionFailure ("MyClass::IsCorrectPath ()", "::Module32First ()", ::GetLastError ()) ;
    }

    return (::_stricmp (strPath.data (), me.szExePath) == 0) ;
}


texts: Python to write multiple dataframes and highlight rows inside an excel file

texts:
I am trying to write multiple dataframes into an excel file one after another with the same logic. Nothing changes for any of the data frame, except the number of columns or number of records. The functions are still the same.

For example,

writer = pd.ExcelWriter(OutputName)
Emp_ID_df.to_excel(writer,'Sheet1',index = False)
Visa_df.to_excel(writer,'Sheet2',index = False)
custom_df_1.to_excel(writer,'Sheet3',index = False)
writer.save()

Now then, once written I am trying to highlight a row if any of the Boolean column has False value in it. There is no library in anacondas that I am aware of can highlight cells in excel. So I am going for the native one.

from win32com.client import Dispatch #to work with excel files
Pre_Out_df_ncol = Emp_ID_df.shape[1]
Pre_Out_df_nrow = Emp_ID_df.shape[0]
RequiredCol_let = colnum_num_string(Pre_Out_df_ncol)
arr = (Emp_ID_df.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows = np.arange(1, len(Emp_ID_df)+ 1)[arr].tolist()

Pre_Out_df_ncol_2 = Visa_df.shape[1]
Pre_Out_df_nrow_2 = Visa_df.shape[0]
RequiredCol_let_2 = colnum_num_string(Pre_Out_df_ncol_2)
arr_2 = (Visa_df.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows_2 = np.arange(1, len(Visa_df)+ 1)[arr_2].tolist()

Pre_Out_df_ncol_3 = custom_df_1.shape[1]
Pre_Out_df_nrow_3 = custom_df_1.shape[0]
RequiredCol_let_3 = colnum_num_string(Pre_Out_df_ncol_3)
arr_3 = (custom_df_1.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows_3 = np.arange(1, len(custom_df_1)+ 1)[arr_3].tolist()

xlApp = Dispatch("Excel.Application")
xlwb1 = xlApp.Workbooks.Open(OutputName)
xlApp.visible = False
print ("\n...Highlighting the Output File at " + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

for i in range(len(ReqRows)):
   j = ReqRows[i] + 1
   xlwb1.sheets('Sheet1').Range('A' + str(j) + ":" + RequiredCol_let + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet1').Columns.AutoFit()

for i in range(len(ReqRows_2)):
   j = ReqRows_2[i] + 1
   xlwb1.sheets('Sheet2').Range('A' + str(j) + ":" + RequiredCol_let_2 + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet2').Columns.AutoFit()

for i in range(len(ReqRows_3)):
   j = ReqRows_3[i] + 1
   xlwb1.sheets('Sheet3').Range('A' + str(j) + ":" + RequiredCol_let_3 + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet3').Columns.AutoFit()

At last, I am changing the name of the sheet

xlwb1.Sheets("Sheet1").Name = "XXXXA"
xlwb1.Sheets("Sheet2").Name = "XXXXASDAD"
xlwb1.Sheets("Sheet3").Name = "SADAD"
xlwb1.Save()

Now there are a few problems here

1) My number of dataframe increases and which means I am writing up the same code again and again.

2) The highlighting process works but it is too slow. Sometimes 90 % of the rows needs to be highlighted. There are 1 million rows and doing them one after another takes 35 minutes.

Kindly help me with this.


texts:
I wrote a small webserver using flask and python to test the response of a program. When the user try to login the program sends to the server a xml file with the data and if everything works, returns a xml file and a cookie if something goes wrong it returns a xml file with the error.

I am new on all this and would like to get some opinion on what I did and maybe how I could improve.

import uuid
import hashlib
from flask import Flask, request, make_response, redirect
import xmltodict
from xml.etree import ElementTree as xml

Server = Flask(__name__)

_email = 'email@email.com' #email to be sent via xml to test
_password = 'keineahnung'  #password to be sent via xml to test

#if one of the values above does not match the values sent through the xml
#file
#the method LoginError will be called and the xml file loginError will be
#sent as response

@Server.route('/', methods=['GET'])
# This is a test I wanted to implement to check via browser if I can
#redirect the user to the login page

def api_root():

    for name in request.cookies:

    #search if the cookie with the user email already exists

    value = request.cookies.get('sessionid')
    if  value ==  hashlib.md5(_email.encode('utf')).hexdigest():
        print('Logged')

        return 'Welcome back, '+_email

return redirect('/login', code=302)

@Server.route('/login', methods = ['GET','POST'])
def Login():

if request.method == 'GET':
#Test the cookie session via browser
    return LoginPassed(_email)
#Pass automatically the right email so the cookie can be created
else:

    xmlFile = xmltodict.parse(request.data) #Converts the xml to json dict
    user = xmlFile['LOGIN']['BENUTZER']
    password = xmlFile['LOGIN']['PASSWORT']

for name in request.cookies:
#search if the cookie with the user email already exists

    value = request.cookies.get('sessionid')
    if  value ==  hashlib.md5(user.encode('utf')).hexdigest():
        print('Logged')
        redirect('/loginPassed.xml', code=302)
        return 'Welcome back, '+user
    return LoginError()

#if a post request is made the login file is decoded into a json dictionary
#the user email and password sent through the file are checked against the
_email and _password constant values

if request.method == 'POST':
    if user == _email:
        if password == _password:
            return LoginPassed(user)
    return LoginError()

#if email or password does not match this function will be called
# a loginError.xml will be returned

@Server.route('/loginError.xml', methods=['GET', 'POST'])
def LoginError():
    print('Login Failed')
    redirect('/loginError.xml', code=302)
    response = make_response(open('LoginError.xml').read())
    response.headers["Content-type"] = "text/xml"
    return response

#If login data is correct the app.route delivers the loginPassed.xml file
# and creates a new session_id and cookie for the user

@Server.route('/loginPassed.xml', methods=['GET', 'POST'])
def LoginPassed(user):
    print('Loged w success')
    _cookieExpireOn = 60 #cookie expires in 60 seconds
    sessionid = hashlib.md5(user.encode('utf')).hexdigest()
    #generates the session id for the cookie
    response = make_response(open('LoginPassed.xml').read())

    response.headers["SESSION"] = sessionid
    #includes the session on the header
    response.set_cookie('sessionid', sessionid, path= '/login',
    max_age=_cookieExpireOn, secure=False, httponly=True)
    #creates the session cookie using email
    return response

#initializes the app
if __name__ == '__main__':

Server.run(host='0.0.0.0', port=80)

This doesn't need to work via webbrowser

P.S:Thanks for the critics and suggestions to improve. I am trying to learn software development and it is really important for me all that help with get here from all of you.


texts:
I pretty sure it should be shoter solution.

(defun modulename-vinlist(val lst)
  "Check if value in list"
  (let ((res "no"))
    (let (vv)
      (dolist (pi lst vv)
        (when (string-equal pi val)
          (setq res "yes")
          (return))
        (setq vv (cons pi vv))))
    (when (string-equal res "yes")
      t)))


texts: Merge three ByteArrays together and then split resulting ByteArrays

texts:
I have a ByteArray value as avroBinaryValue , Schema Id value as short schemaId and Last Modified Date value as lastModifiedDate in long.

short schemaId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] avroBinaryValue = os.toByteArray();

Now, I will write schemaId , lastModifiedDate and avroBinaryValue together into a single ByteArray and then deserialize that final ByteArray value to extract schemaId , lastModifiedDate and avroBinaryValue from it.

Below is the code, I have got so far...

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

    String os = "whatever os is";
    byte[] avroBinaryValue = os.getBytes();

    long lastModifiedDate = 1379811105109L;
    short schemaId = 32767;

    ByteArrayOutputStream byteOsTest = new ByteArrayOutputStream();
    DataOutputStream outTest = new DataOutputStream(byteOsTest);
    outTest.writeShort(schemaId); // first write schemaId
    outTest.writeLong(lastModifiedDate); // second lastModifiedDate
    outTest.writeInt(avroBinaryValue.length); // then attributeLength
    outTest.write(avroBinaryValue); // then its value

    byte[] allWrittenBytesTest = byteOsTest.toByteArray();

    DataInputStream inTest = new DataInputStream(new ByteArrayInputStream(allWrittenBytesTest));

    short schemaIdTest = inTest.readShort();

    long lastModifiedDateTest = inTest.readLong();

    int sizeAvroTest = inTest.readInt();
    byte[] avroBinaryValue1 = new byte[sizeAvroTest];
    inTest.read(avroBinaryValue1, 0, sizeAvroTest);

    System.out.println(schemaIdTest);
    System.out.println(lastModifiedDateTest);
    System.out.println(new String(avroBinaryValue1));

    writeFile(allWrittenBytesTest);
}

I am trying to see whether there is any efficient way of doing this in Java or this is the only correct way of doing it in Java?

The way I am serializing all the three ByteArrays into one ByteArray and the way I am deserializing the resulting ByteArrays to extract the schemaId, lastModifiedDate, avroBinaryValue looks correct or not?


texts: Calculating the posterior distribution in multivariate Gaussian processes

texts:
Matlab profiler throws this horrible bottleneck which is called 700000 times:

for k =1:model.nlf,
    for r =1:model.nlf,
        KuyDinvKyu = zeros(model.k,model.k);
        for q =1:model.nout,
            KuyDinvKyu = KuyDinvKyu + model.KuyDinv{k,q}*model.Kyu{q,r};
        end
        if (k == r)
            model.A{k,r} = model.Kuu{k} + KuyDinvKyu;
        else
            model.A{k,r} = KuyDinvKyu;
        end
    end
end

Even if the math is correct, there must be a faster way.


texts:
The code below is a good representation of my coding skills.  I've been at it for about 6 months.  What I am interested in is ways to make the following program faster.  I currently have the urlrequests threaded to pull information for 500 stocks, but it is still too slow (around 30 seconds).  What python techniques can I use to make this program more efficient?

Thanks!

from urllib.request import urlopen
from csv import reader
from threading import Thread

class StockQuote():
    """gets stock data from Yahoo Finance"""

    def __init__(self, quote):
        self.quote = quote

    def lastPrice(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=l1'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def volume(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=v0'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def yearrange(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=w0'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def PEratio(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=r0'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def bookValue(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=b4'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def EBITDA(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=j4'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def PEGRatio(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=r5'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

    def ticker(self):
        url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f=s0'.format(ticker=self.quote)
        return bytes.decode((urlopen(url).read().strip()))

class StockData(Thread):

    def __init__(self, stk, fileobj):
        Thread.__init__(self)
        self.stk = stk
        self.fileobj = fileobj

    def run(self):
        try:
            stkObj = StockQuote(self.stk)
            stkdata= {}
            stkdata['Ticker'] = stkObj.ticker()
            stkdata['Price'] = stkObj.lastPrice()
            stkdata['PE Ratio'] = stkObj.PEratio()
            stkdata['Volume'] = stkObj.volume()
            stkdata['Year Range'] = stkObj.yearrange()
            stkdata['Book Value per Share'] = stkObj.bookValue()
            stkdata['EBITDA'] = stkObj.EBITDA()
            stkdata['PEG Ratio'] = stkObj.PEGRatio()
        except Exception:
            pass
        self.fileobj.write(str(stkdata))

def openSP500file():
    SP500 = reader(open(r'C:\Users\test\Desktop\SP500.csv', 'r'), delimiter=',')
    printlist = open(r'C:\Users\test\Desktop\SP500prices.txt', 'w')
    for x in SP500:
        indStk = x[0]
        t1 = StockData(indStk, printlist)
        t1.start()

def main():
    openSP500file()

if __name__ == '__main__':
    main()


texts:
Problem Statement

  You are given time in AM/PM format. Convert this into a 24 hour format.

  Note Midnight is \$ 12:00:00AM \$ or \$ 00:00:00 \$ and 12 Noon is \$ 12:00:00PM. \$

Input Format

  Input consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM
  where
  \$ 01 \le hh \le 12 \$,
  \$ 00 \le mm \le 59 \$,
  \$ 00 \le ss \le 59 \$

Output Format

  You need to print the time in 24 hour format i.e. hh:mm:ss
  where

  \$ 00 \le hh \le 23 \$,
  \$ 00 \le mm \le 59 \$,
  \$ 00 \le ss \le 59 \$

Sample Input

  \$ 07:05:45PM \$

Sample Output

  \$ 19:05:45 \$

Solution

class AbsTime(object):

    def __init__(self, hh, mm=0, ss=0, pm=False):
        self.hh = hh
        self.mm = mm
        self.ss = ss
        self.pm = pm

    def add(self, time):
        self.hh += time.hh
        self.mm += time.mm
        self.ss += time.ss

        if self.ss >= 60:
            self.ss -= 1
            self.mm += 1
        if self.mm >= 60:
            self.mm -= 1
            self.hh = self.hh % 24
        return self

    def midnight(self):
        return not self.pm and str(self) in ['00:00:00', '12:00:00']

    def noon(self):
        return self.pm and str(self) == '12:00:00'

    def __str__(self):
        return "{0:02d}:{1:02d}:{2:02d}".format(self.hh, self.mm, self.ss)

    def get(self):
        if self.midnight():
            return AbsTime(0)
        if self.noon():
            return AbsTime(12)
        if self.pm:
            if self.hh == 12:
                hh = self.hh
            else:
                hh = self.hh + 12
            return AbsTime(hh, self.mm, self.ss)
        else:
            return AbsTime(self.hh % 12, self.mm, self.ss)

    @classmethod
    def create_from_string(cls, time):
        pm = True if time[-2:] == 'PM' else False
        hh, mm, ss = map(int, time[:-2].split(':'))
        return cls(hh, mm, ss, pm)

def main(time):
    if time == '00:00:00':
        return time

    abstime = AbsTime.create_from_string(time)
    return abstime.get()

if __name__ == '__main__':
    TIME = raw_input().strip()
    print main(TIME)
    #print main('00:00:00')   #00:00:00
    #print main('12:00:00PM') #12:00:00
    #print main('12:00:00AM') #00:00:00
    #print main('02:00:00PM') #14:00:00
    #print main('02:00:00AM') #02:00:00
    #print main('11:59:00AM') #11:59:00
    #print main('12:59:00PM') #12:59:00
    #print main('01:00:00PM') #13:00:00
    #print main('11:59:59PM') #23:59:59
    #print main('12:59:59AM') #00:59:59

It really took me a while to do this simple solution, its fast when we do just structural programming but once I thought to step into OOP world things really got confusing. How can I improve this design?


texts: Enclosing Circle Problem implementation in Haskell

texts:
I implemented the algorithm by Pr. Chrystal described here in Haskell so could someone please tell me: Do i have implemented this algorithm correctly?
Initial calling of findPoints takes the first and second point of convex hull and the list of points on convex hull.

My second question is: I am trying to solve the problem on sphere online judge [link of problem in code below, because I can not post more than 2 links] using this algorithm but I'm getting the wrong answer.
The code for the problems is on ideone. Why am I getting the wrong answer.

--http://www.spoj.pl/problems/QCJ4/
findAngle :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> Point  a  -> ( Point a , Point a , Point  a , a )
findAngle u@(P x0 y0 ) v@(P x1 y1 ) t@(P x2 y2)
| u == t || v == t = ( u , v , t , 10 * pi )  -- two points are same so set the angle more than pi
| otherwise =  ( u , v, t , ang ) where
        ang = acos ( ( b + c - a ) / ( 2 * sb * sc ) ) where
        b = ( x0 - x2 ) ^ 2 + ( y0 - y2 ) ^ 2
        c = ( x1 - x2 ) ^ 2 + ( y1 - y2 ) ^ 2
        a = ( x0 - x1 ) ^ 2 + ( y0 - y1 ) ^ 2
        sb = sqrt b
        sc = sqrt c

findPoints :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> [ Point  a ] -> ( Point a , Point a , Point a , a )
findPoints u v xs
  | 2 * theta >= pi   =     ( a , b , t , theta )
  | and [ 2 * alpha <= pi , 2 * beta <= pi ]   = ( a , b , t , theta )
  | otherwise = if 2 * alpha > pi then findPoints v t xs else findPoints u t xs
     where
       ( a , b , t , theta ) = minimumBy ( \(_,_,_, t1 ) ( _ , _ , _ ,t2 ) -> compare  t1 t2 ) . map ( findAngle u v )  $ xs
       ( _ , _ , _ , alpha ) = findAngle v t u  --angle between v u t angle subtended at u by v t
       ( _ , _ , _ , beta ) = findAngle u t v   -- angle between u v t angle subtended at v by  u t


texts:
This is my first C program and I'm just looking for some constructive criticism before I start trying to do more with it. Am in quite unfamiliar territory here and am uncertain if I'm releasing all my resources, handling errors, and whatnot "properly".

#include <errno.h>
#include <share.h>
#include <stdbool.h>
#include <stdio.h>

#define BUFFER_SIZE 4096
#define DATA_FILE_NAME "X"

static inline bool fillBuffer(FILE *, char [], size_t *, size_t *);
static inline bool nextCharEquals(FILE *, char [], size_t *, size_t *, char);

int main(void) {
    char buffer[BUFFER_SIZE];
    FILE *dataFile = NULL;
    size_t numBytesRead = 0;
    size_t numBytesUsed = 0;
    size_t statusCode = 0;

    dataFile = _fsopen(DATA_FILE_NAME, "rbS", _SH_DENYWR);

    if (!dataFile) { goto error; }

    while ((numBytesUsed < numBytesRead) || fillBuffer(dataFile, buffer, &numBytesRead, &numBytesUsed)) {
        char c = buffer[numBytesUsed++];

        if (('\n' == c) || ('\r' == c)) {
            if ((c == '\r') && nextCharEquals(dataFile, buffer, &numBytesRead, &numBytesUsed, '\n')) {
                numBytesUsed++;
            }

            continue; // TODO: something useful...
        }
    }

error:
    if (errno) {
        strerror_s(buffer, BUFFER_SIZE, errno);
        fprintf(stderr, "%s\n", buffer);

        statusCode = -1;
    }

exit:
    if (dataFile) {
        fclose(dataFile);
    }

    return statusCode;
}

static inline bool fillBuffer(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed) {
    *numBytesRead = fread(buffer, 1, BUFFER_SIZE, file);
    *numBytesUsed = 0;

    return (0 < *numBytesRead);
}
static inline bool nextCharEquals(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed, char value) {
    return (((*numBytesUsed < *numBytesRead) || fillBuffer(file, buffer, numBytesRead, numBytesUsed)) && (buffer[*numBytesUsed] == value));
}


texts:
I'm working on a game in C#, this game generate new chunk (infinite) when you move around. If I have > 1000 chunks in my list then it become laggy even though I only load the necessary chunks on my screen. Tried all things to improve the code but it did not improve.

Stopwatch ChunkDetect = new Stopwatch();
List<Chunks> allChunks = new List<Chunks>();
public readonly int sizeChunk = 800;

private void loadChunks()
{
    ChunkDetect.Restart();
    ChunkDetect.Start();
    int CamXCh = Convert.ToInt32(Math.Ceiling(-Convert.ToDouble(CameraX) / sizeChunk)),
        CamYCh = Convert.ToInt32(Math.Ceiling(-Convert.ToDouble(CameraY) / sizeChunk));

    int sizeX = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(gameBox.Width) / sizeChunk)) + 4,
        sizeY = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(gameBox.Height) / sizeChunk)) + 4;

    Random generation = new Random();
    // Load Chunks or Create
    for (int chunkX = 0; chunkX < sizeX; chunkX++)
    {
        for (int chunkY = 0; chunkY < sizeY; chunkY++)
        {
            int xChunk = chunkX + CamXCh - 2,
                yChunk = chunkY + CamYCh - 2;

            Chunks currentChunk = allChunks.Where(i => i.positionX == xChunk && i.positionY == yChunk).FirstOrDefault();

            bool isLoad = true;
            if (chunkX == 0 || chunkX == (sizeX - 1) || chunkY == 0 || chunkY == (sizeY - 1))
                isLoad = false;

            if (currentChunk == null)
            {
                Color ColorBiome = Color.FromArgb(64, 233, 56);
                string BiomeName = "Grass";
                allChunks.Add(new Chunks(xChunk, yChunk, sizeChunk, ColorBiome, BiomeName, isLoad, 40));
            }
            else
            {
                bool isCurrentLoaded = currentChunk.isLoaded;
                if (!isLoad)
                    currentChunk.isLoaded = false;
                else if (!isCurrentLoaded)
                    currentChunk.isLoaded = true;
            }
        }
    }
    ChunkDetect.Stop();
}

class Chunks
{
    public Color biomeType;
    public Guid uid;
    public bool isLoaded;
    public int positionX, positionY, Size;
    public string biomeName;
    public List<CeldsChunk> MapChunk;

    public Chunks(int x, int y, int size, Color biome, string BiomeName, bool loaded, int sizeCeld)
    {

        // Identificador
        this.uid = new Guid();

        // Posición y tamaño
        this.positionX = x;         // Position
        this.positionY = y;         // Position
        int cSize = this.Size = size;         // Size

        // Bioma
        this.biomeType = biome;      // Biome Color
        this.biomeName = BiomeName;  // Name of Biome

        // Propiedades
        this.isLoaded = loaded;      // If chunk is loaded

        int sizeChunkInCeld = (cSize / sizeCeld);

        List<CeldsChunk> celdsToChunk = new List<CeldsChunk>();

        Random rd = new Random();
        for (int CeldX = 0; CeldX < sizeChunkInCeld; CeldX++)
        {
            for (int CeldY = 0; CeldY < sizeChunkInCeld; CeldY++)
            {
                celdsToChunk.Add(new CeldsChunk(new Point(CeldX, CeldY, sizeCeld), this.biomeType));
            }
        }

        this.MapChunk = celdsToChunk;
    }

    public void changeLoaded(bool g)
    {
        this.isLoaded = g;
    }

}


texts: Outputting every second char in half string

texts:
My algorithm works but it is too slow.
I have to ask for help with improving this algorithm because the website which checks this, kicks me for too slow execution.
What should I improve here ?

Details:

  Given a sequence of 2*k characters, please print every second
  character from the first half of the sequence. Start printing with the
  first character.

  Input In the first line of input your are given the positive integer t
  (1<=t<=100) - the number of test cases. In the each of the next t
  lines, you are given a sequence of 2*k (1<=k<=100) characters.

  Output For each of the test cases please please print every second
  character from the first half of a given sequence (the first character
  should appear).

Example

  Input:

4
your
progress
is
noticeable

  Output:

y
po
i
ntc

class Chars{

    public static void main (String[] args) {

        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        if (t <= 100 && t >= 1) {
            for (int i = 0; i < t; i++) {
                calculate();
            }
        }
    }

    private static void calculate() {

        Scanner sc = new Scanner(System.in);
        String rawString = sc.nextLine();
        StringBuilder afterAdd = new StringBuilder();
        StringBuilder finishChars = new StringBuilder();
        int numberOfChars = rawString.length();
        if (numberOfChars <= 100 && numberOfChars >= 1) {
            if (numberOfChars % 2 == 0) {
                int numHalfChars = numberOfChars / 2;
                for (int i = 0; i < numHalfChars; i++) {
                    afterAdd.append(rawString.charAt(i));
                }
                if (afterAdd.length() <= 2) {
                    System.out.println(afterAdd.charAt(0));
                } else {
                    for (int i = 0; i < afterAdd.length(); i = i + 2) {
                        finishChars.append(afterAdd.charAt(i));
                    }
                    System.out.println(finishChars);
                }
            }
        }
    }
}

after improve:

class Algorithm{

    private static List<String> results = new ArrayList<>();

    public static void main (String[] args) {
        calculate();
        show();
    }

    private static void show() {
        for (String result : results) {
            System.out.println(result);
        }
    }

    private static void calculate() {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        if (t <= 100 && t >= 1) {
            for (int i = 0; i <= t; i++) {
                String rawString = sc.nextLine();
                StringBuilder finishChars = new StringBuilder();
                int numberOfChars = rawString.length();
                if (numberOfChars <= 100 && numberOfChars >= 1 && numberOfChars % 2 == 0) {
                    for (int j = 0; j < rawString.length() / 2; j = j + 2) {
                        finishChars.append(rawString.charAt(j));
                    }
                    results.add(String.valueOf(finishChars));
                }
            }
        }
    }
}


texts:
At first I thought this was going to be easy, but the asynchronous Node.js really made things difficult for me. Currently, my tracker only features one coin and the address is hard-coded.

I plan to put this on a server with a far greater selection of coins and other user input. But for that I want the code to be cleaner and faster (if possible).

While making this I often stumbled over the same stones:

How to make Node.js execute code one after another once it's finished.
How to make sure the timestamp gets added to the right object.
How to write out my object to a file only when all data is gathered!

As you can see, I somewhat managed to accomplish step 1 and 2 but I failed at 3.

The structure is as follows:

Go to ubiqscan to get a sum of all transactions made
Iterate over the resulting html and save the data into an object
Get the block's timestamp via the API and add it to the corresponding object
When all is done write the object to a JSONfile

I hope I can get some tips on how to structure or approach this task. Every time I sat down to rewrite this I found myself using the same approach!

App.js

var Promise = require('bluebird')
var request = Promise.promisifyAll(require("request"), {multiArgs: true})
var fs = require('fs')

var blockUrl = 'https://ubiqscan.io/api/v1/getblockarray/'
var txUrl = "https://ubiqscan.io/api/v1/getaddresstxns/0x49cbb931773e446ac665c9b61955b35aab56fa95"
var tempJson = {}

request.getAsync(txUrl).spread(function(response, body){
    console.log('Fetchin tx data: Start')
    var jsonData = JSON.parse(body)
    for (var index = 0; index < jsonData.length; index++) {
        tempJson[index] = {
            val: jsonData[index].value,
            block: jsonData[index].blockNumber,
            time: "placeholder"
        }
    }
    console.log('Fecthing tx data: Complete!')
}).then(function () {
    console.log('Fetchin Block data: Start')
    for (var i in tempJson) {
        var url=blockUrl+tempJson[i].block
        addTimestamp(url,i)
    }
    console.log('Fecthing Block data: Complete!')
 })

 function addTimestamp (url, index,) {
    request(url,function (error, response, html){
        //check for errors
        if(!error && response.statusCode == 200){
             var jsonData = JSON.parse(html.slice(1,-1))
            tempJson[index].time = jsonData.timestamp
            console.log(index)
            fs.writeFileSync('out.json',JSON.stringify(tempJson))
        }
    })
}


texts: Split a string based on a delimiter in C

texts:
Basically, this code splits a string into substrings based on a token. The printf call is just a placeholder for something useful for each substring and can be substituted for something else, like a spell checker, profanity checker, etc...

With the input ("The quick brown fox jumps over the lazy dog", 44, ' ') the output is:

Processed: The
Processed: quick
Processed: brown
Processed: fox
Processed: jumps
Processed: over
Processed: the
Processed: lazy
Processed: dog

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sal.h>

/**
 * Splits a string into substrings delimited by a token.
 * Returns the number of substrings found in the string.
 */
size_t __cdecl splitstring(
    _In_reads_or_z_(len) char *str,
    _In_ size_t len,
    _In_ char token
)
{
    char *temp = malloc(len + 1), *p = str, *q = str;
    memset(temp, 0, len);
    size_t i, cnt = 0;
    if (!temp)
    {
        _wperror(L"malloc");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < len + 1; i++)
    {
        if (str[i] == token || str[i] == '\0')
        {
            q = &str[i];
            strncpy_s(temp, len, p, q - p);
            printf("Processed: %s\n", temp);
            memset(temp, 0, len);
            cnt++;
        }
        // Useful property of boolean expressions in C: they are always either 1 or 0
        // Adjust p to point either to the next space or the next letter depending on if
        // it's the first word being processed.
        p = q + (p != &str[0]);
        if (!*p) break;
    }

    free(temp);
    temp = NULL;

    return cnt;
}


texts: Quicksort in JavaScript assuming an immutable array

texts:
Update: further succinct versions below (inspired by Haskell)

Quick sort in JS assuming an immutable array:

    const reorder = (arr, pivot) => {
      let larger = []
      let smaller = []
      let equals = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] < arr[pivot]) {
          smaller.push(arr[i])
        } else if (arr[i] > arr[pivot]) {
          larger.push(arr[i])
        } else {
          equals.push(arr[i])
        }
      }
      return {
        smaller: smaller,
        equals: equals,
        larger: larger
      }
    }

    const sort = (arr) => {
      if (arr.length <= 1) {
        return arr
      }
      const pivot = Math.floor(arr.length / 2)
      const result = reorder(arr, pivot)
      return [...sort(result.smaller), ...result.equals, ...sort(result.larger)]
    }

    console.log(sort([3, 1, 1, 1, 2]))

PS: I deleted the question posted earlier, thinking the algo was wrong, but then I realized a small tweak corrected it. The present code is based on comments received on earlier question.

Update:
Inspired by Haskell, here is a more succinct version using ES6:

const qsort = (arr) => {
  if(arr.length == 0) {
    return []
  }
  let [x,...xs] = arr
  let smaller = xs.filter(v => v <=x)
  let larger = xs.filter(v => v > x)
  return [...qsort(smaller),x,...qsort(larger)]
}

OR simplified further:

const qsort = ([x,...xs]) => {
  return x == undefined ? [] :
  [...qsort(xs.filter(v => v <=x)),x,...qsort(xs.filter(v => v > x))]
}

qsort([3,3,8,1,23,4,5,6,9,9,1,0,45,5,10])


texts:
I'm sort of at a loss for what to do with webapps and whether what I'm doing is actually allowed or not. Here is a sample of the type of thing I'm doing at the moment. I need a list that is accessible by essentially everything.

global_list = []

@bottle.route('/')
def index():
    global_list.append(4)

@bottle.route('/test')
def test():
    return len(global_list)

@bottle.run(port='8080')

The problem (or what I think is a problem) is that it feels wrong and I've been told it is unsafe to use a global variable. This code works perfectly fine, but is there a better or safer way to handle this? Even with multiple clients at the same time, the data in the list currently does not get corrupted. What kind of issues am I going to run into if I keep using this?


texts: Search a list recursively and return the index of the smallest value

texts:
I was asked to define a function that takes a list as an argument and returns the index of the smallest value.

This is what I came up with:

def index_finder(lst):
    """
    parameters: lst of type list
    returns: index of the lst's smallest value
    """
    for i in range(len(lst)):
        if lst[i]==index(lst):
            print(i)
    return None

def index(lst):
    """
    parameters: lst of type list
    returns: the smallest value of that lst
    """
    if len(lst)==1:
        return lst[0]
    if lst[0]<lst[1]:
        lst.append(lst[0])
    return index(lst[1:])

index_finder([3,2,4,0,1,5,-6,2,5])

This will output the following:

6

As you can see I had to use separate functions in order to get the result. Is there a concise, yet simple way to do this?

By concise I mean short and by simple I mean using only simple functions.


texts:
I want to replace the fifth space in a sentence with a new line. Sample input:

"Hi this is empty string. This should be in new line!"

Expected output:

"Hi this is empty string.
This should be in new line!"

I'm getting the expected output with this code, but I need to know, is this the optimized solution or there are any better solution than this?
    string s = "Hi this is empty string. This should be in new line!", t = "";
    int countSpaces = s.Count(Char.IsWhiteSpace);
    if (countSpaces > 3)
    {
        int count = 0;
        char n;
        foreach (char c in s)
        {
            if (c == ' ') count++;
            if (count == 5)
            {
                n = '\n';
                count++;
            }
            else n = c;
            t += n;
        }
    }
    else t = s;
    MessageBox.Show(t);


texts: Majorly refactored my code, is this good enough?

texts:
namespace SharpDream.Api
{
    public enum SourceType
    {
        Test,
        Xml
    }

    public class UserFinder
    {
        private IUserInformationSource _sourceType;
        private IParser _parserType;
        private string _source;

        public UserFinder(SourceType sourceType)
        {
            switch (sourceType)
            {
                case SourceType.Test:
                    var testSource = new TestSource();
                    _sourceType = testSource;
                    break;
                case SourceType.Xml:
                    var xmlSource = new XmlSource();
                    var xmlParser = new XmlParser();
                    _sourceType = xmlSource;
                    _parserType = xmlParser;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// Returns a User object loaded with information.
        /// </summary>
        /// <param name="forumUserId">The DIC forum users ID number.</param>
        /// <returns>A User object.</returns>
        public User GetUserById(int forumUserId)
        {
            _source = _sourceType.GetResponseSource(forumUserId);
            return _parserType.ParseUserFromSource(_source);
        }
    }
}

What I'm aiming for:

Separation of concerns. Which is working believe it or not! It's so refreshing to feel confident that your code won't break if you change something somewhere else. I finished this bit, and now I can work on the parsing area without having to put anything else in the mental buffer.
Flexibility during usage.

Here is an example of how my library will be used:

UserFinder userFinder = new UserFinder(SourceType.Xml);
var foundUser = userFinder.GetUserById(1);

Compare this to the old version of the library:

//Let's create an XmlMemberFinder, since we'll use the XML api as our data source.
XmlMemberFinder xmlMemberFinder = new XmlMemberFinder();

//MemberList is the class you'll use in your application to get anything you need
//relating to members.
MemberLister memberList = new MemberLister(xmlMemberFinder);

//This is an example of fetching and listing a user.
var member = memberList.FindMember(1);

I think I have made improvements, but there is always someone smarter out there. :)

Thanks for your time!


texts:
Here's an implementation of finding the minimum element in a rotated array using binary search (one that is sorted in ascending order, and all elements are distinct).

Please let me know of any improvements that can be made to it.

import java.util.List;

public class RotatedArray {
    /**
     * Finds and returns the index at which the smallest value in a rotated array is located.
     *
     * @param rotatedArray    a rotated array that's sorted in ascending order (all elements are distinct)
     * @return the index of the smallest value, or -1 if rotatedArray is empty
     */
    public int findReset(List<Integer> rotatedArray) {
        if (rotatedArray.isEmpty()) {
            return -1;
        }

        // when array is already sorted
        if (rotatedArray.size() == 1 || rotatedArray.get(0) < rotatedArray.get(rotatedArray.size() - 1)) {
            return 0;
        }

        int midpoint = rotatedArray.size() / 2;

        // when left side is monotonically increasing
        if (rotatedArray.get(0) < rotatedArray.get(midpoint)) {
            return findReset(rotatedArray.subList(midpoint + 1, rotatedArray.size())) + midpoint + 1;
        }

        // Prevents stack overflow error from occurring (e.g. test case [1,2,3,4,0])
        if (rotatedArray.size() == 2) {
            return midpoint;
        }

        // when right side is monotonically increasing
        return findReset(rotatedArray.subList(0, midpoint + 1));
    }

}


texts: First drafts of Ultima-like adventure code

texts:
A friend and I watched most of the thenewboston syntax videos for Python 3 and spent 2 hours attempting to piece together our first program / generic text adventure. First experience with coding.

I'm looking for feedback on silly code and poor conventions.

Pastebin

class Erdrick():
    exp = 0
    level = 1
    levelupthresholds = [10, 30, 60, 100]
    #some sort of xp system here    #where we left off

    equipment = {'Copper Sword': 3, 'Leather Tunic': 3}             # currently equipped
    weapon = equipment['Copper Sword']
    armor = equipment['Leather Tunic']
    damage = 2 + 1 * (level - 1) + weapon
    health = 20 + 10 * (level - 1) + armor

class Enemy():
    def __init__(self, name, health, damage, exp):
        self.name = name
        self.health = health
        self.damage = damage
        self.exp = exp

hero = Erdrick()
slime1 = Enemy('Slime', 7, 2, 2)

Kind of stuck on integrating character levels, xp, and level up thresholds.

The math for damage and health is probably stupid

Doubtful that our implementation of classes and creating objects (hero/enemies) is better than bad

print(slime1.name, str(slime1.health))
print("You encounter a %s!,"
      "\n\t[%s] Health: %s\n" % (slime1.name, slime1.name, str(slime1.health)))

while hero.health > 0 and slime1.health > 0:
    print("\tYou deal %s damage!" % hero.damage)
    slime1.health -= hero.damage
    if slime1.health <= 0:
        print("\tSlime is defeated!!")
    else:
        print("\t[Slime] Health: %s" % slime1.health)
        print("\tSlime deals %s damage!" % slime1.damage)
        hero.health -= slime1.damage
        if hero.health <= 0:
            print("YOU DIED")
        else:
            print("\t[Hero] Health: %s" % hero.health)

Combat will be revised with prompts and options. It's currently (poorly?) automated just to have things work.

Hero and Enemy health will be formatted to print together in more of a typical horizontal information layout you'd find in a traditional RPG.