texts:
let date= new Date()

let day = date.getDay()

let weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";

changeText = () => {

 if(day === 1){
   firstDay.textContent = weekday[2]
   secondDay.textContent = weekday[3]
   thirdDay.textContent = weekday[4]
   fourthDay.textContent = weekday[5]
   fifthDay.textContent = weekday[6]

 }else if(day === 2){
    firstDay.textContent = weekday[3]
    secondDay.textContent = weekday[4]
    thirdDay.textContent = weekday[5]
    fourthDay.textContent = weekday[6]
    fifthDay.textContent = weekday[0]
}
}
 changeText();

this is for a weather app. I need to change the html text.content based on the current day so that the extended forecast stays accurate

This code repeats for each day of the week it works but seems very inefficient. the purpose is to change the text in my html so the extended weather forecast is consistent


texts: Toggling ActionBar visibility for SherlockFragmentActivity

texts:
Method implemented in parent class (extends SherlockFragmentActivity) (source)

ViewPager viewPager; // initialized in onCreate method
public void toggleActionBar() {
    try {
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        if (getSupportActionBar().isShowing()) {
            getSupportActionBar().hide();
            lp.topMargin = 0;
        } else {
            getSupportActionBar().show();
            lp.topMargin = getSupportActionBar().getHeight();
        }
        viewPager.setLayoutParams(lp);
    } catch (Throwable t) {
        Log.e(TAG, "Toggle of Actionbar failed", t);
    }
}

Call made from one of Fragments in ViewPager (source)

try {
    ((DilbertFragmentActivity) getSherlockActivity()).toggleActionBar();
} catch (Throwable t) {
    Log.e(TAG, "Toggle of Actionbar failed", t);
}

MinSdkVersion is equal 8, ActionBar support is done by ActionBarSherlock library.


texts: Algorithm that generates orthogonal vectors: C++ implementation

texts:
Recently I asked the similar question, but the algorithm was implemented in Python. Now I've tried to implement the same algorithm, but in C++ (I'm very new to it):

#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include <tgmath.h>
using namespace std;

const int MAXRANGE = 1000;

int randint(int low, int high){
    return rand() % (high - low) + low;

    }

void generate_vector(float vec[],int dimension){
    for (int i = 0; i < dimension; i++){
        vec[i] = randint(-MAXRANGE,MAXRANGE);
        }

    // We need to ensure that the last entry doesn't equal to zero

    if (vec[dimension-1] == 0){
        while (vec[dimension-1] == 0){
            vec[dimension-1] = randint(-MAXRANGE,MAXRANGE);

        }
    }

}

void generate_orthogonal (float *vector, float orthogonal_vector[], int dimension){
    float last_entry;
    float dot_product = 0;
    for (int i = 0; i < dimension -1; i++){
        orthogonal_vector[i] = randint(-MAXRANGE,MAXRANGE);
    }
    for (int i = 0; i < dimension -1; i++){
        dot_product = dot_product + (vector[i] * orthogonal_vector[i]);
    }
    last_entry = -(dot_product/vector[dimension-1]);
    orthogonal_vector[dimension-1] = last_entry;
}

float dot_product(float *vector1, float vector2[],int dimension){
    float sum = 0;
    for (int i = 0; i < dimension; i++){
        sum += (vector1[i])*(vector2[i]);
    }
    return sum;
}

void print_vector(float *A,int dim){
    cout << "(";
    for (int i = 0; i < dim; i++){
        if (i == dim -1){
            cout << A[i];
        }
        else{
            cout << A[i] << ",";}
    }
    cout << ")^T" << endl;
}
int main(){
    srand(time(0));
    int dimension;
    cout << "Choose dimension for the vector: ";
    cin >> dimension;
    float arbitrary_vector[dimension], orthogonal[dimension];
    generate_vector(arbitrary_vector,dimension);
    generate_orthogonal(arbitrary_vector,orthogonal,dimension);
    cout << "First vector: ";
    print_vector(arbitrary_vector,dimension);
    cout << "Orthogonal vector: ";
    print_vector(orthogonal,dimension);
    cout << "Dot product of the vectors: ";
    cout << dot_product(arbitrary_vector,orthogonal,dimension) << endl;

}

What can be improved?

As some people previously pointed out, the algorithm would throw exception if the last entry of the first vector was \$0\$. I made an a slight change to ensure that generate_vector function won't generate vector where the last element is zero.


texts: JSON formatting and processing hierarchies

texts:
I have a properties file I'm using for GIS software. You have a feature like a road, then properties under it, like so:

{
    "road": {
        "colour": "rgb(0,0,0)"
     },
     "railway": {
        "colour": "rgb(100,100,100)"
     }
}

Now I need to group these into categories, for example, transportation. The first thing I thought of was:

{
    "transportation":
    {
        "road": {
            "colour": "rgb(0,0,0)"
        },
        "railway": {
            "colour": "rgb(100,100,100)"
         }
    }
 }

This makes things awkward when I want to access "road" (for example), because now I need to know it is under "transportation" (mind you I could always write a helper function to eliminate this). Further, "road" could be under multiple groups, perhaps "transportation" and "public works". Now I would need to duplicate the properties in both instances.

Would I be wiser to use the following format, or is there a better way to do this?

{
    "road": {
        "colour": "rgb(0,0,0)",
        "group": ["transportation"]
     },
     "railway": {
        "colour": "rgb(100,100,100)",
        "group": ["transportation"]
     }
}


texts: Keyboard handler for selecting radio buttons

texts:
I have got my JavaScript working as seen here:
https://jsfiddle.net/yLg1qs04/3/

But how do I condense/shorten it so that it's not repeating itself so often and taking up so many lines?

$( '#mcnumber' ).keyup(function(){ //when a user types in input box
    var mcnum = this.value;
    if ( mcnum.charAt( 0 ) == '1' ) {
       $("#1mcskel1").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '2' ) {
       $("#1mcskel2").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '3' ) {
       $("#1mcskel3").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '4' ) {
       $("#1mcskel4").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '5' ) {
       $("#1mcskel5").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '6' ) {
       $("#1mcskel6").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '7' ) {
       $("#1mcskel7").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '8' ) {
       $("#1mcskel8").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '9' ) {
       $("#1mcskel9").prop("checked", "checked");
    } else if ( mcnum.charAt( 0 ) == '0' ) {
       $("#1mcskel0").prop("checked", "checked");
    }
})


texts: Using a spinner like a HTML select to display string but return int value

texts:
I'm still learning Android, I need to have a spinner and for it to display a list of string values. However, when I submit that data later on I need a corresponding integer value.
Similarly to how a HTML Select uses <option value="2">BlahBlah</option>.

From searching I've come up with a method which works, just wondering if anyone had any suggestions for improving the code?

I've got the two variables setup:

private String[]            arrMuppetNames  = {"Kermit","Gonzo","Fuzzy","Animal"};
HashMap<String, Integer>    hashMuppets     = new HashMap<String, Integer>();

hashMuppets is built up with a simple set of "Kermit":1,"Gonzo":2 etc.
Then to stop the code running on load I've added a "--please select--" to index 0.

//Add "please select" to spinner
arrNewArray[0]  = this.getString(R.string.muppet_select);
for(int i=0; i < arrMuppets.length; i++){
    arrNewArray[i+1]    = arrMuppets[i];
}

Obviously I add this array arrNewArray to the spinner using ArrayAdapter. Then use the OnItemSelectedListener.

private Spinner.OnItemSelectedListener spinnerListener = new Spinner.OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
        Spinner spinner             = (Spinner) findViewById(R.id.muppet_spinner);

        //Arg 3 is selected index. Lets ensure we didn't select our "Please select"
        if(arg3 != 0){
            //Get Selected Item and convert to corresponding value using hashMap
            String  strSelectedMuppet   = spinner.getSelectedItem().toString();
            int     intCatID            = hashMuppets.get(strSelectedMuppet);
            //Show toast of value
            Toast.makeText(getApplicationContext(), String.valueOf(intCatID), Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        //Do nothing
    }
};

If anyone has any suggestions or pointers I'd very much appreciate it. I'm happy to post the full code if you'd like, but I'm hoping the above short example is pretty self explanatory.

Thanks


texts: Is this common way to build this class and method?

texts:
I am a new developer therefore I have many questions:

In this class I get file path on the disk (wireshark file that needs to be converted to pcap format extension) and convert it with the method convertFileToPcap(), in the constructor I am calling convertFileToPcap() and from the main after create the Editcap object I am receiving the new file path (pcap format) with the property getNewFileName() who return _newFileName (class member) and I want to know if there is a better way or appropriate way to do it.

public class Editcap
{
    #region members
    private string _editpcap;
    private ProcessStartInfo _editpcapProcess;
    private FileInfo _fileInfo;
    private string _newFileName;
    #endregion

    #region c'tor
    public Editcap(FileInfo fileinfo)
    {
        _fileInfo = fileinfo;
        _newFileName = "";
        convertFileToPcap();
    }
    #endregion

    public void convertFileToPcap()
    {
        string oldFileExtension = _fileInfo.Extension;
        _newFileName = _fileInfo.FullName.Replace(oldFileExtension, "_new") + ".pcap";
        _editpcapProcess = new ProcessStartInfo(string.Format("\"{0}\"", _editpcap));
        _editpcapProcess.Arguments = (string.Format("{2}{0}{2} -F libpcap {2}{1}{2}", _fileInfo.FullName, _newFileName, "\""));
        _editpcapProcess.WindowStyle = ProcessWindowStyle.Hidden;
        _editpcapProcess.RedirectStandardOutput = true;
        _editpcapProcess.RedirectStandardError = true;
        _editpcapProcess.CreateNoWindow = true;
        _editpcapProcess.UseShellExecute = false;
        _editpcapProcess.ErrorDialog = false;
        Process capinfosProcess = Process.Start(_editpcapProcess);
        capinfosProcess.WaitForExit();
    }

    public string getNewFileName()
    {
        return _newFileName;
    }
}


texts: Count the number of vowels and consonants

texts:
So I needed to write a function that takes a string and returns a javascript object with vowels and consonants properties that maps to the number of vowels and consonants in the string

function getCount(words) {
  let answer = {vowels: 0, consonants: 0};
  if( typeof words !== 'string') { return answer }

  let vowel  = 'aeiouAEIOU'

  for(char of words){
    if(char === ' ') { continue }
    if(vowel.indexOf(char) === -1){  // not a vowel
      answer.consonants += 1
    }
    else if(vowel.indexOf(char) !== -1){  // is a vowel
      answer.vowels += 1
    }
  }
  return answer
}

Is there a better way of going about it? Preferably a functional approach


texts: Analyzing a web access log to obtaining totals for requests

texts:
This program takes the filename as the input and outputs to a file the number of requests that were more than 1000 bytes and the total bytes.

Log file example:

