texts: Function that returns the number of items that appear more than once

texts:
This is the question:

  Write a method that takes in a string and returns the number of letters that appear more than once in the string. You may assume the string contains only lowercase letters. Count the number of  letters that repeat, not the number of times they repeat in the string.

How can I make this better?

function count(str){
    var nArr = [];
    var result = [];
    var obj = {};
    var arr = str.split("");
    // count all occurances in arr
    for(var i = 0; i < arr.length; i++){
        var letter = arr[i];
        obj[letter] === undefined ? obj[letter] = 1 : obj[letter] += 1;

    }
    for(var prop in obj){
        if(obj[prop] !== 1){
            nArr.push(prop);
        }
    }
    return nArr.length;

}

count("adsaaaffda");


texts:
Challenge:

  Swap positions in a list

Specifications:

  Your program should accept as its first argument a path to a filename.
  The file contains several test cases, one on each line.
  Each test case is a list of numbers, supplemented with positions to be swapped.
  List and positions are separated by a colon.
  Positions start with 0.
  There may be more than one position swaps, separated by a comma.
  Positions swaps are processed left to right.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SwapElements {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            String[] temp = input.nextLine().split(":");
            printSwapped(swapList(temp[0], temp[1]));
        }
    }

    public static void printSwapped(List<String> list) {
        StringBuilder result = new StringBuilder();

        for (String s : list) {
            result.append(' ').append(s);
        }

        System.out.println(result.substring(1));
    }

    public static List<String> swapList(String input, String swapKey) {
        List<String> result = modifyToList(input);

        for (String s : swapKey.split(",")) {
            String[] keys = s.split("-");
            int index1 = Integer.parseInt(keys[0].substring(1));
            int index2 = Integer.parseInt(keys[1]);

            String target1 = result.get(index2);
            String target2 = result.get(index1);

            result.set(index1, target1);
            result.set(index2, target2);
        }

        return result;
    }

    public static List<String> modifyToList(String list) {
        List<String> result = new ArrayList<>(list.length());

        for (String s : list.split("\\s+")) {
            result.add(s);
        }

        return result;
    }
}

Sample Input:

  1 2 3 4 5 6 7 8 9 : 0-8
  1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3

Sample Output:

  9 2 3 4 5 6 7 8 1
  2 4 3 1 5 6 7 8 9 10

It's actually been a while since I did one of these and I get the feeling it shows. The solution itself, of course, works, but I get the sense that it's memory intensive and/or slow. I'd mostly like to focus on optimizing speed, but any and all general feedback is welcome.

What do you think?


texts:
I have a class that listens to a file event constantly and reads that json file once it's created and makes of it a mail report and an excel file.

Now, I made the properties that are used for both these tasks static so I could determine their values once from the json and easily access them from all methods:

public class Reporter
{
    public static bool ShouldNotify = false;
    public static string CSVFilePath;
    private static string HTMLReport;
    private string aSerializedObject;
    ...
    public Reporter(string jsonFilePath)
    {
      //Determine static params values.
    }
    ...
    public string BuildHtmlReport() { ... }

    public string WriteCsvFile() { ... }
}

There are a couple of things I feel that aren't best practices:

Is it bad practice to combine static and non static params in the same non static class? Eventually it's a lot like using local and global variables but maybe I should encapsulate them.
Initializing all necessary params in the constructor - I always call the constructor with the jsonFilePath and don't use the default constructor.
I don't dispose the instance when finished since most properties are static and I don't really need to (functionality wise), should I?


texts: vuejs vuex element-ui used to toggle a login dialog but req

texts:
I have a login dialog working in vue js with typescript.

I want to trigger the open via a button on page, but also by toggling a value in the vuex store.

It is working by 2 watchers:

Watching the local visible state persists the state to the store on every change
Watching the store state then toggles the local visible flag.

The result is the button can open the modal, click outside the modal closes. But i can trigger the modal to be opened from the router now too from elsewhere in the app via vuex.

But... now i have to have 2 watchers running all the time. Is there a better way?

<template>
    <div>
        <el-button v-if="!authenticated" @click="visible = true">Login</el-button>
        <el-dialog :visible.sync="visible" title="Login or Register">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="Login" name="login">
                    <login-form></login-form>
                </el-tab-pane>
                <el-tab-pane label="Register" name="register">
                    <register-form></register-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>

<script lang="ts">
  import { Component, Vue, Watch } from 'vue-property-decorator';
  import { AuthenticationModule } from '@/store/modules/authentication';
  import LoginForm from '@/views/forms/LoginForm.vue';
  import RegisterForm from '@/views/forms/RegisterForm.vue';

  @Component({
    components: {
      LoginForm,
      RegisterForm,
    },
  })
  export default class AppHeaderLogin extends Vue {
    private visible: boolean = false;
    private activeTab: string = 'login';

    get authenticated() {
      return AuthenticationModule.authenticated;
    }

    get loginPrompt() {
      return AuthenticationModule.prompt.login;
    }

    @Watch('loginPrompt')
    onLoginPromptChange(value: boolean) {
      if (value !== this.visible) {
        this.visible = value;
      }
    }

    @Watch('visible')
    onVisibleChange(value: boolean) {
      // Do stuff with the watcher here.
      AuthenticationModule.TOGGLE_PROMPT_LOGIN(value);
    }
  }
</script>


texts: Nested if statements with 3 different parameters

texts:
I have a block of code below. The allDone() method at the bottom should only be run if the allCompleted == true. It should run through each of the statements to test.

allCompleted: This starts as true so the below logic works right.
run*.Checked: This is based on a check box in a form. This block should only run if this box is checked.
cmd: This is a generic string variable stating whether another part of the code (not shown here) was run successfully. If it has run successfully this string will read "done".