site.com - - [01/Jul/1995:00:00:01 -0400] "GET /images/launch-logo.gif HTTP/1.0" 200 183

Any suggestions/recommendations on the code or structure?

import re
import os

filename = input()
filename_regex = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+)\s?(\S+)?\s?(\S+)?" (\d{3}|-) (\d+|-)\s'
nbr_of_requests = 0
sum_of_bytes = 0

def parse_file(filename):
    with open(filename, 'r', encoding='utf-8') as fin:
        print(f"Opening file: {filename}")
        for line in fin.readlines():
            if os.path.exists(filename):
                line = re.findall(filename_regex, line)
                yield line

def save_to_file(filename):
    output_filename = "bytes_" + filename
    with open(output_filename, 'w+') as fout:
        fout.write(str(nbr_of_requests) + '\n' + str(sum_of_bytes))

if __name__ == '__main__':
    for line in parse_file(filename):
        if line and int(line[0][8]) >= 1000:
            nbr_of_requests += 1
            sum_of_bytes = sum_of_bytes + int(line[0][8])

    save_to_file(filename)


texts: Using EqualityComparer to find contained value

texts:
While searching for a method in HashSet which allows me to actually find an object in \$O(1)\$ (not just Contains, I need the reference), I came across this question on Stack Overflow and specifically the latest answer drew my attention.

I reworked the answer in a more generic approach and came up with the following;

public class EqualityComparerWithValue<T> : IEqualityComparer<T>
{
    public T Value;
    public bool Equals(T t1, T t2)
    {
        if (!(t1.GetHashCode() == t2.GetHashCode())) return false;
        if (!t1.Equals(t2)) return false;
        Value = t1;
        return true;
    }

    public int GetHashCode(T t)
    {
        return t.GetHashCode();
    }
}

Then an implementation of a potential \$O(1)\$ TryGetValue() would be something like this:

public static bool TryGetValue<T>(this HashSet<T> hs, T valIn, out T valOut)
{
    if (hs.Contains(valIn))
    {
        if (hs.Comparer is EqualityComparerWithValue<T>)
            valOut = (hs.Comparer as EqualityComparerWithValue<T>).Value;
        else
            valOut = hs.First(t => t.Equals(valIn));

        return true;
    }
    else
    {
        valOut = default(T);
        return false;
    }
}

Which will find the searched object in \$O(1)\$ if the EqualityComparerWithValue is specified in the constructor, and in \$O(n)\$ otherwise.

An implementation of this would be:

var set = new HashSet<string>(new EqualityComparerWithValue<string>());
string sOut = "";
if (set.TryGetValue("searchTerm", out sOut))
{
    //do stuff
}

Now, in my eyes, this seems to be a very legit solution. However, I'm just starting out. Are there any problems this could cause which I am overlooking? Is there any way to improve TryGetValue()?


texts:
I wrote a Python MP3 player for Linux using PyGame, with a curses GUI and a mouse-only interface.

It's purely for personal use.

It hasn't been polished yet, but for now I'd like to know what I've done inefficiently so I can fill in some ignorance-holes. I know a few things could be handled more directly.

import curses
import pygame

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
player = pygame.mixer.music
song = "testshort.mp3"
player.load(song)
player.play()
screen = curses.initscr()
curses.noecho()
curses.mousemask(curses.ALL_MOUSE_EVENTS)
screen.keypad(1)
curses.curs_set(0)
screen.resize(6, 30)
screen.border(0)
screen.addstr(4, 19, "*"*5+"-"*5)
player.set_volume(0.5)
screen.addstr(4, 2, "|")
paused = 0
curses.halfdelay(1)

while True:
            busycheck = player.get_busy()
            if busycheck == 0:
                screen.addstr(4, 2, ">")
            char = screen.getch()
            if char == curses.KEY_MOUSE:
                cords = list(curses.getmouse())
                mouse_x = cords[1]
                mouse_y = cords[2]
                vol_on = mouse_x - 18
                vol_off = 10 - vol_on
                screen.border(0)
                if mouse_y == 4:
                    if 29 > mouse_x > 18:
                        vol_bar = screen.addstr(4, 19, "*"*vol_on+"-"*vol_off)
                        volchange = (mouse_x-19)/9.0
                        player.set_volume(volchange)
                    elif mouse_x == 2:
                        if paused == 0:
                            if busycheck == 1:
                                screen.addstr(4, 2, ">")
                                player.pause()
                                paused = 1
                            else:
                                player.play()
                                paused = 0
                                screen.addstr(4, 2, "|")
                        else:
                            player.unpause()
                            screen.addstr(4, 2, "|")
                            paused = 0


texts: Vectorising orthogonal-triangular decomposition for 3D matrix

texts:
I am trying to optimise the computation time of my code (for the second time after a first optimisation that gives very good results). Currently, this code is very time-consuming depending on the size of the data (i.e. sometimes very big matrices). So if anyone has some ideas to help me to optimize this code, I will be very grateful!

matrice1=0+(20-0).*rand(500,5);
matrice2=datasample(matrice1,100);