After those options, if all enabled (run*.Checked == true) methods have returned the cmd* string as "done" (everything that's checked has run successfully) then allCompleted should be true at the end so allDone() gets run.

If one single enabled method returns false (there was an error somewhere or otherwise it did not return "done"), then the allDone() method should not be run and the code will continue, skipping the last if (allCompleted) statement.

bool allCompleted = true;

if (runPart1.Checked)
    if (cmdPart1 == "done")
        allCompleted = ((allCompleted)? true : false);
    else
        allCompleted = false;

if (runPart2.Checked)
    if (cmdPart2 == "done")
        allCompleted = ((allCompleted) ? true : false);
    else
        allCompleted = false;

if (runPart3.Checked)
    if (cmdPart3 == "done")
        allCompleted = ((allCompleted) ? true : false);
    else
        allCompleted = false;

if (runPart4.Checked)
    if (cmdPart4 == "done")
        allCompleted = ((allCompleted) ? true : false);
    else
        allCompleted = false;

if (allCompleted)
    allDone();

So if at anytime one of the enabled parts fail the code will basically just move on.

As it stands this code works, I just feel like it could be written better. Is this the best way or have I got it? Something about it makes me feel awkward still.

EDIT: Also, each time one of the parts completes, it runs this method, so it will run a few times being false in the end until the last one runs and all the others are "done" in which case it should completes and run allDone().


texts: Generic Stack implementation in C-style C++

texts:
I implemented generic stack in C. Seems to work fine. It doesn't work for strings, though.

It was compiled using Visual C++.

Implementation:

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

struct node{
    void* value;

    node* next;
};

struct stack{
    node* first;
    int elemSize;
    int length;
};

stack* StackNew(int elemSize)
{
    stack* s = (stack*)malloc(sizeof(stack));
    s->elemSize = elemSize;
    s->length = 0;
    return s;
}

void Push(stack* s, void* value)
{
    node* oldFirst = s->first;
    s->first = (node*)malloc(sizeof(node));
    s->first->value = malloc(s->elemSize);
    memcpy(s->first->value, value, s->elemSize);
    s->first->next = oldFirst;
    s->length++;
}

void* Pop(stack* s)
{
    void* value = malloc(s->elemSize);
    memcpy(value, s->first->value, s->elemSize);
    node* oldFirst = s->first;
    s->first = s->first->next;
    free(oldFirst);
    s->length--;
    return value;
}

void Destory(stack* s)
{
    while (s->length > 0) Pop(s);
    free(s);
}

Test:

struct point{
    int x, y;
};

int main()
{
    stack* s = StackNew(sizeof(point));
    for (int i = 0; i < 100; i++){
        point pt;
        pt.x = i;
        pt.y = i * i;
        Push(s, &pt);
    }

    while (s->length > 0) {
        point pt = *(point*)Pop(s);
        printf("(%d,%d)\n", pt.x, pt.y);
    }
    Destory(s);
    return 0;
}

Output:

(99,9801)
(98,9604)
(97,9409)
(96,9216)
(95,9025)
(94,8836)
(93,8649)
(92,8464)
(91,8281)
(90,8100)
(89,7921)
(88,7744)
(87,7569)
(86,7396)
...

as expected.

Please tell me what I did wrong and how I can improve things.


texts: Converting input containing special character to float

texts:
This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.

I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.

def toNum(interest):

    if '/' not in interest:
        if float(interest) > 1:
            return float(interest)/100

        else:
            return float(interest)

    else:
        l= []
        n = 0
        count = 1

        list_interest=[]
        for e in interest:
            list_interest.append(e)

        for e in list_interest:

            if count == 1 or count == 3:
                l.append(e)
                count = count +1
                continue

            if e == '/':
                n = n + 1
                count = count +1
            else:
                l[n] = l[n] + e

        return int(l[0]) / int(l[1])

interest = input("Interest rate: ")
interest = toNum(interest)
print(interest)


texts:
Given an array of numbers and another number k, how can I find the number of 2 elements such as their difference is equal to k?

def pairs(n,k)
  n.combination(2).select{|x|(x[0]-x[1] == k) || (x[1]-x[0] == k)}.count
end

I ran a test where n was an array of 8000 different 10 digit numbers.

However, this took about 30 seconds to solve, and ideally it would solve in under a second.

It looks like there is a problem with my algorithm, but I can't figure out how to make it more efficient.


texts: Java Is my class file methods well written?

texts:
the purpose of this class file is to design a Saving account that stores a saving account's annual interest rate and balance. I have not wrote the test program yet, seeing that I believe I made a few mistakes with my class file. Also, at the end of classfile, I hid a method because I didn't understand how to word that method to add the interest rate to the balance.

Here are some additional information that could help you understand where I was going.

Name of class :SavingAccount Class

The Constructor should accept the amount of the savings account's starting balance.

Methods:
-Subtracting the amound of withdrawal.
-Adding the amound of a deposit.
-Adding the amount of monthly interest to the balance.
Other information:
- The annual rate is 5% (.05)
-monthly interest = Annual interest rate divided by 12.
- Getting the monthly interest rate added to balance: Add the monthly rate to the   balance. With the new result, add to the balance.

Class File

 public class SavingsAccount
{

private double balance;
private double startBalance;
private double AnnualRate = 0.5;
private double MonthlyInterest;
private double withdrawl;
 private double NewWithdrawl;
 private double deposit;
 private double NewDeposit;

public SavingsAccount()
{
balance = 0.0;
}

public SavingsAccount(double startBalance)
{
balance = startBalance;
}

public double getAnnualRate()
{
return AnnualRate;
}

public double MonthlyInterest()
{
MonthlyInterest= AnnualRate/12;
return MonthlyInterest;
}

public double getWithdrawl()
{
NewWithdrawl = balance - withdrawl;
return NewWithdrawl;
}
public double deposit()
{
NewDeposit = balance + deposit;
return NewDeposit;
}

/* ( The objecttive is to "Add the amount of monthly interest to the balance", not sure        where this was going)

public  getMonthlyInterestRate()
{
MonthlyBalance = MonthlyInterest x balance;
NewMonthlyBalance = MonthlyBalance + balance;
return NewMonthlyBalance;
 }
*/

}

Thanks for going through what I wrote, I hope I didn't make a huge mistake with my class file.


texts: Excel to Json getting file data into state in React JS

texts:
I am using dropzone and XLSX to load excel documents and then convert them into json.
The goal is to upload as many documents as possible and it will create an object with a key of the file name and then the value as the data. The problem I notice is that reader.onload is not available immediately after calling readAsArrayBuffer(). My solution was to use setTimeout. I am wondering if there is another method that I might be able to use instead of setTimeout as though it works perfectly, I feel it is more of a hack and maybe something exists that I have not learned or just don't know well enough. Here is my code inside the react element.
const [showLoader, setShowLoader] = useState(false)
const [filePaths, setFilesPaths] = useState([]);
const [parsedData, setParsedData] = useState({})
const [validationErrors, setValidationErrors] = useState([])
const [fileTypeError, setFileTypeError] = useState("")
const [uploadError, setUploadError] = useState("")

const onDrop = useCallback((acceptedFiles) => {
  setShowLoader(true)
  let data = {...parsedData};
  let files = [...filePaths];
  let errors = []

  if (validationErrors.length > 0) {
    setValidationErrors([])
  }

  if (fileTypeError) {
    setFileTypeError("")
  }

  if (uploadError) {
    setUploadError("")
  }

  acceptedFiles.forEach((file) => {
    const reader = new FileReader()

    reader.onabort = () => console.log('file reading was aborted')
    reader.onerror = () => console.log('file reading has failed')
    reader.onload = () => {
      const isExcelFile = file.type === XLSX_MIME_TYPE

      if (!isExcelFile) {
        setFileTypeError("One or more of the files added were removed because they were not excel files");
        return;
      }

      if (filePaths.includes(file.path)) {
        setUploadError("One or more of the files wasn't added because a file of that name already exists");
        return
      }

      let bstr = reader.result;
      const wb = XLSX.read(bstr, { type: 'array', bookVBA : true, cellDates: true, cellStyles: true});
      /* Get first worksheet */
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      /* Convert array of arrays */
      const data = XLSX.utils.sheet_to_json(ws);

      const validateData = data.map(dataItem => {
        const validTypes = ["Major", "Patch", "Maint", "Dependency", "Infrastructure"]
        if (!dataItem["Application Description"] || !validTypes.includes(dataItem["Event Type"]) || !dataItem["Event Type"]) {
          return "error"
        } else {
          return "valid"
        }
      })

      if (validateData.includes("error")) {
        reader.errorMessage = "error";
      } else {
        reader.data = [...data].map((item, index) => {
          return {
            id: index,
            ...item
          }
        })
      }
    }
    reader.readAsArrayBuffer(file)
    setTimeout(() => {
      if (reader.errorMessage) {
        errors.push(`${file.path} contains errors, please make sure it was filled out correctly`)
      } else {
        files.push(file.path)
        data[file.path] = reader.data
      }
    }, 250)
  })

  setTimeout(() => {
    if (errors.length > 0) {
      setValidationErrors(errors)
    }
    setFilesPaths(files)
    setParsedData(data)
    setShowLoader(false)
  }, 250)
}, [
  validationErrors,
  fileTypeError,
  uploadError,
  parsedData,
  filePaths
])

So in short the code isn't broken. I'm just curious if I am going about achieving the result that I want correctly. If not doing correctly or if a better method I would love to know and understand how that works. I appreciate everyones help.


texts:
I have a number x and I need to choose another number y from the given range [l, r] such that x XOR y is maximum.

This is what I did till now:

def maxXOR(x, l, r):
    max_ = 0
    for y in range(l, r+1):
        temp = x^y
        if temp>max_:
            max_ = temp
    return max_

But it is quite slow. How can I optimise it?


texts: Calculating the checksum digit with the Luhn-algorithm

texts:
I'm doing some exercises in Python and this one is about using the Luhn-algorithm to calculate the checksum digit in Swedish personal identification numbers.

The description is the same as this question:

  Given a string of 9 digits, abcdefghi compute:

array = [a*2, b, c*2, d, e*2, f, g*2, h, i*2]

  Then you compute the sum of the digits in this array, so for example
  if a*2 is 16, then that part counts as 1 + 6

  Then the result is how much more you have to add to make it evenly
  divisible by 10. For example, if sum == 54 then the result is 6 as
  60 - 54 = 6.

def control_numb(nbr_string):
    cut_string = nbr_string[:9]  ## We need 9 numbers to calculate the 10th
    mult_numb = [2,1]            ## we should alternate multiplying 2 and 1 starting with 2
    i = 0                        ## holds the index of which mult_numt to use. starting with index 0

    sum_of_digits = 0
    for s in cut_string:         ## loop through the string of digits
        for d in str(int(s) * mult_numb[i]):  ## use s as int to do the multiplication. then turn back to str to loop through digit
            sum_of_digits += int(d)
        i = (i+1)%2

    return (10 - sum_of_digits % 10) % 10

I'm pretty new to Python and would very much like feedback, if there are any pythonic way to do things please spread the knowledge. Or just tear the code apart completely. Any comments are welcome!


texts:
I have created a module to draw text tables. The relevant parts are below and here's the full code for txtable).

class Row(Txtable):
    [...]
    def format(self, col_widths):
        """Return the row as formatted string.
        """

        columns = []
        for x, column in enumerate(self.columns):
            # skip empty rows
            if 0 == len(str(column)):
                columns.append((" " * col_widths[x]))
                continue
            columns.append(self.format_cell(x, col_widths[x]))
        return str(" " * self.col_spacing).join(columns)

class Table(Txtable):
    [...]
    def add_rows(self, rows):
        """Add multiple rows.
        """

        for columns in rows:
            self.add_row(columns)

    [...]
    def render(self):
        """Return the table as a string.
        """

        # render cells and measure column widths
        for y, row in enumerate(self.rows):
            for x, column in enumerate(row.columns):
                fmt_column = row.format_cell(x)
                width = len(fmt_column)
                try:
                    if self.col_widths[x] < width:
                        self.col_widths[x] = width
                except IndexError:
                    self.col_widths.append(width)
        # render the table with proper spacing
        output = ""
        lmarg = (" " * self.margin)
        for row in self.rows:
            [...do rest of the rendering...]

I'd like to know about ways I could optimize this please. I see I could calculate the maximum column widths in Table.add_rows() instead of Table.render(), but I'd like to keep the possibility to modify the rows before rendering the final output.

How could I cut back on the looping? Is there a better way to output tabular data?


texts:
I am using this code in an MVC application to manage objects that should only have one instance per request.

/// <summary>
/// Manage all the resources that we want to scope to a single HTTP request.
/// </summary>
/// <remarks>
/// This class should not be directly referenced in many places.
/// In general, infrastructure code is OK whereas application code is not.
/// </remarks>
sealed class RequestScoped : IDisposable
{
    private static readonly object key = typeof(RequestScoped);

    /// <summary>
    /// Gets the RequestScoped instance for the given HttpContext.
    /// Creates and returns a new instance if it doesn't exist yet.
    /// This method is not thread-safe.
    /// The assumption is that there will only be one thread per request.
    /// </summary>
    public static RequestScoped GetOrCreate(System.Web.HttpContext context)
    {
        if (!context.Items.Contains(key))
        {
            context.Items[key] = new RequestScoped();
            context.AddOnRequestCompleted(Cleanup);
        }
        return (RequestScoped)context.Items[key];
    }

    private static void Cleanup(System.Web.HttpContext context)
    {
        if (context.Items.Contains(key))
        {
            var scope = (RequestScoped)context.Items[key];
            scope.Dispose();
        }
    }

    private readonly Lazy<IDbConnection> connection;
    private readonly Lazy<SessionRepository> sessionRepo;

    private RequestScoped()
    {
        connection = new Lazy<IDbConnection>(() => Utilities.MakeOpenConnection());
        sessionRepo = new Lazy<SessionRepository>(() => new SessionRepository(connection));
    }

    public IDbConnection OpenConnection { get { return connection.Value; } }
    public SessionRepository SessionRepo { get { return sessionRepo.Value; } }

    public void Dispose()
    {
        if (connection.IsValueCreated)
        {
            try
            {
                if (connection.Value.State == ConnectionState.Open)
                {
                    connection.Value.Close();
                }
            }
            catch (Exception)
            {
                // ignore
            }
            connection.Value.Dispose();
        }
    }
}

Example usage is like this:

protected IDbConnection OpenConnection
{
    get { return RequestScoped.GetOrCreate(HttpContext.Current).OpenConnection; }
}

(I am aware of DI containers but I have chosen not to use one in this application.)


texts:
I have just made a simple script which spawns an alien that chases the player. I want to move as much of the script into functions so as to minimize the amount of code, to make it run better when my game gets a lot bigger. I am new to functions and classes, and I want to know what can be turned into a class in another script and how to go about doing it. I do not want just code, I want to be able to understand what I'm doing with it as well.

import pygame, sys, random, time, math
from pygame.locals import *
pygame.init()

bifl = 'screeing.jpg'
milf = 'character.png'
alien = 'alien_1.png'

screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
nPc = pygame.image.load(alien).convert_alpha()

x, y = 0, 0
movex, movey = 0, 0

z, w = random.randint(10, 480), random.randint(10, 640)
movez, movew = 0, 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_w:
                movey = - 4
            elif event.key == K_s:
                movey = + 4
            elif event.key == K_a:
                movex = - 4
            elif event.key == K_d:
                movex = + 4

        if event.type == KEYUP:
             if event.key == K_w:
                movey = 0
             elif event.key == K_s:
                movey = 0
             elif event.key == K_a:
                movex = 0
             elif event.key == K_d:
                movex = 0

    if w < x:
        movew =+ 0.4
    if w > x:
        movew =- 0.4
    if z < y:
        movez =+ 0.4
    if z > y:
        movez =- 0.4

    x += movex
    y += movey
    w += movew
    z += movez
    print('charecter pos: ' + str(x) + str(y))
    print('alien pos: ' + str(w) + str(z))

    chpos = x + y
    alpos = w + z
    print(alpos, chpos)
    if chpos == alpos:
        pygame.quit()
        sys.exit()

    screen.blit(background, (0, 0))
    screen.blit(mouse_c, (x, y))
    screen.blit(nPc, (w, z))

    pygame.display.update()


texts: Python class assignment simplification for d&d character creator

texts:
As some of you may know, part of creating, or leveling up a character in almost any game is ability score increases. In this example, the character has six abilities with preassigned scores: strength, dexterity, intelligence, wisdom, charisma, and constitution. Users of the code have the option of choosing to level up one score by 2 points, or two different scores by one each.

The code I have works, and it works well, however, I realize that it's bulky, ugly, and probably a sin for python to be running it. Can you help me simplify/streamline it? Thank you

def ability(self):
    choice = raw_input("leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
    if choice == "one":
        score = raw_input("which ability do you want to increase by two?")
        if score == "strength":
            self.strength = self.strength + 2
        elif score == "dexterity":
            self.dexterity = self.dexterity + 2
        elif score == "intelligence":
            self.intelligence = self.intelligence + 2
        elif score == "wisdom":
            self.wisdom = self.wisdom + 2
        elif score == "charisma":
            self.charisma = self.charisma + 2
        else:
            self.constitution = self.constitution + 2
    else:
        score = raw_input("which ability do you want to increase by one?")
        if score == "strength":
            self.strength = self.strength + 1
        elif score == "dexterity":
            self.dexterity = self.dexterity + 1
        elif score == "intelligence":
            self.intelligence = self.intelligence + 1
        elif score == "wisdom":
            self.wisdom = self.wisdom + 1
        elif score == "charisma":
            self.charisma = self.charisma + 1
        else:
            self.constitution = self.constitution + 1
        score_two = raw_input("which second ability do you want to increase?")
        if score_two == "strength":
            self.strength = self.strength + 1
        elif score_two == "dexterity":
            self.dexterity = self.dexterity + 1
        elif score_two == "intelligence":
            self.intelligence = self.intelligence + 1
        elif score_two == "wisdom":
            self.wisdom = self.wisdom + 1
        elif score_two == "charisma":
            self.charisma = self.charisma + 1
        else:
            self.constitution = self.constitution + 1


texts: Firestore async function with array and object transform for jquery datatables - improve efficiency and maintainability

texts:
How could this Firestore function be improved, please? This is a question to help us learn to write better code. So by improved, I don't mean made shorter... I mean made clearer as to what it is doing, more efficient in terms of its operations, easier to understand and maintain. I found getting this code working very frustrating, so am including it here to help others learn from it, hopefully.
The code takes an object returned from Firestore which looks like this:
{
  "GKXKsY34TAghSrNcaV6V": {
    "finishedScoring": "true",
    "id": "GKXKsY34TAghSrNcaV6V",
    "role": "mentor",
    "speaker": "Bob",
    "yourScore": "60",
    "title": "Aquaplex First Round Pitch"
  },
   etc.
}

This is passed into this code. The outcome desired is an array of arrays to allow us to use it as data in datatables.js. Yes, I'd have liked to use the Object source for datatables, instead of doing this array or arrays transform, but couldn't work out how to make it work in Firebase hosting with Node.js!
async function getDoc(db) {
  let workArr = [];
  let workArrArr = [];
  try {
    let doc = await db
      .collection("user")
      .doc("tNySnDyRdTfKCJnnpk9kHpVKTl12")
      .collection("userwork")
      .doc("000_user_work_index")
      .get();
    let workDoc = doc.data();
    console.log("workDoc", workDoc);

    //Create array of objects from Firestore object of objects
    for (const [key, value] of Object.entries(workDoc)) {
      workArr.push(value);
    }
    //Create array of arrays from array of objects
    workArrArr = workArr.map(function (obj) {
      return Object.keys(obj)
        .sort()
        .map(function (key) {
          return obj[key];
        });
    });
    return workArrArr;
  } catch (err) {
    console.log("Error getting document: ", err);
  }
}

$(document).ready(function () {
  getDoc(db).then((result) => {
    console.log("RESULT OF getDoc: ", result);
    $("#datatable-assessment").DataTable({
      data: result,
      columns: [
        { title: "Finished Scoring" },
        { title: "Doc ID" },
        { title: "Role" },
        { title: "Speaker." },
        { title: "Your Score" }
      ]
    });
  });
});

It does work... I just have a feeling it is not exactly efficient - so any advice please on how to improve it would be welcome.


texts:
As part of my own C++11 learning exercise I have implemented this Blocking Queue using the new C++11 thread API. One of the aspects I would like to improve is efficiency i.e. in the take member function while returning the Job template type to be returned by reference instead of by value.

/*
 * blockingqueue.h
 *
 *  Created on: May 20, 2016
 *      Author: bravegag
 */

#ifndef BLOCKINGQUEUE_H_
#define BLOCKINGQUEUE_H_

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
#include <cassert>

using namespace std;

template<class Job>
class blocking_queue {
private:
    queue<Job> queue_;
    mutex mutex_;
    condition_variable not_empty_cond_;
    condition_variable not_full_cond_;
    int capacity_ = 0;

public:
    blocking_queue(int capacity) : capacity_(capacity) {
        // empty
    }

    void put(const Job& job) {
        unique_lock<mutex> lock(mutex_);
        while (queue_.size() >= capacity_) {
            cout << "queue full, waiting for jobs to be taken" << endl;
            not_full_cond_.wait(lock, [&]() { return (queue_.size() < capacity_); } );
        }
        queue_.push(job);
        not_empty_cond_.notify_one();
        assert(!queue_.empty());
    }

    Job take() {
        unique_lock<mutex> lock(mutex_);
        while (queue_.empty()) {
            cout << "queue empty, waiting for jobs to be put" << endl;
            not_empty_cond_.wait(lock, [&]() { return !queue_.empty(); });
        }
        Job job = queue_.front();
        queue_.pop();
        not_full_cond_.notify_one();
        assert(queue_.size() < capacity_);
        return job;
    }

    int size() const {
        return queue_.size();
    }

    virtual ~blocking_queue() {
        // empty
    }
};

#endif /* BLOCKINGQUEUE_H_ */


texts:
I have written a service which uses the Java Mail Api to send bulk email notifications to the recipients. I feel that the way I implemented the solution is not really scalable when the number of recipients increases. I would like to know if there is a better way to make my solution more efficient.

This is what I tried so far

@Component
public class EmailService {

     public String  sendEmail(String [] to,String from, String subject, String msg) throws MessagingException {

         String status ="099";
         final  String password ="********";

           final String fromsender = from;
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.debug", "true");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(fromsender,password);
           }
           });

           //session.setDebug(true);
           Transport transport;
        try {
            transport = session.getTransport();
             InternetAddress addressFrom = new InternetAddress(fromsender);

               MimeMessage message = new MimeMessage(session);
               message.setSender(addressFrom);
               message.setSubject(subject);
               message.setContent(msg, "text/plain");
               //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
               for(int i =0;i<to.length;i++){
                   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));

               }

               transport.connect();
               Transport.send(message);
               status ="000";
               transport.close();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

        return status;
        }