[n1,~]=size(matrice1);
[n2,p2]=size(matrice2);
% Pre-calculate replicated B and the indices to be modified at each iteration
B_rep=repmat(matrice2,[1 1 n2]);
B_idx=bsxfun(@plus,((0:p2-1)*n2+1)',(0:n2-1)*(n2*p2+1));
B=mean(B_rep,1);
out=zeros(n1,n2); % initialize output array
for i=1:n1
    B_rep(B_idx)=repmat(matrice1(i,:)',1,n2);
    B_meanB=bsxfun(@minus,B_rep,B); % B minus mean values of B
    A_B_meanB=matrice2'-reshape(B,p2,[]); % A minus B_meanB

    for j=1:n2
        [~,R]=qr(B_meanB(:,:,j),0);
        out(i,j)=sum((R'\A_B_meanB(:,j)).^2)*(n2-1);
    end
end


texts: Implementing the CutHill-McKee Algorithm

texts:
I am very much interested in the Reverse Cuthil McKee Algorithm. I have seen Fortran and C or C++ implementations of it, and I decided that it would be a nice exercise to implement it in Python.
I know this algorithm is quite domain specific, but I would still be happy to see what kind of comments I get regarding:

Correctness - I am not sure my only test case works for others, although I did some comparison to the Octave and Matlab version.
Speed - Of course a C version would be faster. However, is there some Python improvements which can be done?
Readability - Is this code clear enough to other peer programmers?

The code:

import numpy as np

def getDegree(Graph):
    """
    find the degree of each node. That is the number
    of neighbours or connections.
    (number of non-zero elements) in each row minus 1.
    Graph is a Cubic Matrix.
    """
    degree = [0]*Graph.shape[0]
    for row in range(Graph.shape[0]):
        degree[row] = len(np.flatnonzero(Graph[row]))-1
    return degree

def getAdjcncy(Mat):
    """
    return the adjacncy matrix for each node
    """
    adj = [0]*Mat.shape[0]
    for i in xrange(Mat.shape[0]):
        q=np.flatnonzero(Mat[i])
        q=list(q)
        q.pop(q.index(i))
        adj[i] = q
    return adj

def RCM_loop(deg,start, adj,pivots,R):
    """
    Reverse Cuthil McKee ordering of an adjacency Matrix
    """
    digar=np.array(deg)
    # use np.where here to get indecies of minimums
    if start not in R:
        R.append(start)
    Q=adj[start]
    for idx, item in enumerate(Q):
        if item not in R:
            R.append(item)
    Q=adj[R[-1]]
    if set(Q).issubset(set(R)) and len(R) < len(deg) :
         p = pivots[0]
         pivots.pop(0)
         return RCM_loop(deg,p,adj,pivots,R)
    elif len(R) < len(deg):
         return RCM_loop(deg,R[-1],adj,pivots,R)
    else:
         R.reverse()
         return R

def test():
    """
    test the RCM loop
    """
    A = np.diag(np.ones(8))
    print A
    nzc=[[4],[2,5,7],[1,4],[6],[0,2],[1,7],[3],[1,5]]

    for i in range(len(nzc)):
        for j in nzc[i]:
            A[i,j]=1
    # define the Result queue
    R = ["C"]*A.shape[0]
    adj = getAdjcncy(A)
    degree = getDegree(A)
    digar=np.array(degree)
    pivots = list(np.where(digar == digar.min())[0])
    inl=[]
    Res = RCM_loop(degree,0, adj,pivots,inl)
    print degree
    print adj
    print "solution:", Res
    print "correct:", [6,3,7,5,1,2,4,0]

if __name__ == '__main__':
    test()


texts: Perform SELECT INTO Statement and add Primary Key afterwards

texts:
How can I imrpove the performance of this T-SQL statement?

SELECT Code, Description
INTO [DBApps_Pulse_WarehouseAreas].[dbo].[Tbl_Partmaster]
FROM SYSDataBridge.dbo.View_Pulse_Partmaster_Synchronized

ALTER TABLE [DBApps_Pulse_WarehouseAreas].[dbo].[Tbl_Partmaster] ADD PRIMARY KEY (Code)


texts:
I wrote this program, to determine if any given number is happy, and would like to know of any improvements that can be made to make it better. I have tested it, but whether or not it works perfectly I have no idea, there might be some numbers that get through, although I doubt it.

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class HappyNumber
{
    public static void main(String[] args)
    {
        System.out.print("Please enter a number: ");
        int number = new Scanner(System.in).nextInt(), value;

        Set<Integer> unique = new HashSet<Integer>();

        while (unique.add(number))
        {
            value = 0;
            for (char c : String.valueOf(number).toCharArray())
                value += Math.pow(Integer.parseInt(String.valueOf(c)), 2);
            number = value;
        }

        System.out.println(number == 1 ? "Happy" : "Not Happy");
    }
}


texts: NCAA Pool - Generate random teams for a list of players

texts:
Anyways, I am running a pool where 64 entrants will receive a random team from a field of 64 teams.  I'd like for it to be randomized to a decent extent, and although I understand the limitations of RNGs, I think this should be good enough.  See my code below - are there any issues with this?  Could this be done in an easier way?  Or alternatively, is this better asked in Cross Validated?

import random

regions = ["East", "West", "Midwest", "South"]
playerlist = []
teamlist = []

# this will be an actual list of player names when completed
for i in range(0, 64):
    playerlist.append("Player " + str(i))

for i in range(0, 7):
    random.shuffle(playerlist)

for i in range(0, 4):
    for j in range(1, 17):
        teamlist.append(playerlist[i*16+j-1] + ": " + regions[i] + " " + str(j))

#  edited: this is unnecessary
#for i in range(0, 7):
#    random.shuffle(teamlist)

print(teamlist)


texts: Find How Many Times Numbers Repeat on a Digital Clock

texts:
Project Overview:

See how many times numbers would repeat x times on a digital clock output. This particular code only counts from 12:00 to 11:59, so it's technically only half of a day, I could take the (output x 2) for a full day.

Functions:

input_io():
Input the number of times you would like to see if a number repeats (for example 11:11 will have the number "1" repeated four times. 12:11 would have 3 repeated "1"s, etc.)

gen_times():
Generate a list of all the "digital clock" outputs starting from 12:00 to 11:59 - including leading zeros for minutes (e.g. 12:04 would need the zero before the "4").

count_repeat():
Test each "clock output" (from gen_times()) to see how many times the numbers 0-9 repeat in each one. If it is greater than the input time add one to the counter.

Questions:

In the code, you'll see that I return values from functions and immediately assign them to variables. I'm not sure the proper conventions of this in Python. Are there ways to pass-through variables from function to function - is it reasonable to assign variables outside of functions to function outputs?
Is there a better way to run this program without all of the coercion? The main use case of the coercion is for the leading zeros when generating times.

Code:

def input_io():
    input_repeats = input("Please input the amount of times you'd like to see if numbers repeat")

    while True:
        try:
            input_repeats = int(input_repeats)
            break
        except:
            print("Please enter an integer.")
            input_repeats = input()
    return input_repeats

input_repeats = input_io()

def gen_times():

    total_minutes = (24 * 60) / 2
    print(f"Total Minutes {total_minutes}")
    times = ["0"] * int(total_minutes)
    hours = "12"
    minutes = "00"
    i = 0

    while (i < total_minutes):

        if(hours==13):
            hours=1

        times[i] = str(hours)+str(minutes)
        #print(int(minutes))

        if(minutes == "59"):
            minutes = "00"
            hours = int(hours) + 1

            #ADDING "0" IN FRONT OF HOURS
            #if(int(hours) >= 10):
            #    hours = hours
            #else:
            #    hours = "0"+str(hours)

        else:
            minutes = str(int(minutes)+1)

            if (int(minutes) >= 10):
                minutes = minutes
            else:
                minutes = "0" + str(minutes)

        i += 1
    return times

times = gen_times()
print(times)

def count_repeat():
    counter_repeat = 0
    i=0
    ii=0
    iterationcounter = 0

    while(i != len(times)):

        ii=0

        while(ii < 10):
            count = times[i].count(str(ii))
            #iterationcounter+=1
            if count >= int(input_repeats):
                counter_repeat+=1
                break

            ii+=1
        i+=1
    return counter_repeat

counter_repeat = count_repeat()

print(f"Number of Times w/ {input_repeats} repeats: {counter_repeat}")
print(counter_repeat,"/",len(times))
percent_repeat = (counter_repeat/len(times))
print("{:.2%}".format(percent_repeat))
#print(iterationcounter)


texts: Status view logic - is my approach good?

texts:
I would like to ask you for review of my application’s Status viewing logic implementation.
At first I have to close to you somewhat of my domain problem space.
I’m building social application. Part of my application are user’s statuses. User should add private status.
 Similarly, user should add public status. Private status is visible only to the Followers (It’s like on Instagram, user can follow other user to eg. get notification about followed user activities), and Public is visible to every user. Status owner can check information about who previewed his status.

When it comes to domain objects (I mean real world objects by this), I have following objects:

UserProfile (represents user. My approach is to not confusing actors with inner system objects. I mean, we have to consider two systems.

First is outer system, which is everything, that interacts with our system and second is inner system, generally system we are implementing. What is more we should have unambiguous terms in our namespace, so user is someone who interacts with our system by eg. asking it to send message and UserProfile is something which represents user in our system eg. Storing user’s data. Sorry for my bloated explanation. So that’s why I don’t have class user)

Status

Now we go to some of concrete implementation.

My approach is to delegate logic of giving preview of status to significant user in different class than Status.
Status class has only flag, which indicates whether status is public or not.

class Status {

 private boolean privy;

 boolean isPublic() {

  return !privy;

 }

 static Status ofInaccessible() {
   return InaccessibleStatus.create();
 }

}

I also thought to use in some degree Null Object pattern for status, which can be accessed by user. I said in some degree, because the main goal is to return some text informing about blocked content ( I know I could return 404 status instead but...)

class InaccessibleStatus extends Status {

  // Overriding  methods omitted

}

Here we have UserProfile class, which status viewing logic is delegated to StatusPreviewer class:

class UserProfile {

 private final StatusPreviewer statusPreviewer;

 private UserProfile(...) {
  this.statusPreviewer = StatusPreviewer.create(this);
 }

 // Cheking if user is on followers list - omitted method definition
 boolean isFollowing( UserProfile UserProfile );

 Status preview( Status status ) {
  return statusPreviewer.preview( status )
 }

}

And now the time for status view logic has come. I thought for a while about encapsulating logic of status view inside Status. Mhmm.. Can Status know who can read him? Rather not. So I came up with specialized class StatusPreviewer which is only responsible for giving access to status, by returning Status or InaccessibleStatus object.

So here is my StatusPreviewer class:

class StatusPreviewer {

 private UserProfile previewedBy;

 private StatusPreviewer( UserProfile previewedBy ) {

  this.previewedBy = previewedBy;

 }

 preview( Status status ) {

   if (status.isPublic() || previewedBy.isFollowing( status.getOwner())) {
     status.addViewer( userProfile );
     return status;
   }
   else return Status.ofInaccessible();

 }

}

Of course, I won’t use domain object directly within presentation layer. StatusPreviewer is some kind of indirect object used by UserProfile as containment(composition). Someone could think that StatusPreviewer is also UserProfile, so it should be subclass of UserProfile. But the point is, that I don’t need all of even part of UserProfile interface, so StatusPreviewer is different type.

I always try to write readable, easy to maintain code, that benefit from SOLID principles, but I am still learning.

Thanks in advance for any review from more experienced users or even someone with better, fresh insight.


texts:
I have a view function that allows a user to Add / Edit / Delete an object. How does the following function look, and in what ways could I improve it? I was thinking about separating aspects of the function into different parts, but since no 'component' is more than four-five lines of code, I thought that would be a bit overkill.

@login_required
def edit_education(request, edit=0):
    profile = request.user.get_profile()
    education = profile.education_set.order_by('-class_year')
    form = EducationForm(data=request.POST or None, request=request)

    if request.method == 'POST':

        ##### to add a new school entry ######
        if 'add_school' in request.POST:
            if form.is_valid():
                new_education = form.save(commit=False)
                new_education.user = profile
                new_education.save()
                return redirect('edit_education')

        ##### to delete a school entry #####
        for education_id in [key[7:] for key, value in request.POST.iteritems() if key.startswith('delete')]:
            Education.objects.get(id=education_id).delete()
            return redirect('edit_education')

        ###### to edit a school entry -- essentially, re-renders the page passing an "edit" variable #####
        for education_id in [key[5:] for key, value in request.POST.iteritems() if key.startswith('edit')]:
            edit = 1
            school_object = Education.objects.get(id = education_id)
            form = EducationForm(instance = school_object, request=request)
            return render(request, 'userprofile/edit_education.html',
                        {'form': form,
                         'education':education,
                         'edit': 1,
                         'education_id': education_id}
                    )
        ##### to save changes after you edit a previously-added school entry ######
        if 'save_changes' in request.POST:
            instance = Education.objects.get(id=request.POST['education_id'])
            form = EducationForm(data = request.POST, instance=instance, request=request, edit=1)
            if form.is_valid():
                form.save()
                return redirect('edit_education')

return render(request, 'userprofile/edit_education.html', {'form': form, 'education': education})

And in my template, if this help to clarify anything:

{% for education in education %}

{{ education.school }} {% if education.class_year %}{{ education.class_year|shorten_year}}, {% endif %} {{ education.degree}}
        <input type="submit" name="edit_{{education.id}}" value='Edit' />
        <input type="submit" name="delete_{{education.id}}" value="Delete" />

{% endfor %}


texts: Prevent multiple ifelse statements in php

texts:
I'm trying to figure out a way to make my code more readable and maintainable. While rewriting some ugly spaghetti code, I stumbled across this:

if($header !== null && $fieldValue === null)
{
    $errorMessage =  $message . ': row ' . $row . ', header "' . $header . "\"\n";
}
elseif($header === null && $fieldValue !== null)
{
    $errorMessage =  $message . ': row ' . $row . ', field value "' . $fieldValue . "\"\n";
}
elseif($header === null && $fieldValue === null && $row === null)
{
    $errorMessage =  $message . "\n";
}
elseif($header !== null && $fieldValue !== null)
{
    $errorMessage =  $message . ': row ' . $row . ', header "' . $header . '", value "' . $fieldValue . "\"\n";
}

It must be possible to make this more efficient, but how? Do I use a switch statement? Please enlighten me.


texts:
I have been teaching myself Python (as well as Tkinter) and today one of the sites I was reading, asked us to write a program to covert one value from Fahrenheit to Celsius, once - an easy three line program. As you can read in the comments for the program below, I wanted to expand on this.

This program is one of the most complex and best organized for me thus far. I have feed it through a PEP8 program and it returned no errors, and the program itself runs as I intended and I haven't crashed it when passing errors.

I would be grateful for any comments on the structure of the program, as well as areas I can improve and/or streamline the code - any and all constructive feedback is welcomed!

#!/usr/bin/python
"""
Program: Temperature Coversion (C to F, or F to C)
Date:    02 May 2019
Author:  Jason P. Karle
Remark:  This program was inspired by a Python exercise that
asks you to create a program that will convert one Celsius value to Fahrenheit;
so a program that can be executed with three lines of code.
However, I wanted to make something that would allow the user to
convert to and from either C of F, and do so multiple times, until the user
decides to end the program. This was also an exercise for me to
advance not only my code skills, but how I structure a program.
"""

def quitContinue():
    print("\nDo you want to:\n")
    print("     1. Make another conversion; or")
    print("     2. Exit the program?\n")
    answer = input("Make you selection: ")
    try:
        if answer == "1":
            mainProg()
        else:
            return
    except:
        print("That is not a valid choice.")
        quitContinue()

def CtoF_Calc():
    print("\nThank you, please enter the")
    print("value you want to convert.")
    print("Enter a value between -273.5°C to")
    print("+5.5 dectillion °C")
    value = float(input(": "))
    try:
        if value < -273.5 or value > 5.5**30:
            print("That is not a valid range.")
            celciusCalc()
        else:
            answer = (value*(9/5))+32
            print(f"{value}°C equals: {answer}°F")
            quitContinue()
    except:
        print("Please entet a number!")
        CtoF_Calc()

def FtoC_Calc():
    print("\nThank you, please enter the")
    print("value you want to convert.")
    print("Enter a value between -273.5°C to")
    print("+5.5 dectillion °C")
    value = float(input(": "))
    try:
        if value < -459.5 or value > 42**30:
            print("That is not a valid entry.")
            celciusCalc()
        else:
            answer = (5/9)*(value-32)
            print(f"{value}°F equals: {answer}°C")
            quitContinue()
    except:
        print("That is not a number!\n")
        FtoC_Calc

def makeSelection(selection):
    try:
        if selection == "1":
            CtoF_Calc()
        elif selection == "2":
            FtoC_Calc()
        else:
            return
    except:
        print("That is not a valid selection")
        makeSelection(selection)

def mainProg():
    print("Please enter the number")
    print("corresponding to what you")
    print("want to convert:")
    print("     1. Celcius to Farenheit")
    print("     2. Farenheit to Celcius")
    print("     3. Exit\n")
    selection = input("Enter 1, 2 or 3: ")
    makeSelection(selection)

if __name__ == "__main__":
    print("Welcome to the temperature")
    print("conversion program!\n")
    mainProg()


texts: Java enum-based factory to calculate entry parameters

texts:
I want to create a factory to return all Source instances that match given entry parameters- that is, I want to iterate through some Collection of objects and for each entry check boolean method.
I thought about enum, as  I'm guaranteed to iterate through them all.
I came up with something like this:

simple interface

public interface Source {

    public boolean isPresent(SourceCalculationData data);

    public Source2 getType();
}

my take on enum factory:

public enum Source2 {

    IB("IB", SourceIb.class),
    CCWEW("BOT", SourceCcwew.class),
    OBD("CUF", SourceCuf.class),
    PB("PB", SourcePb.class),
    COK("COK", SourceCok.class),
    CCZEW("CCZ", SourceCczew.class),
    CRM("CRM", SourceCrm.class),
    APP("APP", SourceApp.class);

    private static final Logger SENSITIVE_LOGGER = SensitiveLoggerFactory.getSensitiveLogger(Source2.class);

    private String configChannel;

    private Class<? extends Source> clazz;

    private Source2(String configChannel, Class<? extends Source> clazz) {
        this.configChannel = configChannel;
        this.clazz = clazz;
    }

    public Class<? extends Source> getClazz() {
        return clazz;
    }

    public String getConfigChannel() {
        return configChannel;
    }

    public Source getSource() {
        return getAction(clazz);
    }

    private Source getAction(Class<? extends Source> source2Class) {

        try {
            return source2Class.newInstance();

        } catch (InstantiationException | IllegalAccessException e) {
            SENSITIVE_LOGGER.warn("<< Exception occured during init of {}, returning unkown source.", source2Class);
            return new SourceUnkown();
        }

    }

and use case:

        final SourceCalculationData data = new SourceCalculationData();

        final EnumSet<Source2> presentSources = EnumSet.noneOf(Source2.class);
        for (final Source2 source2ToCheck : Source2.values()) {
            if (source2ToCheck.getSource().isPresent(data)) presentSources.add(source2ToCheck);
        }

I'm pretty sure this is not the best code in the world. Any suggestions what will make it better?


texts: More efficient way to retrieve data from JSON

texts:
I am using the jsmn JSON parser (source code) to get extract data from a JSON string.  jsmn stores the data in tokens that just point to the token boundaries in the JSON string instead of copying the data. For example, jsmn will create tokens like:

Object [0..31]
String [3..7], String [12..16], String [20..23]
Number [27..29]

This method is used to retrieve the actual characters between those values (for String objects):

char* getTextFromJSON(const char *json)
{
    json_parser p;
    jsontok_t tokens[15];
    jsontok_t key;

    if (!json) return NULL;

    initJsonParser(&p);
    parseJson(&p, json, tokens, sizeof(tokens) / sizeof(tokens[0]));
    for(unsigned int i = 0; i < sizeof(tokens) / sizeof(tokens[0]); ++i)
    {
        key = tokens[i];
        unsigned int length = key.end - key.start;
        char keyString[length + 1];
        memcpy(keyString, &json[key.start], length);
        keyString[length] = '\0';
        if(!strcmp(keyString, "utterance"))
        {
            key = tokens[i + 1];
            length = key.end - key.start;
            char* keyString = (char*) malloc(length + 1);
            memcpy(keyString, &json[key.start], length);
            keyString[length] = '\0';
            return keyString;
        }
    }
    return NULL;
}

Here are some JSON examples that would be thrown into the parser:

{"status":0,"id":"432eac38858968c108899cc6c3a4bade-1","hypotheses" [{"utterance":"test","confidence":0.84134156}]}

{"status":5,"id":"695118aaa3d01dc2ac4aa8054d1e5bb0-1","hypotheses":[]}


texts:
I have a representation for each initial shape as an Enum with points and another for each rotated shape in the same Enum.

Here is an example of the latter Enum:

//
//     * *
//     *
//     *
J_SHAPE_SOUTH(new Point[] {
        new Point(2, 0),
        new Point(2, 1),
        new Point(2, 2),
        new Point(3, 2)
}),

//
//   * *
//     *
//     *
L_SHAPE_SOUTH(new Point[] {
        new Point(1, 2),
        new Point(2, 0),
        new Point(2, 1),
        new Point(2, 2)
});

I was then wondering whether to move the rotated shapes into individual Enums, say RotatedJShape, or simply keep all the rotated shapes in the same Enum. My concern is that some shapes like the I-shape only has one rotated condition, so it seems pointless to have an Enum for that shape.

What would be the most suitable approach in my case in terms of scalability and code correctness?


texts: Determine total number of seconds since the epoch

texts:
I am looking for ways to enhance this function in C++.

The function gets a date and returns the total number of seconds since the epoch (01/01/1970).

Do you have any suggestion regarding the algorithm, the code style, etc ?

Note: I use this function instead of the standard library functions because it can handle negative dates and dates before 1900.

static int NDaysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

double getUnixTimeStamp(int y, int m, int d, int h, int mn, int s)
{
    // Begin bounds checking
    if (y < 0 || m < 1 || d < 1 || h < 0 || mn < 0 || s < 0)
        return -1;
    // End bounds checking

    int ye = 1970; //UNIX epoch 01/01/1970

    int sign = y > ye ? 1 : -1;

    int maxY = std::max(y, ye);
    int minY = std::min(y, ye);

    int nleapYears = 0;

    for (int i = minY; i < maxY; i++)
        if ((i % 100 != 0 && i % 4 == 0) || i % 400 == 0) nleapYears++;

    if (m > 2)
        if ((y % 100 != 0 && y % 4 == 0) || y % 400 == 0)
            nleapYears += sign;

    nleapYears = std::max(0, nleapYears);

    double monthsNDays = 0;

    for (int i = 1; i < m; i++)
        monthsNDays += NDaysInMonth[i - 1];

    return ((y - ye) * 365 + sign * nleapYears + monthsNDays + d - 1) * 86400
        + h * 3600 + mn * 60 + s;
}


texts:
I'm a newbie in the use of LinqToXml and I wonder if I can improve this snippet.

 Shared Function GetListByType(ByVal intIndex As Integer) As List(Of FileInfo)

            Dim strWorkingPath As DirectoryInfo = New DirectoryInfo(GetWorkspaceDir)
            Dim lstAllFiles As FileInfo() = strWorkingPath.GetFiles("*.xml", SearchOption.AllDirectories)
            Dim lstFiltredList As New List(Of FileInfo)
            Dim xelement As XElement
            Dim contratTypeIndex As String
            Dim contratVersion As Integer

            For Each fic In lstAllFiles
                xelement = xelement.Load(fic.FullName)
                contratTypeIndex = xelement.Element("TypeIndex").Value
                contratVersion = xelement.Element("Version").Value
                If (contratTypeIndex = intIndex.ToString And contratVersion = 0) Then
                    lstFiltredList.Add(fic)
                End If
            Next

            Return lstFiltredList.Distinct.ToList

        End Function


texts:
I got my JWT generation working with X509 and wanted to ask if you would recommend any changes in respect to:

Signing certificate storing / handling.
Publishing for anonymous access public key

Background info on service:

Generating JWT with refresh token
Expiration set in DB
Certificate (*.cer) x509 is stored securely on Azure Blob
Certificate (*.pfx) x509 is stored securely on Azure Blob

Here is piece of code I'm using to generate JWT:

var cert = _azureBlobService.DownloadFile("container", "certname.pfx");

X509Certificate2 myCert = new X509Certificate2();
// Import from the byte array
myCert.Import(cert, "Password1", System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet);

var token = new JwtSecurityToken(myCert.SubjectName.Name,
    audienceId, data.Identity.Claims,
    issued.Value.UtcDateTime,
    expires.Value.UtcDateTime,
    new X509SigningCredentials(myCert));

var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);

return jwt;


texts: strstr implementation with python and sets

texts:
Please review my strstr implementation in terms of time/space efficiency and overall readability. I am preparing for a coding assessment coming up as I am looking to pivot my career from Physics to Computer Science. This is an exercise from the interview practice questions on CodeSignal. My implementation successfully passes all 14 tests but I get the following error when I submit my answer:

Tests passed: 21/27. Execution time limit exceeded on test 22: Program
exceeded the execution time limit. Make sure that it completes
execution in a few seconds for any possible input.

"""strstr().

Given two strings, text and pattern, return an integer indicating the index
in the text of the first occurrence of the pattern.
"""

def strstr(text, pattern):
    """Needle in haystack O(|text|) time? and O(?) space.

    Return an integer indicating the first occurrence of pattern in the text,
    or -1 if the pattern is not part of the text.
    """
    lookup = set([pattern])
    len_text = len(text)
    len_pattern = len(pattern)
    for index in range(len_text-len_pattern+1):
        if text[index:index+len_pattern] in lookup:
            return index
    return -1

def tests():
    """Sample Tests."""
    samples = [("CodesignalIsAwesome", "IA", -1),
               ("CodesignalIsAwesome", "IsA", 10),
               ("a", "a", 0),
               ("a", "A", -1),
               ("sst", "st", 1),
               ("lrnkbldxguzgcseccinlizyogwqzlifxcthdgmanjztlt", "an", 38)]
    for text, pattern, answer in samples:
        if strstr(text, pattern) != answer:
            print(f"text: {text}, pattern: {pattern}, aswer: {answer}")

if __name__ == "__main__":
    tests()

Edit: Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.


texts:
Is there a better way to design this code? I have read that too many function parameters is a sign of poorly design code, and would love some feedback on this code.
The functions Google Maps markers and update the state.
Also any other feedback unrelated is welcome.
Functions:
// Initialising map and markers
export const handleApiLoaded = (
  games,
  map,
  setGameMarkers,
  setInfoWindow,
  handleMarkerClick
) => {
  const infoWindow = new google.maps.InfoWindow({});

  const gameMarkers = [];
  for (const game of games) {
    const newMarker = createGameMarker(
      map,
      game,
      infoWindow,
      gameMarkers,
      handleMarkerClick
    );

    newMarker ? gameMarkers.push(newMarker) : null;
  }

  // Update state
  setGameMarkers(gameMarkers);
  setInfoWindow(infoWindow);
};

// Create marker object for game
export const createGameMarker = (
  map,
  game,
  infoWindow,
  gameMarkers,
  handleMarkerClick
) => {
  const [lat, lng] = [parseFloat(game.latitude), parseFloat(game.longitude)];

  if (locationIsUnoccupied(lat, lng, gameMarkers)) {
    var icon = {
      url: GAME_ICON_URL,
      scaledSize: new google.maps.Size(30, 45),
    };

    var marker = new google.maps.Marker({
      position: {
        lat: lat,
        lng: lng,
      },
      icon: icon,
      map,
    });

    marker.addListener("click", () => {
      infoWindow.close();
      map.panTo(marker.getPosition());
      handleMarkerClick(marker, map);
      infoWindow.setContent(createGameInfoWindow(game));
      infoWindow.open(map, marker);
    });

    return marker;
  }
};


texts: Sentinel based find with conditional fallback to std::find

texts:
I've got bored, so I decided to write a code using ancient knowledge of sentinels.

Sentinel based find

Basically what we do is put value that is needed to find at the end, and then write an endless loop. Breaking from loop happens in the body of it, so one branch (which probably won't make much, since it is a loop branch, but still) is eliminated. Requires the type to have noexcept copy assign and noexcept copy construct (in C++17, since I guess T t = value will have guaranteed copy elision).

Is there any possibilities to make this faster without compromising functionality?

#ifndef FAST_FIND_HPP
#define FAST_FIND_HPP

#include <type_traits>
#include <utility>
#include <iterator>

namespace impl
{
    template <typename BidirIt, typename T>
    BidirIt find(std::true_type, BidirIt first, BidirIt last, const T& value)
    {
        if (first == last)
        {
            return last;
        }

        auto real_last = std::prev(last);
        if (*real_last == value)
        {
            return real_last;
        }

        auto copy = *real_last;
        *real_last = value;

        auto it = first;
        for (; ; ++it)
        {
            if (*it == value)
                break;
        }

        *real_last = copy;

        if (it == real_last)
        {
            return last;
        }

        return it;

    }

    template <typename BidirIt, typename T>
    BidirIt find(std::false_type, BidirIt first, BidirIt last, const T& value)
    {
        return std::find(first, last, value);
    }
}

template <typename BidirIt, typename T>
BidirIt find(BidirIt first, BidirIt last, const T& value)
{
    return impl::find(std::integral_constant<bool, std::is_nothrow_copy_assignable<std::remove_reference_t<decltype(*first)> >::value> {},
        first, last, value);
    //I'd like to allow T to be different from *first

}

#endif

Usage:

#include "fast_find.hpp"
#include "randomsequence.h"
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v(10'000'000);
    random_int_generator<> gen(0, 10'000); //generate values in range
    gen(v.begin(), v.end());

    int n;
    std::cin >> n;
    auto it = find(v.begin(), v.end(), n);
    if (it != v.end())
    {
        std::cout << "Found it!\n" << *it << '\n';
    }
    else
    {
        std::cout << "Sadness\n";
    }
}

Here is the random_int_generator<>, do not review this, I posted it to make it easier for you to benchmark if needed:

#pragma once

#include <random>

template <typename T = int, class Engine = std::random_device>
class random_int_generator
{
    Engine engine;
    std::uniform_int_distribution<T> dist;
public:
    random_int_generator(T begin = 0, T end = std::numeric_limits<T>::max()) :
        dist(begin, end)
    {

    }

    template <typename OutputIt>
    void operator()(OutputIt first, OutputIt last)
    {
        while (first != last)
        {
            *first++ = dist(engine);
        }
    }

    T operator()()
    {
        return dist(engine);
    }
};

You can find current version in my github repo (it's a mess, I hope you won't mind that).


texts: Immutable C++ stack - thoughts and performance

texts:
What are your thoughts on the fallowing immutable stack implementation? It is implemented having as a basis a C# immutable stack (where garbage collector assistance does not impose using a reference counted implementation like here).

namespace immutable
{
    template<typename T>
    class stack: public std::enable_shared_from_this<stack<T>>
    {
        public:

            typedef std::shared_ptr<T> headPtr;
            typedef std::shared_ptr<stack<T>> StackPtr;
            template <typename T> friend struct stackBuilder;

            static StackPtr empty()
            {
                return std::make_shared<stackBuilder<T>>(nullptr, nullptr);
            }

            static StackPtr Create()
            {
                return empty();
            }

            StackPtr push(const T& head)
            {
                return std::make_shared<stackBuilder<T>>(std::make_shared<T>(head), shared_from_this());
            }

            StackPtr pop()
            {
        return this->tail;
    }

    headPtr peek()
    {
                return this->head;
            }

            bool isEmpty()
            {
                return (this->head == nullptr);
            }

        private:
            stack(headPtr head, StackPtr tail): head(head), tail(tail)
            {
            }

            stack<T>& operator= (const stack<T>& other);

        private:
    headPtr head;
    StackPtr tail;
    };

    template <typename T>
    struct stackBuilder: public stack<T>
    {
        stackBuilder(headPtr head, StackPtr tail): stack(head, tail){}
    };
}

Usage:

auto empty = stack<int>::empty();

auto newStack = empty->push(1);
auto stack = newStack;
while(!stack->isEmpty())
{
    std::cout << *stack->peek() << "\n";
    stack = stack->pop();
}


texts:
I have a Node project and am trying to make my code better, so I've created a new folder with a file like following which encapsulates the read and write file.

This is working and my question is if it's good practice since I need to use the call to read and write file in several place in my code.

var fs = require('fs');

function writeFile(filePath, fileContent) {
    fs.writeFile(filePath, fileContent, 'utf8', function (err) {
        if (err) {
            return console.log("error to write to file:  " + filePath + " " + err);
        }
    });
}
function readFile(filePath, content) {
    fs.readFile(filePath, 'utf8', function (err, data) {
        if (err) {
            return console.log("error to read file:  " + filePath + " " + err);
        }
        content(data);
    });
}
exports.readFile = readFile;
exports.writeFile = writeFile;

I call it in my modules like this:

module.exports = function (app) {
    app.get('/aa', function(req, res) {

        var filePath  = 'C://test.txt';
        var file = require('../helprs/file');
         file.readFile(filePath ,function(fileContent){
            console.log(fileContent);
            res.send(fileContent);
        });

    });


texts:
After some googling for about 2 days, I am here with a simple wordpress front-end login system.

Please let me know if there is anything wrong with it, or if there is anything I can do, for improving it regarding functionality and security:

// Limit admin access to admins
function wp3344_checkRole(){
    global $wp_roles;
    $currentrole ='';
    foreach( $wp_roles->role_names as $role => $name ) {
        if( current_user_can( $role ) ){
            $currentrole = $role;
        }
    }
    if($currentrole == 'subscriber') wp_redirect ( site_url() . '/login/' );
}
add_action( 'admin_init', 'wp3344_checkRole' );

// Redirect to login if not
function wp3344_redirect_user(){
    if( !is_user_logged_in() ){
        wp_redirect( site_url() . '/login/');
        exit ();
    }
}
add_action( 'template_redirect', 'wp3344_redirect_user' );

// Redirect to login if failed
function login_failed() {
    $login_page  = site_url( '/login/' );
    wp_redirect( $login_page . '?user-login=failed' );
    exit;
}
add_action( 'wp_login_failed', 'login_failed' );

// Redirect to login if empty
function wp3344_verify_username_password( $user, $username, $password ) {
    $login_page  = site_url( '/login/' );
    if( $username == "" || $password == "" ) {
        wp_redirect( $login_page . "?user-login=empty" );
        exit;
    }
}
add_filter( 'authenticate', 'wp3344_verify_username_password', 1, 3);

// Redirect to login if logged out
function wp3344_logout_page() {
    $login_page  = site_url( '/login/' );
    wp_redirect( $login_page . "?user-login=false" );
    exit;
}
add_action( 'wp_logout', 'wp3344_logout_page' );

// Do authentication
function wp3344_frontend_login(){
    if( !empty( $_POST ) && !is_admin() ){
        if( is_user_logged_in() ){
            wp_redirect( site_url() );
            exit;
        }elseif( !empty( $_POST['username'] ) && !empty( $_POST['password'] ) ){
            if( wp_verify_nonce( $_POST['wp3344_nonce'], 'wp3344-login' ) ){
                $user = wp_signon( array( 'user_login' => $_POST['username'], 'user_password' => $_POST['password'], 'remember' => true ), true );
                if( $user->ID ){
                    wp_redirect( site_url() );
                    exit;
                }
            }
        }else{
            auth_redirect();
            exit;
        }
    }
}
add_action( 'after_setup_theme', 'wp3344_frontend_login' );


texts:
Indian Currency format is 12345 → "12,345" (for odd length) and 123456 → "1,23,456" (for even length). I have included all possibilities such as

Minus sign: "-12,345"
Decimal Point: "-12,345.345" or "12,345.123"
Zero Condition 000000.123 → "0.123"
Minus and Zero Condition '-000000.123' -> "-0.123"

int main()
{
    char        currency[20];
    char        *tmpCurrency=NULL;
    int         length = 0;
    int         j = 0, commas = 0,n=0;
    int  i = 0, cnt = 0;
    char        *s=NULL;
    int        signCount=0;
    puts("Enter the Currency");
    gets_s(currency,20);

    n = strspn(currency+1, "0");                            //to find number of zeros present in the array.

    if (currency[n] == '.' || currency[n]=='\0' )         //for Condtion like 0000000 or 000000.123 so as to maintain one zero so that o/p will be 0 or 0.123
    {

        memmove(currency, currency + n, strlen(currency));
    }
    else
    {
        memmove(currency, currency + n, strlen(currency));
    }

signCount==1?currency[0]='-':NULL;

    (s = strchr(currency, '.')) ? (length = s - currency) : (length = strlen(currency));   // Considering decimal Point and restricing to Put commas after decimal Point

    if (length>3)
    commas = (length / 2) - 1;                                                            // No of Commas to put

    tmpCurrency = (char*)malloc((length + commas+1) * (sizeof(char*)));

    while (currency[i] != '\0')
    {
        if (cnt == commas)   //maintaining count to check how many commas have been put in the character array
        {
            tmpCurrency[j] = currency[i];
            i++;
            j++;
            continue;
        }
          if (length % 2 == 0)                            //When length is even comma comes after 1 digit eg 1,23,456. so what i have done adjusting length ann checking when it is becoming even and putting comma.
        {
            tmpCurrency[j] = currency[i];
            if (currency[i] != '-' && currency[i+1]!='.')
            {
               tmpCurrency[j = j + 1] = ',';
            }
            i++;
            j++;
            length = length - 1;
            cnt++;
         }
        if (length % 2 != 0)         //for odd length putting one element in tmpCurrency and then subtracting length to make it even.
        {
            tmpCurrency[j] = currency[i];
            i++;
            j++;
            length = length - 1;
        }
    }

    tmpCurrency[j] = '\0';
    strcpy_s(currency,20, tmpCurrency);
    puts(currency);
    free(tmpCurrency);

    return 0;
}


texts:
I am I C#.NET developer for a few years now... Last couple of months I have started to study design patterns and enterprise software architecture principles so that I will be able to use those principles in my code... Well here is actual example what I need. Right now I am developing ASP.net web API REST services. My data is stored in MySQL relational database. In data access layer I would like to use Dapper micro ORM, so I would like to create some kind of my own ORM wrapper methods... If I decide in the future to change to some other ORM that I won't need to rewrite my whole DAL layer code... Here is the code how I am planning to do this: What do you think about my approach? (my goal here is not to be technology (dapper) dependent...)

public abstract class BaseORMCommandSettings //SQL command base class
{
    public string CommandText { get; private set; }
    public object Parameters { get; private set; }
    public IDbTransaction Transaction { get; private set; }
    public int? CommandTimeout { get; private set; }
    public CommandType? CommandType { get; private set; }
    public CancellationToken CancellationToken { get; private set; }

    public BaseORMCommandSettings(string commandText, object parameters =
    null,
    IDbTransaction transaction = null, int? commandTimeout = null,
                         CommandType? commandType = null, CancellationToken
    cancellationToken = default(CancellationToken))
    {
        this.CommandText = commandText;
        this.Parameters = parameters;
        this.Transaction = transaction;
        this.CommandTimeout = commandTimeout;
        this.CommandType = commandType;
        this.CancellationToken = cancellationToken;
    }
}

public class DapperCommandSettings : BaseORMCommandSettings//dapper cmd impl
{
    public CommandFlags Flags { get; private set; }

    public DapperCommandSettings(string commandText, object parameters =
    null, IDbTransaction transaction = null, int? commandTimeout = null,
                         CommandType? commandType = null, CancellationToken
    cancellationToken = default(CancellationToken), CommandFlags flags =
    CommandFlags.Buffered)
     :base(commandText, parameters, transaction, commandTimeout,
    commandType, cancellationToken)
    {
        this.Flags = flags;
    }
}

public interface ICustomORM //base interface, for now have only generic Read
                        list method
{
    IEnumerable<T> Read<T>(BaseORMCommandSettings cmd);
}

public class DapperORM : ICustomORM //my own dapper ORM wrapper implentation
{
    private readonly IDbConnection con;

    public DapperORM(IDbConnection con)
    {
        this.con = con;
    }

    public IEnumerable<T> Read<T>(BaseORMCommandSettings cmd)
    {
        var cmdDapper = cmd as DapperCommandSettings;
        var dapperCmd = new CommandDefinition(cmdDapper.CommandText,
        cmdDapper.Parameters, cmdDapper.Transaction,
                                          cmdDapper.CommandTimeout,
        cmdDapper.CommandType, cmdDapper.Flags,
                                          cmdDapper.CancellationToken);

        return con.Query<T>(dapperCmd);
    }
}


texts:
Design
My desired outcome is as follows:

S3 event triggers Lambda Function startTextractStateMachine

Lambda Function startTextractStateMachine kicks off State Machine textractStepFunc execution (AWS Step Functions)

State Machine textractStepFunc starts with Lambda Function callTextract; calls Textract async command to start process

Output of Textract command is attached to SQS queue TextractSQS

SQS queue output triggers Lambda Function getTextractOutput

Lambda Function getTextractOutput publishes message to SNS Topic

SNS Topic triggers final Lambda Function parseTextractOutput via subscription

Done

Implementation
I made this system work without any AWS Step Functions initially, but realized that I needed more control over retry/failure of the individual Lambda Functions (especially callTextract), so I've tried to move the system to AWS Step Functions and the Serverless Framework at the same time.
I've come to realize it was harder than I thought it would be. I keep running into roadblocks with the Serverless Framework.
I used several guides, blog posts and Github issues (here, here and here) to reach this point, but am permanently stuck.
Serverless Setup
I've left out much of my Design ideas and simply need to have the S3 event trigger when a file is added to the Bucket.
Here is my configuration file:
# serverless.yml

service: textract-service

provider:
  name: aws
  runtime: python3.7
  timeout: 10
  region: us-east-1
  environment:
    STATE_MACHINE_ARN: ${self:resources.Outputs.TextractStepFunctions.Value}
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "s3:PutObject"
        - "states:*"
      Resource:
        Fn::Join:
          - ""
          - - "<the-chumiest-bucket's ARN> or *"
            - ${self:resources.Outputs.TextractStepFunctions.Value}

plugins:
  - serverless-plugin-existing-s3
  - serverless-step-functions
  - serverless-pseudo-parameters

layers:
  boto3Layer:
    package:
      artifact: boto3_layer.zip
    allowedAccounts:
      - "*"

functions:
  startTextractStateMachine:
    handler: src/start_textract_state_machine.lambda_handler
    role: arn:...lambda-s3-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}
    events:
      - existingS3:
          bucket: the-chumiest-bucket
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: input1/
            - suffix: .pdf
      - existingS3:
          bucket: the-chumiest-bucket
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: input2/
            - suffix: .pdf
  callTextract:
    handler: src/call_textract.lambda_handler
    role: arn:...lambda-s3-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}
  getTextractOutput:
    handler: src/get_textract_output.lambda_handler
    role: arn:...lambda-s3-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}
  parseTextractOutput:
    handler: src/parse_textract_output.lambda_handler
    role: arn:...lambda-s3-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}

stepFunctions:
  stateMachines:
    textractStepFunc:
      name: TextractStepFunctions
      definition:
        StartAt: StartTextractStateMachine
        States:
          StartTextractStateMachine:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-startTextractStateMachine"
            Next: CallTextract
          CallTextract:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-callTextract"
            End: true

resources:
  Outputs:
    TextractStepFunctions:
      Description: The ARN of the state machine
      Value:
        Ref: TextractStepFunctions

How I deploy it:
sls deploy -v && sls s3deploy


texts: Flagging system: Check for changing values in a data frame

texts:
I've written the following code to check if a value in a data frame changes. I'm looking at the last 5 values. If there was no change at all I want my code to return 1, if a single one (or multiple) of the last 5 are different to the value that is being checked return 0. Finally I want the returned values in a new column in my data frame.

Here's my code so far. It works but I think there is a nicer (and more clean) way to do it.

mydata <- data.frame("id" = 1:100, "ta" = c(sample(x = c(-5:20), size = 94, replace = T), rep(1,6))) # include a repetition to check if code works
nums <- mydata$id # create a dummy for iteration
qc_dummy <- vector(mode = "list", length = length(nums)) # create a dummy vector for the values computed in the for loop

for(i in 1:length(nums)) {
  qc_dummy[[i]] <- ifelse(mydata[nums[i], 2] - mydata[nums[i-1], 2] == 0,
                          ifelse(mydata[nums[i], 2] - mydata[nums[i-2], 2] == 0,
                                 ifelse(mydata[nums[i], 2] - mydata[nums[i-3], 2] == 0,
                                        ifelse(mydata[nums[i], 2] - mydata[nums[i-4], 2] == 0,
                                               ifelse(mydata[nums[i], 2] - mydata[nums[i-5], 2] == 0, 1, 0) ,0), 0) ,0) ,0)
}
mydata$qc1 <- as.vector(c(0,unlist(qc_dummy))) # first value of list is skipped by unlist (logi(0)) -> add 0


texts:
I was asked to solve a problem for \$\binom{n}{k}\$. I did the following implementation and am wondering if there's any feedback.

Input:

n = Integer

k = Integer

Output:

result = Array of arrays of integers

Constraints:

Time: \$O(\binom{n}{k})\$

Space: \$O(\binom{n}{k})\$

The order of the output array DOES NOT MATTER.

n and k are both positive.

Resources:

N Choose K

Combinations

function combinations(n, k) {
    let result= [];

  function recurse(start, combos) {
    if(combos.length === k) {
      return result.push(combos.slice());
    }
        // Check if you can actually create a combo of valid length
        // given current start number
        // For example: 5 choose 4 can't begin with [3] since it would never have 4 numbers
    if(combos.length + (n - start + 1) < k){
      return;
    }
    recurse(start + 1, combos);
    combos.push(start);
    recurse(start + 1, combos);
    combos.pop();
  }

  recurse(1, []);
  return result;
}

I was wondering if there's a reason why the time gets optimized using a backtracking solution.

// function combinations(n, k) {
//   let result = []
//   function combine(combo, currentNumber){
//     if(combo.length === k) {
//       result.push(combo);
//       return;
//     }
//     if(currentNumber > n) {
//       return;
//     }

//     let newCombo1 = combo.slice();
//     let newCombo2 = combo.slice();
//     newCombo2.push(currentNumber);

//     combine(newCombo2, currentNumber + 1);
//     combine(newCombo1, currentNumber + 1);

//   }
//   combine([], 1);
//   return result;
// }

// speed: 1120.756 ms

//backtracking method
function combinations(n, k) {
  let result = []
  let stack = []
  function combine(currentNumber){
    if(stack.length === k) {
      let newCombo = stack.slice()
      result.push(newCombo);
      return;
    }
    if(currentNumber > n) {
      return;
    }

    stack.push(currentNumber)
    combine(currentNumber + 1);
    stack.pop();
    combine(currentNumber + 1);
  }
  combine(1);
  return result;
}

console.time("Naive Combinations")
console.log(combinations(20, 10))
console.timeEnd("Naive Combinations")

// speed: 320.756 ms


texts: ChatApp (Web API, Windows Forms and Azure SQL Database)

texts:
I have been working on chatApp (my first app in c#). I used Azure SQL Database, ASP.NET Web API and WinFroms.
The app works very well with no errors

Please give me your professional opinion and advice for myapp/ the way thecode was written.

Any advises/articles/tutorials that can help to improve the way i write code ?

Here is my main class on GitHub

Screenshots of my on GitHub

The classes below handles the restful connection with my Azure SQL Database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Backend.Connector;
using Backend.Models;
namespace Backend.Controllers
{
    public class UserController : ApiController
    {
        // GET: api/User
        public List<User> Get()
        {
            UserDbConnector dbc = new UserDbConnector();
            return dbc.GetUsers();
        }

        // GET: api/User/5
        // GET: api/Person/5
        public User Get(int id)
        {
            return null;
        }

        // POST: api/User
        public void Post(User user)
        {
            UserDbConnector dbc = new UserDbConnector();
            dbc.SaveUser(user);
        }

        // PUT: api/User/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/User/5
        public void Delete(int id)
        {
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Backend.Controllers;
using Backend.Models;
using System.Text;
namespace Backend.Connector
{
       public class UserDbConnector
    {
        private SqlConnection connection;

        public UserDbConnector()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "chat.database.windows.net";
            builder.UserID = "aboualy";
            builder.Password = "****";
            builder.InitialCatalog = "chat";

            try
            {
                connection = new SqlConnection(builder.ConnectionString);
                connection.Open();
            }

            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error in PersonDbConnector(): " + e.Message);
            }
        }

        public void SaveUser(User user)
        {
            try
            {
                String sql = "INSERT INTO tables VALUES ('" + user.username + "','" + user.firstname + "','" + user.lastname + "');";
                SqlCommand command = new SqlCommand(sql, connection);
                command.ExecuteNonQuery();
            }

            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error in SaveUser(): " + e.Message);
            }
        }

        public List<User> GetUsers()
        {
            List<User> users = new List<User>();
            String sql = "SELECT * from tables";

            try
            {
                SqlCommand command = new SqlCommand(sql, connection);
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    users.Add(new User(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));
                }
            }

            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error in GetUsers(): " + e.Message);
            }

            return users;
        }

        }

    }


texts:
I have the following controller with a couple of database queries and I'd like you to review it.

I've tried to make it clean for other developers but the communication with the database can be improved (more effective). The exception returned when nothing is found, so I'm not sure if it's the best way to do it.

public class LookupController : ApiController
{
    // GET api/Lookup
    [CacheOutput(ServerTimeSpan = 3600, ClientTimeSpan = 3600)]
    public List<GlassModel> Get(string filter)
    {
        if (string.IsNullOrEmpty(filter)) throw new ArgumentNullException(nameof(filter));

        using (var db = new LookupDbContext())
        {
            var salesCodes = GetSalesCodes(db, filter.ToUpper().Split(','));

            if (salesCodes.Any())
            {
                var glassQuantities = GetQuantitesByCountry(salesCodes, db);

                if (glassQuantities.Any())
                    return glassQuantities;
            }
            throw new SystemException("Value not found.");
        }
    }

    private List<GlassModel> GetQuantitesByCountry(List<string> salesCodes, LookupDbContext db)
    {
        var queryGlass = db.Countries
            .Where(c => salesCodes.Contains(c.Eurocode))
           .GroupBy(c => new { c.Countrycode })
           .Select(g => new
           {
               g.Key.Countrycode,
               Quantity = g.Sum(p => p.Quantity)
           });

        // build model
        return queryGlass.ToList().Select(x => new GlassModel
        {
            Coordinates = LocationHelper.GetCoordinatesByCountry(x.Countrycode),
            Country = x.Countrycode,
            Quantity = x.Quantity
        }).ToList();
    }

    private List<string> GetSalesCodes(LookupDbContext db, string[] filterValues)
    {
        var make = filterValues[0];
        IQueryable<Car> filter;

        if (filterValues.Length == 1) // make
        {
            filter = db.Cars.Where(c => c.VehicleMakeName.Contains(make));
        }
        else if (filterValues.Length == 2) // make, model
        {
            var carModel = filterValues[1].Trim();

            filter = db.Cars.Where(c => c.VehicleMakeName.Contains(make) &&
                                         c.VehicleModelName.Contains(carModel));
        }
        else // make, model, year
        {
            var model = filterValues[1].Trim();
            var year = Convert.ToDouble(filterValues[2]);

            filter = db.Cars.Where(c => c.VehicleMakeName.Contains(make) &&
                                          c.VehicleModelName.Contains(model) &&
                                          (c.FromYear <= year || c.FromYear == null) &&
                                          (c.ToYear >= year || c.ToYear == null));
        }

        return filter
            .GroupBy(c => new { c.SalesCode })
            .Select(g => g.Key.SalesCode).ToList();
    }
}


texts:
I am trying to insert into a database using JDBC and each thread will be inserting into the database. I need to insert into around 30-35 columns. I wrote a stored procedure that will UPSERT into those columns.

The problem I am facing is, if you look at my run method, I have around 30 columns written over there for insertion. Is there any way I can simplify my run method so that it doesn't looks so messy which is looking right now for me? And I have few more columns as well. So if I keep on adding new columns there, it will be looking so messy at one point in my run method.

Are there any way to make this look cleaner, keeping in mind thread safety issues?

class Task implements Runnable {

    private Connection dbConnection = null;
    private CallableStatement callableStatement = null;

    public Task() {

    }

    @Override
    public void run() {

    dbConnection = getDbConnection();
    callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);

    callableStatement.setString(1, String.valueOf(userId));
    callableStatement.setString(2, Constants.getaAccount(userId));
    callableStatement.setString(3, Constants.getaAdvertising(userId));
    callableStatement.setString(4, Constants.getaAvgSellingPriceMainCats(userId));
    callableStatement.setString(5, Constants.getaCatAndKeywordRules(userId));
    callableStatement.setString(6, Constants.getaClvBehavior(userId));
    callableStatement.setString(7, Constants.getaClvChurn(userId));
    callableStatement.setString(8, Constants.getaClvInfo(userId));
    callableStatement.setString(9, Constants.getaClvSegmentation(userId));
    callableStatement.setString(10, Constants.getaCsaCategoriesPurchased(userId));
    callableStatement.setString(11, Constants.getaCustomerService(userId));
    callableStatement.setString(12, Constants.getaDemographic(userId));
    callableStatement.setString(13, Constants.getaFinancial(userId));
    callableStatement.setString(14, Constants.getaGeolocation(userId));
    callableStatement.setString(15, Constants.getaInterests(userId));
    callableStatement.setString(16, Constants.getaLastContributorsPurchased(userId));
    callableStatement.setString(17, Constants.getaLastItemsLost(userId));
    callableStatement.setString(18, Constants.getaLastItemsPurchased(userId));
    callableStatement.setString(19, Constants.getaLastProductsPurchased(userId));
    callableStatement.setString(20, Constants.getaLastSellersPurchasedFrom(userId));
    callableStatement.setString(21, Constants.getaMainCategories(userId));
    callableStatement.setString(22, Constants.getaMessaging(userId));
    callableStatement.setString(23, Constants.getaPositiveSellers(userId));
    callableStatement.setString(24, Constants.getaPromo(userId));
    callableStatement.setString(25, Constants.getaScores(userId));
    callableStatement.setString(26, Constants.getaSegmentation(userId));
    callableStatement.setString(27, Constants.getaSellers(userId));
    callableStatement.setString(28, Constants.getaSrpBuyerUpiCount(userId));
    }
  }

    private Connection getDBConnection() {

    Connection dbConnection = null;

          Class.forName(Constants.DRIVER_NAME);
      dbConnection = DriverManager.getConnection(url,user,password);

      return dbConnection;
    }

This is my main thread code from which I am creating threads:

//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);

try {
    // queue some tasks
    for (int i = 0; i < noOfTasks * noOfThreads; i++) {
        service.submit(new Task());
    }
    service.shutdown();
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

    while (!service.isTerminated()) {

    }
} catch (Exception e) {

}


texts: An implementation of maximum subarray finding algorithm in STL style

texts:
I am reading Stroustrup now and I was very impressed with how flexible the STL library is thanks to iterators and generic programming. Along the way, I am also reading Cormen's book and decided to try to implement an algorithm for searching for the maximum subarray in the style of STL. I wrote in C++11. I would be very grateful to hear your opinion about this code.

template<typename For>
// Requires Forward_iterator<For>()
auto find_maximum_subarray (For begin, For end)
{
    typename std::iterator_traits<For>::value_type max_sum_subarr = *begin;
    typename std::iterator_traits<For>::value_type max_sum        = *begin;

    For subarr_begin = begin;
    For left = begin;
    For right = ++begin;

    for (; begin != end; ++begin)
    {
        if (max_sum_subarr > 0)
            max_sum_subarr += *begin;
        else
        {
            max_sum_subarr = *begin;
            subarr_begin = begin;
        }

        if (max_sum_subarr > max_sum)
        {
            left = subarr_begin;
            right = begin;
            ++right;
            max_sum = max_sum_subarr;
        }
    }
    return make_tuple (left, right, max_sum);
}