texts:
Should I be using this more, instead of slider? Am I making any serious no-no's here, and is there a better design I should implement? I'm up for any pointers :)

slider = {
                selector : '#slider',
                init : function() {
                        $('#slider').hover(function(e){
                            slider.toggle();
                        });

                    $(document).bind('click', function(e){
                        slider.lock.unlock();
                        slider.state.collapse();
                    });

                    $('#slider').bind('click', function(e){
                        e.stopPropagation();
                        slider.lock.lock();
                    })
                },
                toggle : function() {
                    if (!this.lock.isLocked) {
                        this.state.toggle();
                    }
                },
                lock : {
                    isLocked   : false,
                    lock : function() {
                        this.isLocked = true;
                    },
                    unlock : function() {
                        this.isLocked = false;
                    }
                },
                state : {
                    isExtended : false,
                    toggle : function() {
                        if (this.isExtended===true) {
                            this.collapse();
                        } else {
                            this.extend();
                        }
                    },
                    extend : function() {
                        this.isExtended = true;
                        $('#slider').stop().animate({'left':'-5px'}, 'slow');
                    },
                    collapse : function() {
                        this.isExtended = false;
                        $('#slider').stop().animate({'left':'-210px'}, 'slow');
                    }
                }
            };


texts: compile time template bernstein polynomial

texts:
I wrote a compile time bernstein polynomial instead to define several functions for different coefficients. I wonder whether there is a way to make the function faster. std::powf is known to be relatively slow and the binominal coefficient is for some cases 1. Also style fixes are appreciated.

// Template functions to estimate the binominal coefficient
template<uint8_t n, uint8_t k>
struct binomial {
  static constexpr int value = (binomial<n - 1, k - 1>::value + binomial<n - 1, k>::value);
};

template<>
struct binomial<0, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, n> {
  static constexpr int value = 1;
};

// Template bernstein polynomial
template <uint8_t n, uint8_t k>
float bernstein(const float val) {
  constexpr float binom_coeff = binomial<n, k>::value;
  const float a = std::powf(val, k);
  const float b = std::powf(1 - val, n - k);
  return binom_coeff * a * b;
}


texts: Kill dead instances of Excel on a server

texts:
We have several legacy programs (VB6) generating Excel report. They are scheduled tasks running on a server. Yes, violate this.

As a result, we've got lots of "dead" instances of Excel on the server. I intend to write a program to clean these dead Excels. What is the correct way to kill an idle instance? I know it's not a good practice but it seems to be the easiest way for me.

Process[] procs = Process.GetProcessesByName("EXCEL");

List<ProcessInfo> beginProcessInfoList = new List<ProcessInfo>();
foreach (Process p in procs)
{
    if (p.HasExited)
        continue;
    try
    {
        ProcessInfo pi = new ProcessInfo() { PID = p.Id, TotalProcessorTime = p.TotalProcessorTime };
        beginProcessInfoList.Add(pi);
    }
    catch (Exception exp)
    {
        this.Log(exp.Message);
    }
}

Thread.Sleep(TimeSpan.FromSeconds(10));

foreach (Process p in procs)
{
    if (p.HasExited)
        continue;
    try
    {
        p.Refresh();
        if (p.TotalProcessorTime - beginProcessInfoList.Single(pi => pi.PID == p.Id).TotalProcessorTime == TimeSpan.FromSeconds(0))
        {
            p.Kill();
            p.WaitForExit();
            this.Log(string.Format("EXCEL started at {0} killed at {1}.", p.StartTime, DateTime.Now));
        }
    }
    catch (Exception exp)
    {
        this.Log(exp.Message);
    }
}


texts: Checking whether a bullet has hit a Space Invader

texts:
I just (almost) finished a Space-Invaders game in Javascript.
I have a few bugs to clear out of the way but meanwhile I wanted to ask how I can improve the method I use to test if one of my 'Bullets' has killed an 'Invader'.

I have a feeling I used too many loops and there must be a more elegant way.

The whole program may be found here.

The exact function is:

function testForInvaders(bullet){
    var score = document.getElementById('score');
    var bulletX = bullet.getLocation()[0],
        bulletY = bullet.getLocation()[1];

    for(var i = 0; i < Invaders.length; i++){
        var invaderX = Invaders[i].getLocation()[0],
            invaderY = Invaders[i].getLocation()[1];

        if(Invaders[i].isVisible()){
            // if bullet is in the invaders radius...
            if(bulletX >= (invaderX - 15) && bulletX <= (invaderX + 15) &&
            bulletY >= (invaderY - 15) && bulletY <= (invaderY + 15)){
                Invaders[i].removeVisibility();
                game.incrementScore();
                game.updateScore(score);
                return false;
            }
        }
    }
    return true;
}

This function is called from within my 'loop' function which is the interval the draws all elements to the canvas.
The logic is as follows:

move all invaders (loop through them)
move all bullets (loop through them)
for each bullet I call the above function and test against all Invaders.
then I loop through everything once more to draw it to the canvas.

How can I improve this?
General feedback would be welcome as well :)


texts:
My code works fine and I am just wondering is there a more efficient way to copy a similar list to another and ignore the properties which are not present.

private const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty;

public static List<T> MergeListData<T>(List<object> collection)
{
    if (collection == null)
        throw new ArgumentNullException("Collection", "The Collection that you are copying to cannot be null");

    List<T> result = new List<T>();

    for (int x = 0; x < collection.Count; x++)
    {
        var target = (T)Activator.CreateInstance(typeof(T));
        var propInfos = collection[x].GetType().GetProperties(flags);
        for (int i = 0; i < propInfos.Length; i++)
        {
            try
            {
                PropertyInfo _propinfo = target.GetType().GetProperty(propInfos[i].Name, flags);

                if (_propinfo != null)
                    _propinfo.SetValue(target, Nullable.GetUnderlyingType(propInfos[i].PropertyType) ?? propInfos[i].GetValue(collection[x]));

            }
            catch (ArgumentException aex) { if (!string.IsNullOrEmpty(aex.Message)) continue; }
            catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) return default(List<T>); }
        }
        result.Add(target);
    }
    return result;
}

And the usage is:

public class Name1
{
    public int Number   { get; set; }
    public string First { get; set; }
    public string Last  { get; set; }
}

public class Name2
{
    public string First { get; set; }
    public string Last  { get; set; }
    public decimal Wages { get; set; }
    public bool Active { get; set; }
}

 var List1 = new List<Name1> {  new Name1{  First = "Billy", Number = 1, Last = "Harte"}, new Name1 { First = "Jimmy", Number = 1, Last = "Dunne" } };

 List<Name2> bs = MergeListData<Name2>(List1.Select(x => x as object).ToList());


texts: Render dynamically vertical tabs and set classes depends on if statement

texts:
I would like to refactor code below and get rid of if statements for classes from view.

.container
  .tabbable.tabs-left
    %ul.nav.nav-tabs
      - @related_tasks.each do |task|
        %li{class: ("active" if @task == task)}
          = link_to task.name, "#tab#{task.id}", data: { toggle: 'tab' }, class: @current_user_tasks.include?(task.id) ? '' : 'inactive'

    .tab-content
      - @related_tasks.each do |task|
        .tab-pane{id: "tab#{task.id}", class: ("active" if @task == task)}
          = render 'task_tab', task: task


texts: Monkeypatching builtin open and File Mock-Up for unit testing

texts:
For a specific test-scenario I wanted:

avoid accessing the file system through pythons builtin open-function
don't want to use 3rd party libraries like Michael Foord's Mock library

I would like to hear your opinion, if this seems like a valuable solution, or if there are

similar solutions with less lines of code
grave errors or caveats in the provided solution

from io import StringIO

class MockFile(StringIO):
    """Wraps StringIO, because of python 2.6: clumsy name-property reset"""

    name = None #overwrite TextIOWrapper-property - part 1/2
    _vfs = {} #virtual File-System enables to "re-read" already written MockFiles

    def __init__(self, name, mode = 'r', buffer_ = None):
        self.name = name #overwrite TextIOWrapper-property - part 2/2
        if self._vfs.has_key(name):
            buffer_ = self._vfs[name]
        super(MockFile, self).__init__(unicode(buffer_))
        __enter__ = lambda self: self
        __exit__ = lambda self, exc_type, exc_value, traceback: None
        read = lambda self, size = None: super(Mockfile, self).read(size)

    def write(self, data):
        super(MockFile, self).write(data)
        self._vfs[self.name] = self.getvalue()

def replace_builtin(builtinname, replacementobj):
    import __builtin__
    builtin_func = getattr(__builtin__, builtinname)
    setattr(__builtin__, builtinname, replacementobj)

    def decorator_factory(func):
        def decorator(*args, **kwarg):
            return func(*args, **kwarg)

        #attach the original name and function to the decorator:
        decorator.replaced_builtin = (builtinname, builtin_func)
        return decorator
    return decorator_factory


texts: Improving efficiency and flow by changing subroutine orders

texts:
A batch file executes WinSCP.exe's console mode to download files and log the actions. Upon exit, WinSCP returns:

ERRORLEVEL 0 if the files are successfully retrieved or
ERRORLEVEL 1 if there is a problem with the connection -
time outs, etc. - or if no file is found
Unexplainably, WinSCP will occasionally return 0 when no files are found

Due to this, to meet audit requirements, I must check for four possibilities:

ERRORLEVEL 1 and a connection problem
ERRORLEVEL 0 and the file(s) exist(s)
ERRORLEVEL 1 or ERRORLEVEL 0 and no file found

And respond with one of three options (respectively):

Send email indicating error
Send email indicating success
Send email indicating no file

Note, the same group who receives the success notice, should also receive the no file notice as that is not download failure. The code reflects this.

I wrote the fully functional code below but am not sure it's as streamlined as it could be. My first concern is that I can improve flow by using GOTO and perhaps CALL or :EOF commands in more appropriate ways as I can't seem to find a better 'structure' for the conditions/responses. My goal is to eliminate un-necessary spaghetti-ing. Second, I am troubled to find a better way to reset the ERRORLEVEL to zero so I can use an ERRORLEVEL check twice (currently the %comspec%... line). I'm not even sure I need two checks. I appreciate all suggestions.

The code I'm concerned with begins the line after START /WAIT... but I present it in full, for reference:

SET MailDst=successful_code@mydomain.com
SET FailMailDst=failed_code@mydomain.com
SET MailSrc=downloader@mydomain.com
SET MailSrcName=Automated FTP Process
SET OKMailSub=Files Have Been Moved
SET NoFileMailSub=Files Not Present - Maybe Next Time
SET FailMailSub=An Error Occurred!

IF EXIST WSCPLog.txt DEL WSCPLog.txt
SET LOG=WSCPLog.txt

START /WAIT WinSCP.exe /console /script=WSCP-GetC.txt /log=%log%
IF ERRORLEVEL 1 GOTO erroryes
IF NOT EXIST "\\server\path\Test_File.ext" GOTO nofilemail
GOTO okmail

:erroryes
%comspec% /c exit %0%
FINDSTR /C:"Test_File.ext: No such file or directory" %LOG%
IF ERRORLEVEL 0 GOTO nofilemail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%FailMailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%FailMailSub% /MESSAGE=%log% /HOST=mail.mydomian.com
GOTO end

:nofilemail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%MailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%NoFileMailSub% /MESSAGE=%log% /HOST=mail.mydomain.com
GOTO end

:okmail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%MailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%OKMailSub% /MESSAGE=%log% /HOST=mail.mydomain.com

:end


texts: Fibonacci sequence binary tree console logger

texts:
I wrote code to show the structure of a Fibonacci sequence pattern in a graphical way. First I structure a tree given a variable the user inputs for how many iterations of the sequence they want to print. Then, it converts the numbers into the Fibonacci sequence.

My concern is that this doesn't seem very efficient, first I build a tree, then go through each node again and do the entire Fibonacci calculation on it. Instead, I was hoping for a suggestion to change the code so that it could generate the nodes and the Fibonacci number at the same time. Maybe, instead of two recursive functions, there is just one that calls itself:

fibo(num)=fibo(num-1)+fibo(num-2)

where (num-1) is the left node and (num-2) is on the right.

from binarytree import Node

 # Generates a binarytree with the correct *iterations* numbers.
def makeTree(node):
    if node.value > 1:
        node.left = makeTree(Node(node.value - 1))
        node.right = makeTree(Node(node.value - 2))
    return node

 # Converts the iterated binary tree numbers into fibonacci numbers
def fibonacci(a, b , num):
    if num > 0:
        a += b
        return fibonacci(b, a, num - 1)
    return a

a = int(input("Enter number: "))
fibTree = makeTree(Node(a))

for x in fibTree:
    x.value = fibonacci(0, 1, x.value)

print(fibTree)

Expected result if a user enters 5 as how many iterations they want.


texts: Project Euler #70: Time Efficiency Improvement

texts:
The problem was to find which \$n\$ for which \$\varphi(n)\$ is a permutation of \$n\$ and \$n/\varphi(n)\$ is minimum,now as we all know that means (simple conclusions from mathematics):

\$\varphi(n)\$ should be a permutation of n.
\$n\$ should have least number of prime factors (2 cannot be one of the prime factor and \$n\$ cannot be prime)
The prime factors should be as large as possible. Or in other words, the number should be as large as possible.

So the problem reduces to finding all numbers which are multiples of 2 primes (if no such number is found then find one with 3 prime factors and then 4 and so on, but such a situation never occurs)

I move back from 3137 as first factor and 33..331 the other (378 and 239118 th index in primes array). I multiply 'em, add to a list and then sort it and move in descending order to see which are permutations.

Even then it is taking a lot of time. Several minutes at-least.

double ratio = 100;
    List<Integer> l = new ArrayList<Integer>();
    int[] primes = Helper.getPrimes(10000050);
    for (int i = 378; i >= 1; i--) {
        for (int j = 239118; j > i; j--) {
            BigInteger num = BigInteger.valueOf(primes[i]).multiply(BigInteger.valueOf(primes[j]));
            if (num.compareTo(BigInteger.TEN.pow(7)) < 1) {
                int x = num.intValue();
                System.out.println(primes[i] + " * " + primes[j] + " = " + x);
                l.add(x);
            }
        }
    }
    Collections.sort(l);
    for (int i = l.size() - 1; i >= 0; i--) {
        int x = l.get(i);
        int y = EulerTotient(x);
        boolean isPerm = isPermutation(x, y);
        if (isPerm) {
            if (x < y * ratio) {
                ratio = (double) x / (double) y;
                System.out.println(x);
            }
        }
    }
    return 0;

isPermutation:

private static boolean isPermutation(int x, int b) {
    if (String.valueOf(x).length() != String.valueOf(b).length()) {
        return false;
    } else {
        int[] count = new int[10];
        do {
            ++count[x % 10];
            --count[b % 10];
            x /= 10;
            b /= 10;
        } while (x != 0);// also b!=0
        for (int i = 0; i < 10; i++) {
            if (count[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

EulerTotient: (take care to create a primes array)

public static int EulerTotient(int n) {
    int x = n;
    for (int i = 0; primes[i] <= n; i++) {
        if (n % primes[i] == 0) {
            x /= primes[i];
            x *= (primes[i] - 1);
        }
    }
    return x;
}

getPrimes:

isPrime = new boolean[maxValue + 1];
    Arrays.fill(isPrime, true);
    for (int i = 2; i * i <= maxValue; i++) {
        if (isPrime[i]) {
            for (int j = i; j * i <= maxValue; j++) {
                isPrime[i * j] = false;
            }
        }
    }
ArrayList<Integer> primes = new ArrayList<Integer>();
    for (int j = 2; j < lim; j++) {
        if (isPrime(j)) {
            primes.add(j);
        }
    }
    return listToIntArray(primes);


texts: CodeIgniter MVC Controller to validate and save a form

texts:
I feel although my controller is over complicated and more should be moved to the model.

I've read that the controller shouldn't contain any logic, and just call the model/view, however it currently contains logic which I don't know how to move to the model. Am I correct in thinking that this should be moved or is it's current state acceptable.

It's worth noting that I'm only unit-testing and reporting on models for the reasons described above.

public function create()
{
    $this->load->library(array('form_validation', 'My_form_validation', 'session'));

    $rules = array(
        array(
            'field' => 'name',
            'label' => 'Series name',
            'rules' => 'trim|required'
        ),
        array(
            'field' => 'start',
            'label' => 'Start',
            'rules' => 'trim|required|valid_date'
        ),
        array(
            'field' => 'end',
            'label' => 'End',
            'rules' => 'trim|required|valid_date'
        ),
        array(
            'field' => 'pursuit',
            'label' => 'Pursuit'
        ),
        array(
            'field' => 'userId',
            'label' => 'userId',
            'rules' => 'required|integer'
        )

    );
    $this->form_validation->set_rules($rules);
    $this->form_validation->set_message('valid_date', 'The {field} field must be in the format yyyy-mm-dd');

    $group = array('admin', 'seriesManage');

    if ($this->_is_authorized($group)) { //The user is authenticated and authorized

        if ($this->form_validation->run() == FALSE) { //form not successfully submitted (or not at all)

            $this->load->helper('form');

            /** @noinspection PhpUndefinedFieldInspection */
            $data['site_name'] = $this->config->item('site_name');
            //get current user id
            $data['userId'] = $this->ion_auth->user()->row()->id;

            $this->load->view('header', $data);
            $this->load->view('series/create', $data);
            $this->load->view('footer');

        } else { //form successfully submitted and validated, time to save the response!
            if ($this->series->create()) {
                $this->session->set_flashdata('message', 'New series created successfully!');
            } else {
                $this->session->set_flashdata('message', 'Failed to save to database, please contact system administrator');
            }
            redirect('series');
        }
    }

}


texts: Converting a c# enum into a list to be sent to the client

texts:
I want to use the enum on the client for a dropdown list.  Does this make sense, or is there a smarter way of doing this?

public class clientEnum
{
    public string Value { get;set;}
    public int Key { get; set; }
}

public static List<clientEnum> EnumToclientEnum <T>(T enumType) where T : Type
{
    List<clientEnum> list = new List<clientEnum>();

    foreach (var value in Enum.GetValues(enumType))
    {
        var name = value.ToString();
        var number = (byte)Enum.Parse(enumType, name);
        list.Add(new clientEnum { Key = (int)number, Value = value.ToString() });
    }
    return list;
}


texts:
I wanted to make an extremely light-weight logging system. What are your thoughts on this and what can be done to improve it?
First, the usage:
int main( )
{
    logging::level = logging::fatal | logging::warning;
    mini_log( logging::fatal, "entry point", "nothing", " is ", "happening!" );
}

Now, the code:
#if defined( NDEBUG )
#define mini_log( ... ) static_cast< void >( 0 )
#else
namespace logging
{
    enum level_t
    {
        none = 0b00000,
        information = 0b00001,
        debug = 0b00010,
        warning = 0b00100,
        error = 0b01000,
        fatal = 0b10000,
        all = 0b11111
    } inline level = all; // level should only be used in the entry point
    inline std::mutex stream;
}
#define mini_log \
    [ ]( logging::level_t const level_message, \
         std::string_view const location, \
         auto &&... message ) -> void \
    { \
        std::lock_guard< std::mutex > lock_stream( logging::stream ); \
        struct tm buf; \
        auto time = [ & ]( ) \
        { \
            auto t = std::time( nullptr ); \
            localtime_s( &buf, \
                         &t ); \
            return std::put_time( &buf, \
                                  "[%H:%M:%S]" ); \
        }; \
        auto level = [ = ]( ) -> std::string \
        { \
            switch( level_message ) \
            { \
                case logging::information: \
                    return " [" __FILE__ "@" stringize_val( __LINE__ ) "] [Info] ["; \
                case logging::debug: \
                    return " [" __FILE__ "@" stringize_val( __LINE__ ) "] [Dbug] ["; \
                case logging::warning: \
                    return " [" __FILE__ "@" stringize_val( __LINE__ ) "] [Warn] ["; \
                case logging::error: \
                    return " [" __FILE__ "@" stringize_val( __LINE__ ) "] [Erro] ["; \
                case logging::fatal: \
                    return " [" __FILE__ "@" stringize_val( __LINE__ ) "] [Fatl] ["; \
            } \
        }; \
        if( level_message & logging::level ) \
            ( ( std::cout << time( ) << level( ) << location << "]: " << message ) << ... ) << '\n'; \
    }
#endif


texts:
I have a hierarchy of parts in my database.  For example, one part (call it 0010102-0112-315) is a resistor.  It's used in a billion different top-level assemblies.  My final goal is to get all the top level product IDs related to the low level IDs (e.g. 0010102-0112-315).

My current approach is to left join the table onto itself 8 times (one past the max product depth), and when the recordId after is NULL then it must be a top level recordId.

However, the query takes almost 7 minutes to run, and I have a feeling I'm doing something wrong.

I can't use CTEs (to my knowledge) because we're using SQL Server 2003 (before CTEs).  Is there a better way of doing this?

Here's my current code:

SELECT I1.IMA_ItemID as ItemID1,
    I1.IMA_ProdFam as ProdFam1
    ,I1.IMA_RecordID as RecordId1 -- same as PSH.PSH_IMA_RecordID
    ,I2.IMA_RecordID as RecordId2
    ,I3.IMA_RecordID as RecordId3
    ,I4.IMA_RecordID as RecordId4
    ,I5.IMA_RecordID as RecordId5
    ,I6.IMA_RecordID as RecordId6
    ,I7.IMA_RecordID as RecordId7
    ,I8.IMA_RecordID as RecordId8
    ,I9.IMA_RecordID as RecordId9
FROM   Item AS I1
    left join ProductStructureHeader AS PSH1 ON PSH1.PSH_IMA_RecordID = I1.IMA_RecordID
    left join ProductStructure AS PS1 on PS1.PST_PSH_RecordID = PSH1.PSH_RecordID
    left join Item AS I2 ON I2.IMA_RecordID = PS1.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH2 ON PSH2.PSH_IMA_RecordID = I2.IMA_RecordID
    left join ProductStructure AS PS2 on PS2.PST_PSH_RecordID = PSH2.PSH_RecordID
    left join Item AS I3 ON I3.IMA_RecordID = PS2.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH3 ON PSH3.PSH_IMA_RecordID = I3.IMA_RecordID
    left join ProductStructure AS PS3 on PS3.PST_PSH_RecordID = PSH3.PSH_RecordID
    left join Item AS I4 ON I4.IMA_RecordID = PS3.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH4 ON PSH4.PSH_IMA_RecordID = I4.IMA_RecordID
    left join ProductStructure AS PS4 on PS4.PST_PSH_RecordID = PSH4.PSH_RecordID
    left join Item AS I5 ON I5.IMA_RecordID = PS4.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH5 ON PSH5.PSH_IMA_RecordID = I5.IMA_RecordID
    left join ProductStructure AS PS5 on PS5.PST_PSH_RecordID = PSH5.PSH_RecordID
    left join Item AS I6 ON I6.IMA_RecordID = PS5.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH6 ON PSH6.PSH_IMA_RecordID = I6.IMA_RecordID
    left join ProductStructure AS PS6 on PS6.PST_PSH_RecordID = PSH6.PSH_RecordID
    left join Item AS I7 ON I7.IMA_RecordID = PS6.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH7 ON PSH7.PSH_IMA_RecordID = I7.IMA_RecordID
    left join ProductStructure AS PS7 on PS7.PST_PSH_RecordID = PSH7.PSH_RecordID
    left join Item AS I8 ON I8.IMA_RecordID = PS7.PST_IMA_RecordID

    left join ProductStructureHeader AS PSH8 ON PSH8.PSH_IMA_RecordID = I8.IMA_RecordID
    left join ProductStructure AS PS8 on PS8.PST_PSH_RecordID = PSH8.PSH_RecordID
    left join Item AS I9 ON I9.IMA_RecordID = PS8.PST_IMA_RecordID

Some other obscure facts that might be useful:

RecordId1 above is the highest level RecordId
Selecting * where IMA_ItemStatusCode = 'Active' and IMA_ItemTypeCode = 'Purchased Item' from the Item table gives the lowest level items
Can't think of anything else, but feel free to ask as there might be something.


texts: Printing files count and size of a directory tree

texts:
I've written a small package that counts the files and the size by file type in a directory tree. It produces the result as a markdown file.
Here is a sample:

| directory | type | count | size |
| --- | --- | ---: | ---: |
| 0_0_root | ALL | 26 | 29.914 MiB |
| 0_0_root | .mp3 | 4 | 3.901 MiB |
| 0_0_root | .jpg | 5 | 211.019 KiB |
| 0_0_root | .blu | 5 | 9.829 MiB |
TRUNCATED
| 0_0_root/1_2_node | ALL | 6 | 12.852 MiB |
| 0_0_root/1_2_node | .jpg | 2 | 53.018 KiB |
| 0_0_root/1_2_node | .mp4 | 1 | 7.573 MiB |
TRUNCATED

I would be interested on how you would have iterated over the files. I'd be especially interested on how you would gain performance (time wise, I don't care about memory).

I've decided to use os.walk with the option topdown=False because that way I can iterate only once on each node. The idea is that it iterates over a tree in a way a that a directory is encountered after and only after it has already encountered all of its childs. And in order to include the size of the childs in the parent stats, I store them in a stack.

The stack can be modified in three way:

A node add a clone of itself to the stack, waiting to be eaten by its parent
A node get itself eaten by the top member of the stack, because it shares the same parent, the node from the stack continue to wait to be eaten by its parent
A node eats the top member of the stack because it is its child

He is a first module that I defined to hold the data.

from collections import defaultdict
from os.path import splitext, join, dirname
from os import stat
import logging

log = logging.getLogger('tree_stat.dm')

class DirectoryMeasure:
    def __init__(self, files, path=None, parent=None):
        self.path = path
        self.parent = parent or dirname(path)
        self.file_type_measures = defaultdict(FilesMeasure)

        for f in files:
            ext = splitext(f)[1]
            file_size = stat(join(path, f)).st_size
            self.file_type_measures[ext].volume += file_size
            self.file_type_measures[ext].count += 1

    @property
    def total(self):
        it = FilesMeasure()
        for ext in self.file_type_measures.keys():
            it.volume += self.file_type_measures[ext].volume
            it.count += self.file_type_measures[ext].count
        return it

    def eat(self, child):
        for ext in child.file_type_measures.keys():
            self.file_type_measures[ext].volume += child.file_type_measures[ext].volume
            self.file_type_measures[ext].count += child.file_type_measures[ext].count

    def edible_clone(self):
        clone = DirectoryMeasure([], parent=dirname(self.path))
        clone.eat(self)
        return clone

    def __repr__(self):
        return 'DirectoryMeasure({})' \
            .format(', '.join(['{v}={{{v}}}'
                              .format(v=v) for v in vars(self).keys()])) \
            .format(**vars(self))

class FilesMeasure:
    def __init__(self):
        self.volume = 0
        self.count = 0

    def __repr__(self):
        return 'FilesMeasure({})' \
            .format(', '.join(['{v}={{{v}}}'
                              .format(v=v) for v in vars(self).keys()])) \
            .format(**vars(self))

And here is the main logic:

def take_measures(directory):
    dir_tree = dict()

    stack = []
    for current, sub_dirs, files in os.walk(directory, topdown=False):
        log.debug('working in {}'.format(current))

        measure = dm.DirectoryMeasure(files, path=current)
        dir_tree[current] = measure

        log.debug('own measure: {}'.format(measure))

        if stack and stack[-1].parent == measure.path:
            measure.eat(stack.pop())
            log.debug('child fed measure: {}'.format(measure))

        if stack and stack[-1].parent == measure.parent:
            stack[-1].eat(measure)
        else:
            stack.append(measure.edible_clone())

    return dir_tree

That's pretty much everything but if you want to play around with it, you're welcome: https://github.com/AdrienHorgnies/tree_stat.


texts:
I want to write an example for a language similar to Haskell called Frege. While the interpreter is conceptually easy, it is lengthy and looks still quite messy. Note that I don't want to use Parsec etc, as it isn't available yet in Frege. Please help me to improve the Haskell version.

import Data.Char

data Tape = Tape { left :: [Int], cell :: Int, right :: [Int] }

instance Show Tape where
   show (Tape ls c rs) = show [reverse ls,[c],rs]

data Op = Plus | Minus | GoLeft | GoRight | Output | Input | Loop [Op] deriving (Eq, Show)

removeComments :: [Char] -> [Char]
removeComments xs = filter (`elem` "+-<>.,[]") xs

parseOp :: [Char] -> Maybe (Op, [Char])
parseOp ('+':cs) = Just (Plus, cs)
parseOp ('-':cs) = Just (Minus, cs)
parseOp ('<':cs) = Just (GoLeft, cs)
parseOp ('>':cs) = Just (GoRight, cs)
parseOp ('.':cs) = Just (Output, cs)
parseOp (',':cs) = Just (Input, cs)
parseOp ('[':cs) = case parseOps cs of
  (prog, (']':cs')) -> Just (Loop prog, cs')
  _ -> Nothing
parseOp _ = Nothing

parseOps :: [Char] -> ([Op],[Char])
parseOps cs = go cs [] where
  go cs acc = case parseOp cs of
    Nothing -> (reverse acc, cs)
    Just (op, cs') -> go cs' (op:acc)

parse :: String -> [Op]
parse prog = case parseOps $ removeComments $ prog of
   (ops, []) -> ops
   (ops, rest) -> error $ "Parsed: " ++ show ops ++ ", Rest: " ++ rest

execute :: [Op] -> IO Tape
execute prog = exec prog (Tape [] 0 [])

exec :: [Op] -> Tape -> IO Tape
exec [] tape = return tape
exec (Plus:prog) (Tape ls c rs) = exec prog (Tape ls (c+1) rs)
exec (Minus:prog) (Tape ls c rs) = exec prog (Tape ls (c-1) rs)
exec (GoLeft:prog) (Tape ls c rs) =
  let (hd,tl) = uncons ls in exec prog (Tape tl hd (c:rs))
exec (GoRight:prog) (Tape ls c rs) =
  let (hd,tl) = uncons rs in exec prog (Tape (c:ls) hd tl)
exec (Output:prog) tape = do
  printAsChar (cell tape)
  exec prog tape
exec (Input:prog) (Tape ls _ rs) = do
  n <- getChar
  exec prog (Tape ls (digitToInt n) rs)
exec (Loop loop:prog) tape @ (Tape ls 0 rs) = exec prog tape
exec again@(Loop loop:prog) tape = do
  tape' <- exec loop tape
  exec (if (cell tape') == 0 then prog else again) tape'

uncons :: [Int] -> (Int,[Int])
uncons [] = (0,[])
uncons (x:xs) = (x,xs)

printAsChar :: Int -> IO ()
printAsChar i = putStr $ [chr i]

main = do
  tape <- execute $ parse helloWorld
  putStrLn $ "\n" ++ show tape ++ "\n"

helloWorld =
  ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++" ++
  "[<++++>-]<.>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------." ++
  "[-]>++++++++[<++++>-]<+.[-]++++++++++."

[Edit]

parseOp can be simplified to:

ops = [('+', Plus),('-', Minus),('<',GoLeft),('>',GoRight),('.',Output),(',',Input)]

parseOp :: [Char] -> Maybe (Op, [Char])
parseOp ('[':cs) = case parseOps cs of
  (prog, (']':cs')) -> Just (Loop prog, cs')
  _ -> Nothing
parseOp (c:cs) = fmap (flip (,) cs) $ lookup c ops
parseOp [] = Nothing


texts:
I have a browserify module I've made for resizing two divs I have beside each other. The idea is that I have two panes with a bar between them which I can grab and drag to resize the panes. As one pane gets bigger the other gets smaller. It's not really that important for the code review that this is a browserify module, if you're not familiar with it, you can just focus at the Javascript in the module.

Feedback on the code, especially the Javascript module, is greatly appreciated. Also, feel free to nitpick as long as you specify when you're doing so.

;(function () {
    const $ = require("jquery");

    module.exports = function (dragbarElementId, leftElementPaneId, rightElementPaneId, paneContainerElementId) {
        const $paneContainer = $(`#${paneContainerElementId}`);
        const $dragbar = $(`#${paneContainerElementId} #${dragbarElementId}`);
        const $leftPane = $(`#${paneContainerElementId} #${leftElementPaneId}`);
        const $rightPane = $(`#${paneContainerElementId} #${rightElementPaneId}`);

        let dragging = false;

        // Todo: Load these from previous session.
        let leftPanePercentage = 50;
        let rightPanePercentage = 50;

        function setInitialPaneSizes() {
            if ($leftPane && $rightPane) {
                const unit = $paneContainer.width() / (leftPanePercentage + rightPanePercentage);
                $leftPane.width(unit * leftPanePercentage);
                $rightPane.width(unit * rightPanePercentage);
            }
        }

        $(document).on("ready", setInitialPaneSizes);
        $(window).on("resize", setInitialPaneSizes);

        if ($dragbar) {
            $dragbar.on("mousedown", (mousedownEvent) => {
                mousedownEvent.preventDefault();
                dragging = true;
                let prevPageX = mousedownEvent.pageX;

                $(document).on("mousemove", (mousemoveEvent) => {
                    if (dragging) {
                        if ($leftPane && $rightPane) {
                            const deltaPageX = mousemoveEvent.pageX - prevPageX;
                            prevPageX = mousemoveEvent.pageX;
                            $leftPane.width($leftPane.width() + deltaPageX);
                            $rightPane.width($rightPane.width() - deltaPageX);
                            leftPanePercentage = 100 / $paneContainer.width() * $leftPane.width();
                            rightPanePercentage = 100 / $paneContainer.width() * $rightPane.width();
                        }
                    }
                });

                $(document).on("mouseup", () => {
                    if (dragging) {
                        dragging = false;
                        $(document).unbind("mousemove");
                    }
                });
            });
        }
    };
}());

I have adapted the code to work on JSFiddle, so you can now try a working version here.


texts: Opening a CSV file in Python, with error handling

texts:
Trying to improve my function, as will be used by most of my code. I'm handling most common exception (IOError) and handling when data has no values.

READ_MODE = 'r'

def _ReadCsv(filename):
  """Read CSV file from remote path.

  Args:
    filename(str): filename to read.
  Returns:
    The contents of CSV file.
  Raises:
    ValueError: Unable to read file
  """
  try:
    with open(filename, READ_MODE) as input_file:
      data = input_file.read()
      if not data:
        raise ValueError('No data available')
  except IOError as e:
    logging.exception(e)
  return data


texts:
I have a search box for searching for people in a list of names.
Here is the code that runs every time the query changes.  I could not find anything open-sourced for this, so I wanted to make sure this looks good and efficient.

How does it look?

private final List<String> mTotalNames = ............ // some ArrayList<String> with all the names
private final List<String> mAvailableNames = new ArrayList<String>(mTotalNames);

private void doOnQueryTextChange(final String s) {
    mAvailableNames.clear();
    if (s.length() <= 0) {
        mAvailableNames.addAll(mTotalNames);
    } else {
        final String query = s.toLowerCase();
        for (String name : mTotalNames) {
            name = name.toLowerCase();
            final List<String> partNameList
                    = new LinkedList<String>(Arrays.asList(name.split("\\s+")));
            if (helper0(query, partNameList)) {
                mAvailableNames.add(user);
            }
        }
    }
    // yeah, out mAvailableNames is all updated
}

private static boolean helper0(final String query, final List<String> partNameList) {
    for (String partQuery : query.split("\\s+")) {
        if (!helper1(partQuery, partNameList)) {
            return false;
        }
    }
    return true;
}

private static boolean helper1(final String partQuery, final List<String> partNameList) {
    if (partQuery.trim().length() <= 0) return true;
    final Iterator<String> iterator = partNameList.iterator();
    while (iterator.hasNext()) {
        final String partName = iterator.next();
        if (partName.startsWith(partQuery)
                || partName.trim().length() <= 0) {
            iterator.remove();
            return true;
        }
    }
    return false;
}


texts: A little next combination program in C++

texts:
An implementation of next combination function at Discrete Mathematics and Its Applications, Rosen p.438.

How it works:

Input:

The size n of a integer set {1, 2, ..., n}, which is where you choose objects from.
The size r of the subset of the integer set you currently have.
A pointer to the subset you currently have.

Output: The next subset in lexicographic order.

If you want to play around here is a link to ideone.com.

#include <iostream>
using std::cout;

// C(n, r) and provide the current subset a of size r.
bool nextCombination(int n, int r, int *a);
void printArray(int *a, int n);

int main() {
    int a[] = {1,2,3}; // So the current subset is {1,2,3} of size 3.
    int length = sizeof(a)/sizeof(*a);
    int count = 0;
    // The following example is C(7,3), start at {1,2,3}
    do {
        printArray(a, length);
        count++;
    } while (nextCombination(7, length, a));
    cout << "Total: " << count << '\n'; // Since we start from {1,2,3}, all C(7,3) subsets are generated and counted. The answer should be 7!/(3!4!)=35
    return 0;
}

bool nextCombination(int n, int r, int *a) {
    int lastNotEqualOffset = r-1;
    while (a[lastNotEqualOffset] == n-r+(lastNotEqualOffset+1)) {
        lastNotEqualOffset--;
    }
    if (lastNotEqualOffset < 0) {
        cout << "the end\n";
        return false;
    }
    a[lastNotEqualOffset]++;
    for (int i = lastNotEqualOffset+1; i<r; i++) {
        a[i] = a[lastNotEqualOffset]+(i-lastNotEqualOffset);
    }
    return true;
}

void printArray(int *a, int n) {
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    cout << '\n';
}

The overview of its output:

1 2 3
1 2 4
1 2 5
1 2 6
1 2 7
1 3 4
...
4 5 6
4 5 7
4 6 7
5 6 7
the end
Total: 35


texts:
I implemented a vector class in C for integers. Any feedback welcome.

header:

#define DEFAULT_CAPACITY 1000

// Define a vector type
typedef struct
{
  int nrOfElements;     // Current number of elements.
  int capacity; // Possible capacity.
  int *data;    // Pointer to array elements.
} CVectorInt;

typedef enum {VECTOR_SUCCESS, VECTOR_OUTOFBOUNDS, VECTOR_MEMORYERROR} vector_error;

vector_error CVectorInit(CVectorInt *vector);
vector_error CVectorAppend(CVectorInt *vector, int value);
vector_error CVectorGet(CVectorInt *vector, int index, int * value);
vector_error CVectorSet(CVectorInt *vector, int index, int value);
void CVectorFree(CVectorInt *vector);

.c:

#include "CVectorInt.h"
#include <stdio.h>
#include <stdlib.h>

vector_error CVectorInit(CVectorInt *vector)
{
    int i = 0;

    vector->capacity = DEFAULT_CAPACITY;
    vector->nrOfElements = 0;
    vector->data = malloc(sizeof(int) * vector->capacity);
    if(vector->data == NULL)
        return VECTOR_MEMORYERROR;

    // Initialization in C never hurts.
    for(i = 0; i<DEFAULT_CAPACITY; i++)
        vector->data[i] = 0;

    return VECTOR_SUCCESS;
}

vector_error CVectorAppend(CVectorInt *vector, int value)
{
    int * ptr = NULL;
    int i = 0;

    // Resize vector if there is no space for more elements.
    if(vector->capacity == vector->nrOfElements)
    {
        vector->capacity *= 2;
        ptr = realloc(vector->data, vector->capacity * sizeof(int));
        if(ptr == NULL)
        {
            return VECTOR_MEMORYERROR;
        }
        else
        {
            vector->data = ptr;

            // Initialize new elements to 0.
            for(i = vector->nrOfElements; i<vector->capacity; i++)
                vector->data[i] = 0;
        }
    }

    vector->data[vector->nrOfElements++] = value;

    return VECTOR_SUCCESS;

}

vector_error CVectorGet(CVectorInt *vector, int index, int * value)
{
    if(index < vector->nrOfElements && index >= 0)
    {
        // Pass value at given index.
        *value = vector->data[index];
        return VECTOR_SUCCESS;
    }else
    {
        return VECTOR_OUTOFBOUNDS;
    }
}

vector_error CVectorSet(CVectorInt *vector, int index, int value)
{
    if(index >= vector->capacity)
        return VECTOR_OUTOFBOUNDS;

    vector->data[index] = value;

    return VECTOR_SUCCESS;

}

void CVectorFree(CVectorInt *vector)
{
  free(vector->data);
}

Usage:

#include <stdio.h>
#include <stdlib.h>
#include "CVectorInt.h"

int main(void)
{
    //error handling omitted for simplicity

    CVectorInt v;
    int i = 0, temp = 0;

    CVectorInit(&v);
    for(i = 0; i<100; i++)
    {
        CVectorAppend(&v, i*2);
    }

    for(i = 0; i<100; i++)
    {
        CVectorGet(&v, i, &temp);
        printf("%d ", temp);
    }

    CVectorFree(&v);

    return 0;
}


texts: Use of getters and setters with a car information example

texts:
I have very quickly mocked this up as an example model in Angular JS:

.factory('car', function() {
  function car(serial, name, type, manufacturer)
    //intended to be private
    var serial = serial;
    var name = name;
    var type = type;
    var manufacturer = manufacturer;

    this.getSerial = function() {
      return this.serial;
    }

    this.setSerial = function(newSerial) {
      this.serial = newSerial;
    }
});

There would be getters and setters for every property, and there is a legitimate need for getters and setters for all of them.

I am not a hardcore JavaScript developer, but I have been reading that providing getters and setters for every property is bad practice and providing them in general is bad practice.

Let's say there is a legitimate need for getters and setters for all of the properties, is it still bad practice?
Would other developers do it another way? I have also seen developers writing about it doing in completely different ways

I am after encapsulation of these properties and I assume that this is a good way to go about it.


texts: Ltree inverse crossing function using high order functions

texts:
I was solving some Haskell exercises as a way to refresh some of the language concepts.

I encounter the following exercise:

data LTree a = Leaf a | Fork (LTree a) (LTree a)

crossing :: LTree a -> [(a,Int)]
crossing (Leaf x) = [(x,0)]
crossing (Fork e d) = map(\(x,y) -> (x,y+1)) (crossing e ++ crossing d)

The above function basically takes a Ltree and turns into a list of pars (Lists the tree leaves, along with their depth).

The exercise is to make a function build :: [(a,Int)] -> LTree a, that does the inverse of the crossing function, such as build (crossing a) = a for any 'a' tree.

What I have done so far:

build :: [(a,Int)] -> LTree a
build l = fst (multConvert (map (\(x,n) -> (Leaf x, n)) l))

multConvert :: [(LTree a,Int)] -> (LTree a,Int)
multConvert [x] = x
multConvert l = multConvert (convert l)

convert :: [(LTree a,Int)] -> [(LTree a,Int)]
convert [] = []
convert [x] = [x]
convert ((a,b):(c,d):xs) | b == d = ((Fork a c),(b-1)):xs
                         | otherwise = (a,b):convert ((c,d):xs)

Basically, I turn the list produce by the crossing into an list of (LTree,a) , for example [(3,3),(4,3)..] becomes [(Leaf 3, 3), (Leaf 4, 3)...]. The convert function will take this  list of (LTree,a) and turn consecutive elements with the same depth into a Fork with both elements. For example [(Leaf 3, 3), (Leaf 4, 3), (Leaf 5, 2)...] becomes [(Fork (Leaf 3) (Leaf 4),2), (Leaf 5, 2)...]. Note, that the new produced element have a depth-1.

multConvert function will apply the above idea on the list, over and over, until this list have only one element. This element will represent the original tree. In other words, my algorithm builds the Ltree using a bottom up approach.

I would like to know if there is a more robust way to solve this problem. For example using high order functions, instead of explicitly recursive (possibly using foldr).


texts:
I am pretty new to Swift, as a solo developer I was wondering if somebody could pass comments on the singleton implementation below. The code does work, but being new to Swift and knowing that there are a lot of gotchas, I wanted to get some feedback from someone more experienced.

// Test Singleton Swift 1.2
class FGSingleton {
    static var instance: FGSingleton!
    var gameScore: Int = 0

    // SHARED INSTANCE
    class func sharedInstance() -> FGSingleton {
        self.instance = (self.instance ?? FGSingleton())
        return self.instance
    }

    // METHODS
    init() {
        println(__FUNCTION__)
    }
    func displayGameScore() {
        println("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}

Tests:

FGSingleton.sharedInstance().displayGameScore()
FGSingleton.sharedInstance().incrementGameScore(100)
FGSingleton.sharedInstance().incrementGameScore(1)
FGSingleton.sharedInstance().displayGameScore()
FGSingleton.sharedInstance().incrementGameScore(1000)
FGSingleton.sharedInstance().displayGameScore()

Output:

init()
displayGameScore() 0
displayGameScore() 101
displayGameScore() 1101


texts:
The code along with the utils module is also at github. If you'd also have any advice on how the whole crate is structured I'd love to hear it. :)

use std::ascii::AsciiExt;
use std::str;

use utils::hex_to_bytes;
use s1c2::fixed_xor;

/// Scores ASCII test represented by byte array. The higher the score, the more common
/// English characters the text contains. Letter frequencies are taken from
/// https://en.wikipedia.org/wiki/Letter_frequency.
fn score_text(text: &[u8]) -> f32 {
    let frequencies = "xzqkjupnlgeyihrmfsdcbwaot";
    let text = str::from_utf8(text).unwrap();

    let score: usize = text.chars().map(|letter| {
        frequencies.find(letter.to_ascii_lowercase()).unwrap_or(0)
    }).sum();

    score as f32/text.len() as f32
}

/// Tries to decrypt text encrypted with a single character XOR
/// encryption.
pub fn decrypt_xor(ciphertext: &str) -> Option<(char, String)> {
    let cipherbytes = hex_to_bytes(ciphertext);
    let mut max = 0.0;
    let mut best_solution = None;

    // 32 to 127 should cover printable ASCII characters
    for character in 32..128 {
        let cipher = vec![character; cipherbytes.len()];
        let plaintext = fixed_xor(&cipherbytes, &cipher);
        let score = score_text(&plaintext);
        if score > max {
            max = score;
            best_solution = Some((character as char, String::from_utf8(plaintext).unwrap()));
        }
    }

    best_solution
}

#[test]
fn test_score_text() {
    assert_eq!(score_text(b"x"), 0.0);
    assert_eq!(score_text(b"Z"), 1.0);
    assert_eq!(score_text(b"$"), 0.0);
    assert_eq!(score_text(b"zZz"), 1.0);
}

#[test]
fn test_decrypt_xor() {
    assert_eq!(decrypt_xor("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"),
               Some(('X', "Cooking MC's like a pound of bacon".to_string())));
}


texts: Swift extension: Dictionary to JSON string for URL parameter

texts:
Here's a quick extension for [String: AnyObject] dictionaries in Swift. The output needs to be in the following format (order and spacing don't matter):

{"key": "val", "keywdict": {"anotherKey": 100, "Key2": "Val2"}, "strings": ["string", "another"]}

I am wondering if there's a better way, or if this can be improved.

extension Dictionary //...

func toJSONString() -> String {
  var pcs = [String]()
  for (key, val) in self {
    var valStr = ""
    if let val = val as? String {
      valStr = "\"\(val)\""
    } else if let val = val as? Dictionary<String, AnyObject> {
      valStr = val.toJSONString() // recursion for nested dictionaries
    } else if let val = val as? Array<String> {
      let tmpStr = "\",\"".join(val)
      valStr = "[\"\(tmpStr)\"]"
    } else if let val = val as? NSNumber {
      valStr = "\(val)"
    }
    pcs.append("\"\(key)\":\(valStr)")
  }
  return "{" + ",".join(pcs) + "}"
}


texts:
I'm making an API call in my parent component in React. I'm making a weather app, and theres two different endpoints I'm getting data from. I'm getting 5 day forecast, and the current weather data.
I have two separate functions for the API calls, and I then call them functions in the componentDidMount function. I'm using async/await and I'm trying to avoid try/catch blocks.
import React from 'react';
import WeatherOverview from './WeatherOverview';
import { catchErrors } from '../helpers'

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            forecasts: {
                error: null,
                isLoaded: false,
                forecasts: []
            },
            currentForecast: {
                error: null,
                isLoaded: false,
                forecast: []
            }
        }

        this.getForecastedWeather = this.getForecastedWeather.bind(this);
        this.getCurrentWeather = this.getCurrentWeather.bind(this);
    }

    async getForecastedWeather(){
        const endpoint = `http://dataservice.accuweather.com/forecasts/v1/daily/5day/207931?apikey=mG0ISFW1ZGGHIV3rs5CSFQlF92CYSqhr&language=en&details=true&metric=true`;

        const fetchPromise = await fetch(endpoint).catch((error) => {
            this.setState(state => ({
                forecasts: {
                    ...state.forecasts,
                    error,
                    isLoaded:false
                },
            }));
        });

        if(fetchPromise){
            const result = await fetchPromise.json();
            this.setState(state => ({
                forecasts: {
                    ...state.forecasts,
                    error: null,
                    isLoaded:true,
                    forecasts:result.DailyForecasts
                },
            }));
        }
    }

    async getCurrentWeather(){
        const endpoint = `http://dataservice.accuweather.com/currentconditions/v1/207931?apikey=mG0ISFW1ZGGHIV3rs5CSFQlF92CYSqhr&language=en&details=true&metric=true`;

        const fetchPromise = await fetch(endpoint).catch((error) => {
            this.setState(state => ({
                currentForecast: {
                    ...state.currentForecast,
                     error,
                     isLoaded:false
                },
            }));
        });

        if(fetchPromise){
            const result = await fetchPromise.json();
            this.setState(state => ({
                currentForecast: {
                    ...state.currentForecast,
                    error: null,
                    isLoaded: true,
                    forecast: result
                },
            }));
        }
    }

    componentDidMount(){
        const currentWeather = catchErrors(this.getCurrentWeather);
        const forecastedWeather = catchErrors(this.getForecastedWeather);

        currentWeather();
        forecastedWeather();
    }

    render() {
        return (
            <div className="weather-data">
                <WeatherOverview weather={this.state.forecasts} currentWeather={this.state.currentForecast} />
            </div>
        )
    }
}

export default App;


texts:
My task is to code something that prints out this:

This is what I have done so far.

diag matrix = diag2 [] [] matrix where
 diag2 []  []           []       = []
 diag2 xss []           (zs:zss) =     diag2 []       (reverse $ zs:xss) zss
 diag2 xss ((y:ys):yss) zss      = y : diag2 (ys:xss) yss                zss
 diag2 xss ([]    :yss) zss      =     diag2 xss      yss                zss
 diag2 xss []           []       =     diag2 []       (reverse xss)      []

Is there an easier way to code this?  Also, how can I solve it if this is a very big matrix?


texts:
I have written a quick sort routine to inplace sort an array in descending order:

module sort
  contains
    recursive subroutine qsort_self(array)
      real(kind=8)    :: array(:), temp
      integer :: length, pivot, i, j

      i = 0
      j = 0
      length = 0
      pivot = 1
      temp = 0
      length = size(array)
      if (length > 1) then
        i = 2
        j = size(array)
        do while (i <= j)
           do while (array(j) < array(pivot))
            j = j - 1
          enddo
          do while ((array(i) > array(pivot)) .and. (i<=length))
            i = i + 1
          enddo
         if (i > j) exit
          temp = array(j)
          array(j) = array(i)
          array(i) = temp
          i = i + 1
          j = j - 1
        enddo
          temp = array(pivot)
          array(pivot) = array(j)
          array(j) = temp
          pivot = j
          call qsort_self(array(1:pivot-1))
          call qsort_self(array(pivot + 1 : length))
      endif
    end subroutine qsort_self
  end module sort

program p
  use sort
  implicit none
  integer :: size_,i
  real(kind=8), allocatable    :: b6(:)

  size_ = 100
  allocate(b6(size_))
  do i = 1, size_
    b6(i) = real(rand(), 8)
  enddo
  print *, "unsorted: ", b6
  call qsort_self(b6)
  print *,"sorted a= ", b6
end program p

It works fine for now, but without .and. (i<=length) part of code, i run into errors where if array is in ascending order, i goes out of bound. I checked several online implementations, such as this:

https://stackoverflow.com/questions/11196571/quick-sort-sorts-descending-not-ascending

and I believe they suffer from same flaw. Is here any better way of doing it?
I Always want to take first element as pivot because of the array structure.


texts:
I have written an algorithm to find the largest palindrome under a given number, but I am sure my code loses efficiency by creating new arrays in every pass. I am currently learning about efficiency so I have the following question: Can anyone suggest a more efficient (faster) approach and explain why this approach is more efficient?

int number = 0;
int palindrome = 0;

for (int i = 1; i < 999999; i++)
{
    number = i;
    string s = number.ToString();
    char[] charArray = s.ToCharArray();
    char[] charArrayReversed = new char[charArray.Length];
    Array.Copy(charArray, charArrayReversed, charArray.Length);

    Array.Reverse(charArrayReversed);
    bool isEqual = Enumerable.SequenceEqual(charArray, charArrayReversed);
    if (isEqual)
        palindrome = number;
}

Console.Write(palindrome);
Console.ReadLine();


texts:
I wrote a program to copy a .doc template, add some text to it, then save and close it.  I have to do this many times, and saving and closing a word document is slow. I decided to use multi-threading, but I'm a noob at this stuff and just wrote what came to me. Any feedback would be greatly appreciated (on any aspect, not just the multi-threading).

Here is my code for a task:

public Task
{
    public string Value;
    public bool HasRun;
    public Task(string value)
    {
        Value = value;
        HasRun = false;
    }
}

I create a list of Tasks that is a class level variable, accessible by all threads:

Tasks = db.table.select(a => new Task(a.value)).ToList();

Next, I run the following in each thread:

while(tasks.Any(a => a.HasRun == false))
{
    var value = "";
    lock(tasks)
    {
        var task = tasks.Where(a => a.HasRun == false).First();
        value = task.Value;
        task.HasRun = true;
    }

    CreateNewDocumentAppendValueAndSave(value);
}


texts: Collect all fields having given Modifier(s)

texts:
I want to collect all fields which have given Modifier(s) of a class. I have written following pieces of codes:

/**
 * Method getFields
 * @author TapasB
 * @since 03-Nov-2013 - 2:03:17 pm
 * @version DAM 1.0
 * @param instanceClass
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<Field> getFields(Class<?> instanceClass) {
    List<Field> fields = new ArrayList<Field>();
    Class<?> searchType = instanceClass;

    while (!Object.class.equals(searchType) && searchType != null) {
        fields.addAll(Arrays.asList(searchType.getDeclaredFields()));
        searchType = searchType.getSuperclass();
    }

    return Collections.unmodifiableList(new ArrayList(selectDistinct(fields, "name")));
}

/**
 * Method getFields
 * @author TapasB
 * @since 03-Nov-2013 - 2:31:59 pm
 * @version DAM 1.0
 * @param instanceClass
 * @param includedModifiers
 * @param excludedModifiers
 * @return
 */
public static List<Field> getFields(Class<?> instanceClass, int[] includedModifiers, int[] excludedModifiers) {
    List<Field> fields = getFields(instanceClass);
    List<Field> filteredFields = new ArrayList<Field>();

    if(ArrayUtils.isEmpty(includedModifiers)) {
        filteredFields.addAll(fields);
    } else {
        for(Field field : fields) {
            boolean fieldCanBeAdded = false;

            for(int includedModifier : includedModifiers) {
                if((includedModifier & field.getModifiers()) != 0) {
                    fieldCanBeAdded = true;
                }
            }

            if(fieldCanBeAdded) {
                filteredFields.add(field);
            }
        }
    }

    if(ArrayUtils.isNotEmpty(excludedModifiers)) {
        Iterator<Field> fieldIterator = filteredFields.iterator();

        while (fieldIterator.hasNext()) {
            Field field = fieldIterator.next();
            boolean fieldNeedsToBeRemoved = false;

            for(int excludedModifier : excludedModifiers) {
                if((excludedModifier & field.getModifiers()) != 0) {
                    fieldNeedsToBeRemoved = true;
                }
            }

            if(fieldNeedsToBeRemoved) {
                fieldIterator.remove();
            }
        }
    }

    return Collections.unmodifiableList(filteredFields);
}

The method getFields(Class<?> instanceClass) searchs for fields in an iterative manner to all the super classes of the given class and stops at Object.

Here the selectDistinct is the method of LambdaJ API. It removes the fields with same name which is present in the parent class also in child class.

I was wondering if it is a good way to achieve what I want.

To run it:

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    int[] includedModifiers = new int[]{Modifier.PRIVATE};
    int[] excludedModifiers = new int[]{Modifier.FINAL};
    List<Field> fields = getFields(ArrayList.class, includedModifiers, excludedModifiers);

    for(Field field : fields) {
        System.out.println(field.getName());
    }
}

The main will print only the fields which have modifier only private and exclude the private final.

There is no issue so far I found with this code. I just want to know if there is any better solution exists or not.


texts: Pair elements of two lists by condition without reusing elements

texts:
I have two lists that I want to join on a condition. Unlike in a relational algebra join, if more than one element of each list can be matched, only one should be selected, and shouldn't then be reused.
Also, if any of the elements of the first list don't match any of the second list, the process should fail.

Example:

# inputs
list1 = [{'amount': 124, 'name': 'john'},
         {'amount': 456, 'name': 'jack'},
         {'amount': 456, 'name': 'jill'},
         {'amount': 666, 'name': 'manuel'}]
list2 = [{'amount': 124, 'color': 'red'},
         {'amount': 456, 'color': 'yellow'},
         {'amount': 456, 'color': 'on fire'},
         {'amount': 666, 'color': 'purple'}]
keyfunc = lambda e: e['amount']

# expected result
[({'amount': 124, 'name': 'john'}, {'amount': 124, 'color': 'red'}),
 ({'amount': 456, 'name': 'jack'}, {'amount': 456, 'color': 'yellow'}),
 ({'amount': 456, 'name': 'jill'}, {'amount': 456, 'color': 'on fire'}),
 ({'amount': 666, 'name': 'manuel'}, {'amount': 666, 'color': 'purple'})]

I've written a working implementation in Python, but it seems clunky, unclear and inefficient:

def match(al, bl, key):
    bl = list(bl)
    for a in al:
        found = False
        for i, b in enumerate(bl):
            if key(a) == key(b):
                found = True
                yield (a, b)
                del bl[i]
                break
        if not found:
            raise Exception("Not found: %s" % a)

result = list(match(list1, list2, key=keyfunc)