texts: Creating a dictionary of multiple results

texts:
I am creating list of dictionary from two different results. I appreciate any improvement suggested.

redditFile = urllib2.urlopen("http://www.bing.com/images?q="+word)
redditHtml = redditFile.read()
redditFile.close()
soup = BeautifulSoup(redditHtml)

productDivs = soup.findAll('div', attrs={'class' : 'dg_u'})
for div in productDivs:
    #print div.find('a')['t1']
    #print div.find('img')['src2']
    img_result = {}
    img_result['link'] = div.find('img')['src2']
    img_result['title'] = div.find('a')['t1']
    image_result_final.append(img_result)

final_result['img'] = image_result_final

print "*"*25

redditFile = urllib2.urlopen("http://www.bing.com/videos?q="+word)
redditHtml = redditFile.read()
#redditHtml = open('source.txt').read()
redditFile.close()
soup = BeautifulSoup(redditHtml)
productDivs = soup.findAll('div', attrs={'class' : 'dg_u'})
for div in productDivs:
    if div.find('div', {"class":"vthumb", 'smturl': True}) is not None:
        #print div.find('div', {"class":"vthumb", 'smturl': True})['smturl']
        #print div.find("div", {"class":"tl fade"}).text
        video_result = {}
        video_result['link'] = div.find('div', {"class":"vthumb", 'smturl': True})['smturl']
        video_result['title'] = div.find("div", {"class":"tl fade"}).text
        video_result_final.append(video_result)

final_result['video'] = video_result_final
import json
print json.dumps(final_result)


texts:
I have an application that provides the user the ability to backup the local SQLite database to another location.  I then provide the ability to restore the backup database and overwrite the current database with the backup copy.  In my restore command, I make a backup of the database file, which seems redundant.  I feel like this code could be simplified.

public async void RestoreDatabase()
{
    bool success;
    var pickedFile = default(StorageFile);

    var picker = new FileOpenPicker();
    picker.FileTypeFilter.Add(".sqlite");
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    var file = await picker.PickSingleFileAsync();

    if (file != null)
    {
        var pickedFileToken = StorageApplicationPermissions.FutureAccessList.Add(file);
        _settings.RestoreFileToken = pickedFileToken;

        pickedFile = file;
    }

    // first make a backup of the current database file
    var currentDatabase = await _currentFolder.GetFileAsync("MyMoney.sqlite");
    if (currentDatabase != null)
    {
        currentDatabase.CopyAsync(ApplicationData.Current.RoamingFolder, "MyMoney.bak",
            NameCollisionOption.ReplaceExisting);
    }

    try
    {
        if (pickedFile != null)
        {
            await pickedFile.CopyAsync(ApplicationData.Current.RoamingFolder, "MyMoney.sqlite",
                    NameCollisionOption.ReplaceExisting);
            success = true;
        }
        else
        {
            success = false;
        }
    }
    catch (Exception)
    {
        success = false;
    }

    if (!success)
    {
        // restore the backup file
        var backupDatabase = await _currentFolder.GetFileAsync("MyMoney.bak");

        if (backupDatabase != null)
        {
            await backupDatabase.CopyAsync(ApplicationData.Current.RoamingFolder, "MyMoney.sqlite",
                NameCollisionOption.ReplaceExisting);
        }
    }
}


texts:
I wrote this factory class in order to pass parameter to Singlton class, is it a good design in term of design for multithreading environment?

public static class LoggingServiceFactory
{
    private static string _connectionstring;
    private static readonly Lazy<LoggingService> _INSTANCE = new Lazy<LoggingService>(() => new LoggingService(_connectionstring));

    public static ILoggingService GetService(string connectionString)
    {
        _connectionstring = connectionString;
        return _INSTANCE.Value;
    }

    private class LoggingService : ILoggingService
    {
        private string _connectionstring;
        internal LoggingService(string connectionString)
        {
            _connectionstring = connectionString;
        }

        public void LogMessage(string msg)
        {
            // do the logging work
        }

    }
}

public interface ILoggingService
{
    void LogMessage(string msg);
}


texts:
This is the Tractor problem from the Kattis problems archive.

Problem Statement

  Bessie the Cow has stolen Farmer John’s tractor and is running wild on the coordinate plane! She, however, is a terrible driver, and can only move according to the following rules:

  Each of her movements is in the same direction as either the positive x-axis or the positive y-axis.
  Her \$\text{nth}\$ movement takes her \$2^{n−1}\$ units forward in her chosen direction. (On her first movement, \$n = 1\$, so she moves 1 unit.)
  Farmer John’s farm is on the coordinate plane, in the shape of a rectangle with corners at \$(0, 0), (A, 0), (0, B) \text{and} (A, B)\$. If Bessie starts at (0, 0), how many points inside the farm, including the boundary, could she reach?

  Input Format

  The input begins with an integer \$N (1 \le N \le 100)\$ on a line by itself, indicating the number of test cases that follow. Each of the following N lines contains two space separated integers A and B \$(1 \le A, B \le 10^8)\$, describing the upper-right corner of Farmer John’s farm.

  Output Format

  Output N lines, with the Nth line containing the number of points that Bessie could possibly reach in the Nth test case.

  In the first test case of the sample, Bessie can reach the following six points: \$(0, 0), (0, 1), (1, 0), (1, 2), (2, 1) and (3, 0)\$.

  Sample Input

2
2 3
7 7

  Sample Output

6
15

Solution

def next_steps():
    n = 1
    while True:
        yield n
        n <<= 1

def moves(a, b):
    current_positions = [(0, 0)]
    moves = []
    for step in next_steps():
        next_positions = []
        while current_positions:
            x, y = current_positions.pop(0)
            moves.append((x, y))
            if x + step <= a:
                next_positions.append((x+step, y))
            if y + step <= b:
                next_positions.append((x, y+step))
        if not next_positions:
            break
        else:
            current_positions = next_positions
    return moves

if __name__ == '__main__':
    for test_case in xrange(int(raw_input())):
        a, b = map(int, raw_input().strip().split())
        print len(moves(a, b))

It's working fine on smaller input but gets timed out on very large instances.


texts: Laravel controller method to update user

texts:
I'm using Laravel and this PHP method is in a controller. It's the back-end for a edit profile page. The user can change the profile picture, reset the password, the username, and so on. I'm new in PHP and would like to know if there is a better or simple way to code this.
public function update(Request $request){

        $user = Auth::user();

        $username = $request->username;
        // PENDING $email = $request->email;
        $wallet_address = $request->wallet_address;
        $about = $request->about;
        $password = $request->password;
        $website = $request->website;
        $location = $request->location;

        if($username){
            $user->username = $username;
            $user->save();
        }

        /** upload avatar section */

        $image = $request->file('avatar');

        if($image){

            // note: if avatar_name variable is null it means the user has never uploaded an image..
            // if the user has uploaded an avatar before, delete it before uploading the new one..
            if($user->avatar_name){
                Storage::delete('/public/profile-pics/'.$user->avatar_name);
            }

            $image_new_name = date('dmy_H_s_i').'_'.$user->id.'_'.$image->getClientOriginalName();
            $image->storeAs('profile-pics',$image_new_name,'public');
            $user->avatar_url = 'storage/profile-pics/'.$image_new_name;
            $user->avatar_name = $image_new_name;
            $user->save();
        }

        if($wallet_address){
             $user->wallet_address = $wallet_address;
             $user->save();
        }

        if($about){
             $user->about = $about;
             $user->save();
        }

        if($password){
             $user->password = $password;
             $user->save();
        }

        if($website){
            $user->website = $website;
            $user->save();
        }

        if($location){
             $user->location = $location;
             $user->save();
        }

        return redirect()->route('edit_profile')->with('success','Your account has been updated successfully.');
    }


texts: Calling a function on an object if not null

texts:
Here is code for check null in object:

public static TResult IfNotNull<TInput, TResult>(this TInput obj, Func<TInput,TResult> expression)
    {
        if (obj == null || expression == null) return default(TResult);
        var value = expression(obj);
        return value;
    }

The above code is best pratice of check nullability in object.  I'm working on c# V4.0.

Example usage :

Person.IfNotNull(x => x.User).IfNotNull(x => x.Name) ?? "";


texts:
Our solar system has 8 planets, including earth. Our calendar has some very confusing concepts such as leap years, which I still don't fully understand. In fact, since where I live, we use a different solar calendar that is different from the Gregorian reforms of the Julian Western calendar, I think I'm born in March but I should be born in February! Anyways, I attempted to create a simple program that calculates any given age, subtracting the leap days of each four years, in any planet of our solar system except Pluto which I believe is not a planet. I'm not sure about it.
def calculate_days(age):
    leap_days = 0 #holds number of leap days
    leap_years_list = [i for i in range(age) if i % 4 == 0] #holds the essence of leap years

    for j in leap_years_list:
        if j % 4 == 0 or j % 400 == 0 and j % 100 != 0:
            leap_days += 1 #if leap years are divisible by four and not divisible by a hundred, add to leap days

    return (age * 365) - leap_days

def calculate_celestial_age(planet, age):
    number_of_days = calculate_days(age) #calculate the days in age

    assert str.islower(planet), "Planet name must be entered in lower case e.g. 'mercury'" #if planet name is in lowercase, give error

    days_in_year = {"mercury": 88, "venus": 224, "earth": 365, "mars": 687, "jupiter": 4332, "saturn": 10759, "uranus": 30688,
                    "neptune": 60182} #days in each planet's year

    if planet == "mercury":
        return number_of_days / days_in_year["mercury"]
    elif planet == "venus":
        return number_of_days / days_in_year["venus"]
    elif planet == "earth":
        return number_of_days / days_in_year["earth"]
    elif planet == "mars":
        return number_of_days / days_in_year["mars"]
    elif planet == "jupiter":
        return number_of_days / days_in_year["jupiter"]
    elif planet == "saturn":
        return number_of_days / days_in_year["saturn"]
    elif planet == "uranus":
        return number_of_days / days_in_year["uranus"]
    elif planet == "neptune":
        return number_of_days / days_in_year["neptune"]
    else:
        raise Exception("Unknown Planet! Are you sure you've enter a planet?")

age = 23

planets = ["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]

for planet in planets:
    print("{0}: {1}".format(planet, calculate_celestial_age(planet, age)))

For my age, 23, I got these results:

mercury: 95.3409090909091
venus: 37.455357142857146
earth: 22.986301369863014
mars: 12.212518195050945
jupiter: 1.9367497691597415
saturn: 0.7798122502091273
uranus: 0.2733967674661105
neptune: 0.1394104549533083

According to this, my results are accurate.


texts:
As an academic exercise, I decided to implement a continuous shuffler, as seen on casino blackjack tables.  It operates by storing a "linked loop" (a linked list with the last element linked to the first) and walking a random number of steps around the loop when an item is removed.

public abstract class BaseShuffler<T>
{
    ///<summary>Returns a random int in the range [0,max)</summary>
    protected abstract int GetNextRandom(int max);
    private Node _current = null;
    private int _count = 0;

    public int Count
    {
        get { return _count; }
    }

    public void Add(T value)
    {
        var newNode = new Node(value);

        if (_count <= 0)
        {
            //form the loop
            _current = newNode;
            _current.Next = _current;
        }
        else
        {
            //insert into loop after current node
            var next = _current.Next;
            _current.Next = newNode;
            newNode.Next = next;
        }

        _count++;
    }

    public T Pop()
    {
        if (_count <= 0)
            throw new InvalidOperationException("Shuffler is empty");

        //walk a random number of steps round the loop
        for (int i = 0; i < GetNextRandom(_count); i++)
        {
            _current = _current.Next;
        }

        //remove next node from loop
        var next = _current.Next;
        var nextnext = _current.Next.Next;
        _current.Next = nextnext;
        _count--;

        if (_count <= 0)
        {
            //remove circular reference so we don't break refcounting for GC
            _current.Next = null;
            _current = null;
        }

        return next.Value;
    }

    private class Node
    {
        public Node Next { get; set; }
        public T Value => _value;
        private readonly T _value;
        public Node(T value)
        {
            _value = value;
        }
    }

    public bool Any()
    {
        return _count > 0;
    }
}

public sealed class Shuffler<T> : BaseShuffler<T>
{
    private Random _random;
    public Shuffler()
    {
        _random = new Random();
    }
    public Shuffler(int seed)
    {
        _random = new Random(seed);
    }

    protected override int GetNextRandom(int max)
    {
        return _random.Next(max);
    }
}

However, it appears to have a bias towards the returning an item near the end of the list as its first item: using the following test code

void Main()
{
    var shuffler = new Shuffler<(Rank rank, Suit suit)>();
    foreach (Suit suit in Enum.GetValues(typeof(Suit)))
    foreach (Rank rank in Enum.GetValues(typeof(Rank)))
        {
            shuffler.Add((rank, suit));
        }

    while (shuffler.Any())
    {
        var card = shuffler.Pop();
        Console.Out.WriteLine($"{card.rank} of {card.suit}");
    }
}

enum Suit
{
    Clubs,
    Diamonds,
    Hearts,
    Spades
}

enum Rank
{
    Two = 2,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace
}

I get a Spade most commonly as the first card, occasionally a Heart, and Clubs or Diamonds seemingly never.  Is there a way to remove the bias from my algorithm without entirely removing the limit on the random number generator, which could then produce a large number of steps to take, slowing the program down?  If I remove the limit, my test case changes from sub-millisecond runtime to around 0.15 seconds - but without the bias (I'm running in LinqPad as a test bed).