texts:
I want to generate statistical reports and I have many different where clauses so the function became long. I did much refactoring, but it is not enough. Can someone help me with some techniques that these techniques make the function short and easily readable?

public static function allRejUserByProv($prov = '', $gender = '', $dist = '', $ttc = '')
    {
        if (!empty($gender) && !empty($prov) && !empty($dist))
        {
            return self::where('decision', '3')->where('gender', $gender)->where('p_province', $prov)->where('p_district', $dist)->count();
        }
        if (!empty($prov) && !empty($dist))
        {
            return self::where('decision', '3')->where('p_province', $prov)->where('p_district', $dist)->count();
        }
        if (!empty($prov) && !empty($gender))
        {
            return self::where('decision', '3')->where('p_province', $prov)->where('gender', $gender)->count();
        }
        if(!empty($gender) && !empty($ttc))
        {
            return self::where('decision', '3')->where('ttc_name', $ttc)->where('gender', $gender)->count();
        }
        if(!empty($ttc))
        {
            return self::where('decision', '3')->where('ttc_name', $ttc)->count();
        }
        if (!empty($gender))
        {
            return self::where('decision', '3')->where('gender', $gender)->count();
        }
        if (!empty($prov))
        {
            return self::where('decision', '3')->where('p_province', $prov)->count();
        }

        return self::where('decision', '3')->count();
    }

I am calling the function like this:

public function resultTTC($prov, $dist, $ttc)
{
return [
  'rejected'             => number_format(self::allRejUserByProv($prov, '', $dist, $ttc)),
        'rejected_male'        => number_format(self::allRejUserByProv($prov, '1', $dist, $ttc)),
        'rejected_female'      => number_format(self::allRejUserByProv($prov, '2', $dist, $ttc)),

]


texts: Any way of simplifying the following two short snippets regarding Dictionary?

texts:
Example 1

if (myList.ContainsKey(myKey))
{
    myList[myKey]++;
}
else
{
    myList.Add(myKey,1);
}

Example 2

Where(x =>
(myList.ContainsKey(x.Key) ? x.Value - myList[x.Key] : x.Value) >

myList is Dictionary.

Is there any way or existing method of simplifying or normalizing the code?

Update

Now I've learned Python and came across defaultdict:

Analogue of Python's defaultdict?
Dictionary returning a default value if the key does not exist


texts: Code duplication where impliment extension method for IEnumerable and IQueryable on entity set

texts:
Since Entity Set does not support asqueryable, I have to do this.  How can I reduce the amount of redundant code between the two methods?

public static IQueryable<T> WhereCreateWithin<T>(this IQueryable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
    if (beginDayParam == null)
    {
        beginDayParam = DateTime.Today;
    }

    DateTime beginDay = beginDayParam.Value.Date;
    DateTime startRange;
    DateTime endRange;

    switch (timeRange)
    {
        case DateManager.TimeRange.All:

            return query;

        case DateManager.TimeRange.ThisYear:

            startRange = new DateTime(beginDay.Year, 1, 1); // January 1, this year
            endRange = startRange.AddYears(1);

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ThisMonth:

            startRange = new DateTime(beginDay.Year, beginDay.Month, 1);
            endRange = startRange.AddMonths(1).Date;

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ThisWeek:

            startRange = BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday);
            endRange = startRange.AddDays(6);

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ToDay:

            return query.Where(p => p.create_date.Date == beginDay);

        case DateManager.TimeRange.Last30Day:
            startRange = beginDay.AddDays(-29);
            endRange = beginDay;

            return query.Where(p => p.create_date.Date >= startRange && p.create_date <= endRange);
    }
    return query;
}

public static IEnumerable<T> WhereCreateWithin<T>(this IEnumerable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
    if (beginDayParam == null)
    {
        beginDayParam = DateTime.Today;
    }

    DateTime beginDay = beginDayParam.Value.Date;
    DateTime startRange;
    DateTime endRange;

    switch (timeRange)
    {
        case DateManager.TimeRange.All:

            return query;

        case DateManager.TimeRange.ThisYear:

            startRange = new DateTime(beginDay.Year, 1, 1); // January 1, this year
            endRange = startRange.AddYears(1);

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ThisMonth:

            startRange = new DateTime(beginDay.Year, beginDay.Month, 1);
            endRange = startRange.AddMonths(1).Date;

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ThisWeek:

            startRange = BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday);
            endRange = startRange.AddDays(6);

            return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);

        case DateManager.TimeRange.ToDay:

            return query.Where(p => p.create_date.Date == beginDay);

        case DateManager.TimeRange.Last30Day:
            startRange = beginDay.AddDays(-29);
            endRange = beginDay;

            return query.Where(p => p.create_date.Date >= startRange && p.create_date <= endRange);
    }
    return query;
}


texts:
There are two keys: the main is aes128 and the second is XTEA, used just for randomization of data inside the AES. Randomization is done with secret random key that is not know even if someone knows exactly what is encrypted. Also the key is produced by doing hash many number of times and this hash is salted with the iv so it is not possible to make a dictionary attack with precomputed hashes.

function aes128ctr_en($data,$key,$hash_rounds = 0) {
    //iv is created
    $iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
    //internal secret random string is created so no one knows what
    //is exactly encoded by main cipher
    $xtea = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
    //password is hashed in many rounds to prevent dictionary attack,
    //hashing is done with individual iv for hmac so it make no sense to use
    //precalculated hashes
    for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
    //string is randomized for use in aes, so no one knows what actually will be encoded
    //this is not actual encoding so password is stored inside with xtea encoded string,
    //second half of this password is used as IV for xtea
    //again: THIS IS NOT ACTUAL ENCODING
    $data = $xtea.mcrypt_encrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
    //hash is added to check if return string is really what we looked for,
    //must match with string on decoding
    $data = hash('md5',$data,true).$data;
    //actual encoding, IV is prepended to encrypted string
    return $iv.mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv);
}

function aes128ctr_de($data,$key,$hash_rounds = 0) {
    $iv = substr($data,0,16);
    $data = substr($data,16);
    for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
    $data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
    $md5 = substr($data,0,16);
    $data = substr($data,16);
    if (hash('md5',$data,true)!==$md5) return false;
    $xtea = substr($data,0,16);
    $data = substr($data,16);
    return mcrypt_decrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
}

$key = 'suPer_secret aAnd L10ng ppswrd$%';
$encrypted = aes128ctr_en('the bomb will blow up at 1 pm',$key,12345);
echo aes128ctr_de($encrypted,$key,12345);

I really don't have knowledge to make it better. I'm not that educated in all this to read RFCs and make algorithms out of it. I'm also constrained to methods that are precompiled in core PHP binary as I want these methods to be able to run on remote servers.


texts: Add many objects to a collection in a JavaScript object

texts:
I'm trying to add a lot of objects manually into a collection.  The best I can figure out is to define an object, create an add method, and call that add method multiple times in the object's constructor.

function FieldMap(){
    FieldMap.prototype.add=function(listField,formField,fieldType){
        this[listField]={
            'formField':formField,
            'fieldType':fieldType
        }
    }

    this.add('Status','StatusName','select');
    this.add('Builder','Build Org','select');
    this.add('Route','RouteName','input');
    this.add('DocVersion','Doc Version','input');

    //...  and so on for maybe 20 entries
}

I know that it would be easier to read the data in from a file, but for various reasons, that's not an option here.  Is there a more efficient way to do this?


texts:
As I'm reading the Java code of some other people, I found him using an approach of assigning a format string to a variable and using the variable for String.format in the code:

private final static String URI_SUFFIX_FORMAT = "view/%s";

@Inject
private UriBuilder uriBuilder;

public void buildUriForMusic(String dir)
{
    ...
    String ret = uriBuilder.buildContentUri(dir, String.format(URI_SUFFIX_FORMAT, "music"));
    ...
}

public void buildUriForBook(String dir)
{
    ...
    String ret = uriBuilder.buildContentUri(dir, String.format(URI_SUFFIX_FORMAT, "book"));
    ...
}

I don't like the use of URI_SUFFIX_FORMAT in the above code because I cannot tell what that String.format is trying to compose and if the number of Strings passed in is correct or not.

I prefer to do this instead:

private String formatUriWithSuffix(String dir, String service)
{
    return uriBuilder.buildContentUri(dir, String.format("view/%s", service));
}

public void buildUriForMusic(String dir)
{
    ...
    String ret = formatUriWithSuffix(dir, "music");
    ...
}

public void buildUriForBook(String dir)
{
    ...
    String ret = formatUriWithSuffix(dir, "book");
    ...
}

What do you think? Which one is better, for what reasons? Do you have a better approach?


texts:
I tried following the official solution of LC975 (https://leetcode.com/problems/odd-even-jump/), using a monotonic stack - i.e., I reimplemented their solution (Approach 1) from python in C++.
TLDR Problem statement: Given an array of ints A, "good index" is an index from which the last element of A can be reached, through a series of consecutive "odd" and "even" jumps.
Odd jump (1st, 3rd, 5th jump) from index "i" is defined as jump to the smallest element to the right, greater or equal to the current element (A[i]); Even jump (2nd, 4th,...) -> is defined as jump from index "i" to the largest element to the right, smaller or equal to the current element, A[i]. In case of equality, the element with the lowest index is chosen.
Return the number of "good" indices.
[Update]: Fixed a bug, passing A by reference instead of value, in the sort lambda -- which fixes the Time Limit Exceeded.
int oddEvenJumps(vector<int>& A) {
  int N = static_cast<int>(A.size());
  // Compute odd and even jump indices, i.e. where we can jump from here
  std::vector<int> odd_next(N, 0);
  std::vector<int> even_next(N, 0);

  // First, sort indices in A, by value.
  for (int ii = 0; ii < N; ++ii) {
    odd_next[ii] = ii;
    even_next[ii] = ii;
  }

  // Sort indices in increasing order by value.
  std::sort(odd_next.begin(), odd_next.end(), [&A](int a, int b) {
    if (A[a] == A[b]) {
      return a < b;}
    else {
      return A[a] < A[b];
    }
  });

  // Sort indices in decreasing order, for even jumps.
  //Update: previously -- [A](int a, int b) -- passed A by value -- which was slow.
  std::sort(even_next.begin(), even_next.end(), [&A](int a, int b){
    if (A[a] == A[b]) {
      return a < b;
    }
    else {
      return A[a] > A[b];
    }
  });

  // Convert the sorted indices into next jump index,
  // using a monotonic stack.
  odd_next = make_vec(odd_next);
  even_next = make_vec(even_next);

  // Store a flag if from the current index, through an odd jump or
  // even jump respectively, we can reach the last element.
  vector<int> odd(N, 0);
  vector<int> even(N, 0);

  odd[N - 1] = 1;
  even[N - 1] = 1;

  // Go backwards, and mark reachable elements.
  for (int ii = N - 2; ii >= 0; --ii) {
    if (odd_next[ii] != -1) {
      odd[ii] = even[odd_next[ii]];
    }
    if (even_next[ii] != -1) {
      even[ii] = odd[even_next[ii]];
    }
  }

  int res = 0;
  for (int jj = 0; jj < N; ++jj){
    res += odd[jj];
  }

  return res;
}

// Use monotonic stack to find the element to jump to, i.e.
// the closest larger or closest smaller element.
inline std::vector<int> make_vec(const std::vector<int>& v){
  std::vector<int> result(v.size(), -1);
  stack<int> st;
  for (int x: v){
    while (!st.empty() && x > st.top()) {
      result[st.top()] = x;
      st.pop();
    }
    st.push(x);
  }
  return result;
}

However, this implementation doesn't pass few tests, resulting in time limit exceeded.
The complexity of the algorithm should be O(N log N), dominated by the two sort loops.
make_vec according to my understanding, is O(N), because each element in the vector gets on the stack only once.
How could I improve this code, in particular performance?


texts: Rustacious way of checking if string ends with any suffix from a selection

texts:
What's the best way to check if a String ends with any of multiple suffixes in Rust?

I have a working, naive solution:

fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {
    for suffix in &suffixes {
        if s.ends_with(suffix) {
            return true;
        }
    }
    false
}

Note: suffixes could have varying lengths

As I am quite new to Rust, I would very much appreciate any/all suggestions about how my code can better leverage Rust idioms.

Here are some test cases I need to function pass

#[test]
fn empty_suffixes() {
    let s = String::from("5m");
    let suffixes = vec![];

    assert!(!string_ends_with_any(s, suffixes))
}

#[test]
fn empty_string_has_no_suffix() {
    let s = String::from("");
    let suffixes = vec!["txt"];

    assert!(!string_ends_with_any(s, suffixes))
}

#[test]
fn string_ends_with_first_suffix() {
    let s = String::from("foo.txt");
    let suffixes = vec!["txt", "csv"];

    assert!(string_ends_with_any(s, suffixes))
}

#[test]
fn string_ends_with_last_suffix() {
    let s = String::from("foo.csv");
    let suffixes = vec!["txt", "csv"];

    assert!(string_ends_with_any(s, suffixes))
}

#[test]
fn string_doesnt_end_with_any_suffix() {
    let s = String::from("foo.csv");
    let suffixes = vec!["txt", "tsv"];

    assert!(!string_ends_with_any(s, suffixes))
}

#[test]
fn string_ends_in_suffix_but_case_is_wrong() {
    let s = String::from("foo.csv");
    let suffixes = vec!["txt", "Csv"];

    assert!(!string_ends_with_any(s, suffixes))
}


texts:
How idiomatic is my code? Since Lua does not have classical inheritance such as in OO languages. Feedback on the test and implementation are both appreciated/welcomed.

The rules are:

If the phone number is less than 10 digits assume that it is bad number
If the phone number is 10 digits assume that it is good
If the phone number is 11 digits and the first number is 1, trim the 1 and use the first 10 digits
If the phone number is 11 digits and the first number is not 1, then it is a bad number
If the phone number is more than 11 digits assume that it is a bad number

local PhoneNumber = {}

function PhoneNumber:new(no_as_string)
  self.__index = self
  local n = "0000000000"
  n = no_as_string:gsub("[^0-9]", "")
  if (n:len() == 11 and n:sub(1, 1) == "1") then
    n = n:sub(2, 11)
  else
    if (n:len() > 10 or n:len() < 10) then
      n = "0000000000"
    end
  end
  return setmetatable({ number = n }, self)
end

function PhoneNumber:areaCode(symbol)
  return self.number:sub(1, 3)
end

function PhoneNumber:toString(symbol)
  return "("..self.number:sub(1, 3)..") "..self.number:sub(4, 6).."-"..self.number:sub(7, 10)
end

return PhoneNumber

Here is the test:

local PhoneNumber = require('phone-number')

describe("PhoneNumber()", function()
  it("cleans the number (123) 456-7890", function()
    local phone = PhoneNumber:new("(123) 456-7890")
    assert.are.equals(phone.number,"1234567890")
  end)

  it("cleans numbers with dots", function()
    local phone = PhoneNumber:new("123.456.7890")
    assert.are.equals(phone.number,"1234567890")
  end)

  it("valid when 11 digits and first digit is 1", function()
    local phone = PhoneNumber:new("11234567890")
    assert.are.equals(phone.number,"1234567890")
  end)

  it("invalid when 11 digits", function()
    local phone = PhoneNumber:new("21234567890")
    assert.are.equals(phone.number,"0000000000")
  end)

  it("invalid when 9 digits", function()
    local phone = PhoneNumber:new("123456789")
    assert.are.equals(phone.number,"0000000000")
  end)

  it("has an area code", function()
    local phone = PhoneNumber:new("1234567890")
    assert.are.equals(phone:areaCode(),"123")
  end)

  it("formats a number", function()
    local phone = PhoneNumber:new("1234567890")
    assert.are.equals(phone:toString(),"(123) 456-7890")
  end)
end)


texts: Finding terminal server user is connected on

texts:
I'm trying to find out which terminal server a user is connected to.
Currently I'm trying to cycle through each server and check if he is connected.

$servers = @("server01","server02","server03","server04","server05","server06","server07","server08")

foreach ($server in $servers ) {
    $WMI = Get-WmiObject -Class Win32_Process -ComputerName $server -ErrorAction Stop
    $ProcessUsers = $WMI.getowner().user | Select-Object  -Unique
    if ( $ProcessUsers.Contains("user")) {
        $userServer = $server
        break
    }
}
echo $userServer

This can take some time depending on the server the user is connected too. Is there any better way to check this with PowerShell?


texts:
This is my invoicing program I made for myself to keep track of purchases people made from me. (Yes I know eBay does this for me but I wanted to see what I could make.) Basically it can search the invoice file for a keyword (the invoice number) or lets you enter a new invoice to a file named usb.txt. It is usb.txt because I was selling USB cables at the time.

#Invoice Entering Program Ebay

print("Ebay Invoice Program\n")

while True:
    file = input("Enter 0 to Quit. Enter S to Search The File. Press ENTER to Input new Entries *Case Sensitive*: " )
    if file == "0":
        print("Exiting Program...")
        break
    elif file=="S":
        keyword = input("Enter Invoice Number to Search For: ")
        look_in = "usb.txt"
        search_file = open(look_in,"r")
        with open(look_in, "r") as search_file:
            for line in search_file:
                if keyword in line:
                    print(line)

    else:

        Name = input("Enter Buyer Name: ")
        InNum = input("Enter Ebay Invoice Number: ")
        Quant = int(input("Enter Amount Bought: "))
        Price = Quant * 5
        with open("usb.txt", "at")as out_file:
            out_file.write(
                "Name: %s || Invoice Number: %s || Quantity: %s || Price:$ %s \n\n" % (Name, InNum, Quant, Price))
            out_file.close()
            print("File edits made")

I'm pretty new to python and programming in general. If you have any suggestions on how I could improve it or any ideas to add functionality I'd love to hear it! This was written in python 3.5.1.


texts: Determining if a palindrome exists in a linked list using recursion

texts:
Summary of code:

This code recurses through half of the LinkedList, "adding" the left half node's to the call stack. Then, once at the middle, the code returns the first node of the right side (or more accurately, it assigns it to a variable, "right_node"). As the call stack collapses, the code compares the left nodes with the right nodes, and the right node is assigned to right node's next node.

The full code and updates are available here.

Specific questions:

I have a recursive function with two base cases, and both involve returning True, but each have to do a different step beforehand. Is there a better way to write out this if else statement structure?

This is the code snippet that features the if/else structure:

def recurse(head, length, node):
    if length == 1:  # odd number of nodes
        node[0] = head.next
    if length == 0:  # even number of nodes
        node[0] = head
    if length == 0 or length == 1:
        return True

    recurse(head.next, length/2, node)


texts:
This script allows you to practice your typing skills, as soon as you finish typing a new word appears for a non-stop typing experience. The code has in memory the top 100 words as per the Pareto Principle and Zipf's Law, of these, the top 10 are more common than the rest.

To start, type start.

Tested in Linux, Python 3.4 but should work in any version in any OS.

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import random

FONT = (None, 50)
WORDS = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 'day', 'most', 'us']

new_word = lambda: random.choice(random.choice((WORDS[0:len(WORDS)//10], WORDS)))

root = tk.Tk()
root.title("Typing trainer")

text_to_copy = tk.Label(root, text = "start", font=FONT)
text_to_copy.pack()

typing_ground = tk.Entry(root, font=FONT)
typing_ground.pack()

points = tk.Label(root, text = "Score: 0", font=FONT)
points.pack()

def if_equal_delete_and_take_other_phrase(ev):
    if text_to_copy.cget("text") == typing_ground.get():
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = new_word()
        points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

root.bind('<Key>', if_equal_delete_and_take_other_phrase)

root.mainloop()


texts:
I wrote some code to determine the additions and deletions that happened to a sorted slice after each (sorted) update.

Git repository (includes some tests)

Godoc

// Package slicediff is a utility to determine the additions and deletions that happened to a sorted slice after each update.
//
// All the slices are assumed to be sorted!
package slicediff

import "container/list"

// SliceDiff stores the current state of the sorted slice
type SliceDiff struct {
    l *list.List
}

// New creates a new SliceDiff
func New() *SliceDiff {
    return &SliceDiff{
        list.New(),
    }
}

// Append appends a slice at the end of the SliceDiff
//
// sa is assumed to be sorted
func (sd *SliceDiff) Append(sa []string) {
    for _, s := range sa {
        sd.l.PushBack(s)
    }
}

// SortedDiff compares the updated slice with l and returns the additions and deletions performed
//
// updated is assumed to be sorted
func (sd *SliceDiff) SortedDiff(updated []string) (additions []string, deletions []string) {
    if sd.l.Len() == 0 {
        sd.Append(updated)
        additions = make([]string, len(updated))
        copy(additions, updated)
        return additions, make([]string, 0)
    }

    e := sd.l.Front()

    additions = make([]string, 0)
    deletions = make([]string, 0)

    for _, s := range updated {
        // Delete the small elements at the beginning of the list
        for e != nil && e.Value.(string) < s {
            deletions = append(deletions, e.Value.(string))
            e = removeAndGetNext(sd.l, e)
        }

        if e == nil {
            // End of list is empty: simply push it
            additions = append(additions, s)
            sd.l.PushBack(s)
        } else if s == e.Value.(string) {
            // Same as current element: skip it
            e = e.Next()
        } else {
            // Smaller than current element: insert it
            additions = append(additions, s)
            sd.l.InsertBefore(s, e)
        }
    }

    // delete end of the list
    for e != nil {
        deletions = append(deletions, e.Value.(string))
        e = removeAndGetNext(sd.l, e)
    }

    return additions, deletions
}

func removeAndGetNext(l *list.List, e *list.Element) (next *list.Element) {
    next = e.Next()
    l.Remove(e)
    return
}

Example:

// Create a new SliceDiff
sd := New()

// Add some initial elements
sd.Append([]string{
    "a",
    "b",
    "d",
})

// Perform an update
update := []string{
    "a",
    "b",
    "c",
}
add, del := sd.SortedDiff(update)

// Get the diff
fmt.Println(add, del)
// Output: [c] [d]

I'm interested to know if my implementation is correct (all the tests are passing, but maybe I missed something) and if my "Go-style" can be improved.


texts: Add-to-cart method has too many conditions

texts:
I have a method that seems to be too much for one method. I might be validating programming methodology. I just don't know what to do with it. Would a switch statement be better? Should I break it up and provide other methods?

public void addToCart(OrderlineType orderline) throws Exception
{

        if (orderline == null)
        {
            throw new OutOfStockException("Null object pass addToCart");
        }

        if(orderline.getProduct().isRecallStatus())
        {
             throw new ProductRecallException("Product Id: " + orderline.getProduct().getProductId()
                     + " is being Recalled");
        }

        int tempOrderlineQuantity = orderline.getQuantity();
        int tempOrderlineProductId = orderline.getProduct().getProductId();

        if( Inventory.getInstance().getQuantity(tempOrderlineProductId)
                        == tempOrderlineQuantity  )
          {
                   shoppingCart.add(orderline);
                   log.warn("Product " + orderline.getProduct().getProductName()
                           +" ID: "+ tempOrderlineProductId
                           + "after purchase will have no more in stock");

          }
        else if(Inventory.getInstance().getQuantity(tempOrderlineProductId)
                        > tempOrderlineQuantity)
          {
                    shoppingCart.add(orderline);
          }
        else if(Inventory.getInstance().getQuantity(tempOrderlineProductId)
                            == -1)

          {
                        throw new OutOfStockException("PrductId: " + tempOrderlineProductId
                                + " is not listed in the Inventory: "
                                + Inventory.getInstance().getQuantity(tempOrderlineProductId));

           }
         else
          {
                        throw new OutOfStockException("PrductId: " + tempOrderlineProductId
                                                    + " does not have enough to complete this order, the in Stock amount is: "
                                                    + Inventory.getInstance().getQuantity(tempOrderlineProductId));
          }
}


texts:
I am using a Deep Learning model I trained and want to improve its accuracy by implementing a rolling average prediction. I have already done it but want to improve it as I am making predictions on every 3 frames.
Input:
Each index represents a class and the respective prediction the model makes.
Order is not alphanumeric as its based on my folder structure during training
1st Index : Class 0
2nd Index : Class 10
3rd Index : class 5
[
  0.9288286566734314,
  0.008770409040153027,
  0.062401000410318375,
]

So the goal is to store the highest probability and its index at every frame. Based on the structure I mentioned above I add the probability to its class. Every time a new probability gets added I increase a counter. Once the counter reaches N, I find the class which has the most predictions, I sum the probabilities and return the average of it and the respective class it belongs to.
N = 5
Prediction {
"0": [0.9811,0.9924, 0.8763],
"5": [0.9023],
"10": [0.9232]
}

Code in React(model is loaded on a mobile phone)
Rolling Prediction does the averaging of the predictions and is passed in the array of predictions mentioned in the input.
There are 2 helper functions to find the sum and to find the max value and max index in an array.
  const [allPredictions, setAllPredictions] = useState({
    "0": [],
    "5": [],
    "10": []
  });
  let queueSize = 0;
  let total = 0;

  const rollingPrediction = arr => {
    const { max, maxIndex } = indexOfMax(arr);
    const maxFixed = parseFloat(max.toFixed(2));
    if (maxIndex === 0) {
      allPredictions["0"].push(maxFixed);
      queueSize += 1;
    } else if (maxIndex === 1) {
      allPredictions["10"].push(maxFixed);
      queueSize += 1;
    } else if (maxIndex === 2) {
      allPredictions["5"].push(maxFixed);
      queueSize += 1;
    }
    console.log(`Queue : ${queueSize}`);
    if (queueSize > 4) {
      console.log("Queue Size Max");
      const arr1 = allPredictions["0"].length;
      const arr2 = allPredictions["5"].length;
      const arr3 = allPredictions["10"].length;

      if (arr1 > arr2 && arr1 && arr3) {
        const sum = sumOfArray(allPredictions["0"]);
        const prob = sum / arr1;
        console.log(`Awareness level 0 | Probability: ${prob}`);
      } else if (arr2 > arr1 arr2 && arr3) {
        const sum = sumOfArray(allPredictions["5"]);
        const prob = sum / arr2;
        console.log(`Awareness level 5 | Probability: ${prob}`);
      } else if (arr3 > arr2 arr3 && arr1) {
        const sum = sumOfArray(allPredictions["10"]);
        const prob = sum / arr3;
        console.log(`Awareness level 10 | Probability: ${prob}`);
      } else {
        console.log("No rolling prediction");
      }
      queueSize = 0;
      allPredictions["0"] = [];
      allPredictions["5"] = [];
      allPredictions["10"] = [];
    }
  };

  const sumOfArray = arr => {
    for(let i = 0; i < arr.length; i++){
        total += arr[i];
    }
    return total;
  };

  const indexOfMax = arr => {
    if (arr.length === 0) {
      return -1;
    }
    let max = arr[0];
    let maxIndex = 0;

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] > max) {
        max = arr[i];
        maxIndex = i;
      }
    }
    return {
      max,
      maxIndex
    };
  };


texts: Generating a random maze using disjoint sets

texts:
I've had a go at writing something that generates a random maze using disjoint sets using the grouping class I found here.

The way I'm generating the maze is by generating all the cells, with each cell having a wall to the right of it and beneath it. Each wall can either be active or not.

I pick wall at random and look at the pair of cells on either side of it to see if they are in the same group (connected), if they are, I leave the wall, if they aren't, I destroy the wall, and join the groups the neighbouring cells belonged to.

This will continue until all the cells are connected. I'm then trying to print the maze, probably in a really horrible way.

I'd really like to get some feedback on anything I could be doing better. Is it possible to make the code more efficient? If I do a 1000*1000 maze, it takes a very long time to calculate.

import random
from grouper import Grouper
import sys

X = 20
Y = 20

class Cell():
    """Represents a cell in the maze, with an x and y coordinate and its
    right hand wall and downwards wall.

    """
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.right_wall = self.down_wall = None

class Wall():
    """Represents a wall in the maze with its two neighbouring cells.
    """
    def __init__(self):
        self.neighbours = None
        self.active = True

def popchoice(seq):
    """Takes an iterable and pops a random item from it.
    """
    return seq.pop(random.randrange(len(seq)))

# A mapping of coord tuple to Cell object
cells = {}
# A list of all the non-edge walls
walls = []

# Generate cells
for y in range(Y):
    for x in range(X):
        cells[(x, y)] = Cell(x, y)

# Generate walls and add to the neighbouring cells
for y in range(Y):
    for x in range(X):
        current_cell = cells[(x,y)]
        down_wall = Wall()
        current_cell.down_wall = down_wall
        right_wall = Wall()
        current_cell.right_wall = right_wall
        if y != Y-1:
            down_wall.neighbours = (current_cell, cells[(x,y+1)])
            walls.append(down_wall)

        if x != X-1:
            right_wall.neighbours = (current_cell, cells[(x+1,y)])
            walls.append(right_wall)

# Get a list of all the cell objects to give to the Grouper
cell_list = [cells[key] for key in cells]

maze = Grouper(cell_list)

for _ in range(len(walls)):
    # Pop a random wall from the list and get its neighbours
    wall = popchoice(walls)
    cell_1, cell_2 = wall.neighbours
    # If the cells on either side of the wall aren't already connected,
    # destroy the wall
    if not maze.joined(cell_1, cell_2):
        wall.active = False
        maze.join(cell_1, cell_2)

# Draw the maze

maze_map = []

x_max = (X*2)+1
y_max = (Y*2)+1

# Make an empty maze map with True for wall and False for space
# Make top wall
maze_map.append([True for _ in range(x_max)])
for y in range(1, y_max):
    # Make rows with left side wall
    maze_map.append([True]+[False for _ in range(1, x_max)])

# Add the down and right walls from each cell to the map
for coords, cell in cells.items():
    x, y = coords
    # Add the intersection wall for each cell (down 1 right 1)
    maze_map[(y*2)+2][(x*2)+2] = True
    if cell.right_wall.active:
        maze_map[(y*2)+1][(x*2)+2] = True
    if cell.down_wall.active:
        maze_map[(y*2)+2][(x*2)+1] = True

def output(string):
    sys.stdout.write(string)

# Print the map
for row in maze_map:
    for tick in row:
        if tick: output('X'),
        else: output('.'),
    output('\n')

It gives a maze like this:

XXXXXXXXXXXXXXXXXXXXX
X.......X...X.X.X...X
XXX.XXXXXXX.X.X.X.XXX
X.X...............X.X
X.XXXXXXXXX.XXXXX.X.X
X...X...X.X.X.......X
X.XXXXX.X.X.XXXXXXXXX
X.X.X.....X...X...X.X
X.X.XXX.XXX.XXXXX.X.X
X.X...X.........X...X
X.XXX.XXX.X.XXX.X.XXX
X...X.X.X.X.X.X.X.X.X
XXX.X.X.XXX.X.XXX.X.X
X.................X.X
XXXXX.XXX.XXXXX.X.X.X
X...X.X.X.X...X.X.X.X
XXX.XXX.X.XXX.X.XXX.X
X.X...X...X.....X...X
X.X.X.XXX.X.X.XXX.X.X
X...X.....X.X.....X.X
XXXXXXXXXXXXXXXXXXXXX


texts: Factorial number in Rust for learning purposes

texts:
I'm currently trying to learn the basics of the Rust programming language, to do this my first piece of code after the classic 'Hello World' was a simple recursive Factorial function.

This is the code:

use std::io;

fn factorial(num: i64) -> i64 {
    return if num == 1 {
        1
    }else{
        num * factorial(num - 1)
    }
}

fn trim_newline(s: &mut String){
    if s.ends_with('\n'){
        s.pop();
        if s.ends_with('\r'){
            s.pop();
        }
    }
}

fn main() {
    let mut user_input = String::new();
    println!("Welcome to rust-factorial!");
    loop {
        user_input.clear();
        println!("Please enter a number:");
        match io::stdin().read_line(&mut user_input) {
            Ok(_) => (),
            Err(_e) => {
                println!("error: {}", _e);
                continue;
            },
        };
        let num: i64 = match user_input.trim().parse::<i64>() {
            Ok(n) => n,
            Err(_e) => {
                trim_newline(&mut user_input); // remove trailing newline
                println!("'{}' is not a valid number, full error: {}", user_input, _e);
                continue;
            },
        };
        println!("{}! is equal to {}", num, factorial(num));
    }
}

I am aware of one major issue with my current approach which is that the biggest number this program can calculate is the 20th number of the sequence. Asking for a number bigger than 20 results in the following error on my machine:

Please enter a number:
24
thread 'main' panicked at 'attempt to multiply with overflow', src\main.rs:7:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\rust-factorial.exe` (exit code: 101)

I'd like to know a few things:

How can I change this code to be more "rust-like"

(by that I mean 'pythonic' but for rust)

What would the rust approach be for solving the overflow that happens with numbers past 20?

(I could either hard-code the limit or something to that effect but I'm curious whether or not there is a guideline about this from a Rust perspective)

Any and all comments on code quality, readability and potentially efficiency


texts:
I'm wondering if some PS gurus can advise on whether my method for sorting and recombining some data fields by using an array of PSCustomObjects is as efficient as it might be.

I'm importing a CSV file that contains a number of person details, including Full Names in a single field that have a variety of separators between first and last names (e.g. comma, space, comma + space, semicolon, etc). Last name comes first. Sanitising those variants is also an objective.

The dataset needs to be sorted by last name and reassembled with a single FullName field. Doing a simple sort by the FullName field doesn't work reliably given the variety of delimiters between the name parts.

I've attempted it creating an array of new PSCustomObjects that comprises of all the original fields from the CSV plus the Full Name field split into two new name fields. It's then sorted by the last name, and the results are stored in a new array ready for output, joining the previously-split name fields back together with a comma and space.

Any suggestions for better efficiency welcome.

$data = import-csv .\Cust.csv
# CSV fields: FullName, StreetAddress, City, Postcode
# Create a temporary array for sorting
$splitNames = @()
# Split "FullName" into separate name parts and add all to temp array
$data | foreach {
    $spltName = $_.FullName -split '[\s|,|;]+'
    $splitNames += [PSCustomObject]@{
        Last = $spltName[0]
        First = $spltName[1]
        StreetAddress = $_.StreetAddress
        City = $_.City
        Postcode = $_.Postcode
    }
}
# Create an output array to hold the final result
$sortedNames = @()
# Sort the temporary array by lastname, rejoin name field and add to output array
$splitNames | Sort Last | foreach {
    $FullName = $_.Last, $_.First -join ', '
    $sortednames += [PSCustomObject]@{
        FullName = $Fullname
        StreetAddress = $_.StreetAddress
        City = $_.City
        Postcode = $_.Postcode
    }
}
$sortednames

Sample data - first row is the header:

"FullName","StreetAddress","City","Postcode"
"Bloggs,Joe","1 Some Street","City","1001"
"Bloggs Jane","1 Some Street","City","1001"
"Bloggs;Jill","1 Some Street","City","1001"
"Bloggs, Jo","1 Some Street","City","1001"


texts: Reflecting changes in the DataGridView back on the List and then updating database

texts:
I have a DataGridView on the UI (a win form) and objects in the List <Earnings> are shown in the Grid.

View

class Form
{
    public BindingSource EarningDetails
    {
        set {dgEmployeeEarnings.DataSource= value;}
    }
}

Presenter Class

class WagePresenter
{
    BindingSource BS = new BindingSource();

    private void ShowEarnings()
    {
        bS.DataSource = _WageManager.PrepareEarnings ();
        _WageView.EarningDetails = BS;
    }
}

WageManager Class

class WageManager
{
    public List<Earning> PrepareEarnings()
            {
                return GetEarningObjedtList(CalculateEarnings(WagePeriodStartDate, WagePeriodEndDate));
            }

            private DataTable CalculateEarnings(DateTime startDate, DateTime endDate)
            {
                return _DataService.GetEarnings(startDate, endDate);
            }

            private List<Earning > GetEarningObjedtList(DataTable dt)
            {

                var convertedList = (from rw in dt.AsEnumerable()
                                     select new Earning()
                                     {
                                          EmployeeID=Convert.ToInt32(rw[0]),
                                          WorkDays= Convert.ToInt32 (rw[2]),
                                          DayOffs = Convert.ToInt32(rw[3]),
                                          LeaveDays  = Convert.ToInt32(rw[4]),
                                          ExtraShifts = Convert.ToInt32(rw[5]),
                                          ExtraShiftAmount = Convert.ToDecimal (rw[7]),
                                          BasicSalaryAmount = Convert.ToDecimal(rw[8]),
                                          BudjetoryAllowance = Convert.ToDecimal(rw[9]),
                                          NoPayDays = Convert.ToInt32(rw[10]),
                                          LessNoPayAmount = Convert.ToDecimal(rw[11]),
                                          AmountForEPF = Convert.ToDecimal(rw[12]),
                                          OverTimeAmount = Convert.ToDecimal(rw[13]),
                                          BroughtForwardAmount = rw[14] == DBNull.Value ? 0 : Convert.ToDecimal(rw[14]),
                                     }).ToList();

                return convertedList;
            }
}

Since this is MVP pattern, the DataSet returned from the service is converted to a list of Models (Earning) and then it's passed to the view by the presenter as a BindingSource.

All objects in the List are properly shown on the grid. Now What I'm trying to do is when user do the changes in the grid those changes should be reflected in the list (in object properties) and then it should be updated in the database.

Is it possible to do this with Lists/ ILists?
Any other notable flows in this approach?


texts:
Working on some documentation lately, I had a need to convert a number of asynchronous serial waveforms into ASCII graphics characters.  Rather than draw them by hand, I decided to write a program to do it for me.  I'm interested in a code review, and particularly if there are smarter/shorter ways of coding the class.

#include <iostream>
#include <vector>
#include <string>
#include <bitset>

class waveform
{
public:
    waveform(std::string &s) : data_(s) {}
    std::vector<bool> to_bits() const
    {
        std::vector<bool> bits;
        bits.reserve(data_.size() * 10);
        for (auto &ch : data_) {
            bits.push_back(0); // start bit
            for (int mask=1u; mask != 0x100; mask <<= 1) {
                bits.push_back(ch & mask);
            }
            bits.push_back(1); // stop bit
        }
        return bits;
    }
    friend std::ostream& operator<<(std::ostream& out, const waveform& w) {
        auto bits = w.to_bits();
        bool last = 1;
        for (const auto &b : bits) {
            out << (b ? "+---" : (last ? "+   " : "    "));
            last = b;
        }
        out << '\n';
        last = 1;
        for (const auto &b : bits) {
            out << (b != last ? "|   " : "    ");
            last = b;
        }
        out << '\n';
        last = 1;
        for (const auto &b : bits) {
            out << (b ? (last ? "    " : "+   ") : "+---");
            last = b;
        }
        out << '\n';
        int special = 0x201;
        for (const auto &b : bits) {
            if (special & 1) {
                out << (b ? "  P " : "  S ");
            } else {
                out << (b ? "  1 " : "  0 ");
            }
            special >>= 1;
            if (special == 0)
                special = 0x201;
        }
        out << '\n';
        return out;
    }
private:
    std::string data_;
};

Sample driver

int main()
{
    std::string msg{"ST"};
    std::cout << waveform(msg) << std::endl;
}

Sample output

+   +---+---+       +---+   +---+   +---+           +---+   +---+   +---+   +---
|   |       |       |   |   |   |   |   |           |   |   |   |   |   |   |
+---+       +---+---+   +---+   +---+   +---+---+---+   +---+   +---+   +---+
  S   1   1   0   0   1   0   1   0   P   S   0   0   1   0   1   0   1   0   P

Note that in this diagram, S stands for a start bit, P stands for a stop bit and the 8 data bits are sent least significant bit first.


texts: Throw an exception which contains a nested set of previous exceptions

texts:
I have a set of domain objects which try to find a solution to a problem.

The top level object has an algorithm which splits up the problem and delegates it to lower level objects, which in turn do the same.

I want the top level algorithm to throw an exception if it did not find any solutions, giving a breakdown of possible causes.

My question is, how should(n't) this be implemented?

The way I was thinking of doing this:

The algorithms at all levels throw an exception if it fails to find a solution.

For a given level, call it the parent algorithm, it would accumulate exceptions thrown by its children, and if all attempts by its children throw an exception, the parent will itself throw an exception which contains its childrens' exceptions.

My implementation is as follows:

class ExceptionWithCauses extends \Exception {

    private $causes = array();

    public function addCause(\Exception $ex){
        $this->causes[] = $ex;
        $this->message .= "\n".$ex->getMessage();
    }

}

I'm using it like this:

function findAnOption()
{
    $noOptionsException = new ExceptionWithCauses("findAnOption(): No options found");

    $possibilities = array(1, 2, 3, 4);
    foreach ($possibilities as $possibility)
    {
        try {
            useOption($possibility);
            return $possibility;
        } catch (Exception $e) {
            $noOptionsException->addCause($e);
        }
    }
    throw $noOptionsException;
}

function useOption($x)
{
    if ($x < 5){
        throw new ExceptionWithCauses("useOption(): $x is too small");
    }
    return $x;
}

And when findAnOption() is called, a exception is thrown with the following message:

findAnOption(): No options found
useOption(): 1 is too small
useOption(): 2 is too small
useOption(): 3 is too small
useOption(): 4 is too small

I'm worried that this is bad practice. I've read that exceptions should only be used in exceptional circumstances. So with that in mind, perhaps I should only be throwing an exception at the top level. But then at that top level, how should the exception accumulate details on what was tried by lower levels? The only time that information will be needed is when the top level throws that exception, so in a way it makes sense that it's all handled by exceptions, and that I have exceptions at every level?

On the one hand, this question on Programmers SE explains why using exceptions in control-flow is an anti-pattern, but at the same time, it seems like the tidiest way of accumulating a log for why a top level exception occurred?


texts: Cumulative sum of the smallest neighbors in the previous row in a Numpy array

texts:
I have the following code snippet, which essentially does the following:
Given a 2d numpy array, arr, compute sum_arr  as follow:
$$sum\_arr[i, j] = \begin{cases}
    arr[i, j] + min(sum\_arr[i - 1, j-1:j+2]), &i > 0\\ arr[i, j], &i = 0\end{cases}$$
(reasonable indices for j - 1 : j + 2 of course, all within 0 and w)

Here's my implementation:

import numpy as np

h, w = 1000, 1000 # Shape of the 2d array
arr = np.arange(h * w).reshape((h, w))

sum_arr = arr.copy()

def min_parent(i, j):
    min_index = j
    if j > 0:
        if sum_arr[i - 1, j - 1] < sum_arr[i - 1, min_index]:
            min_index = j - 1
    if j < w - 1:
        if sum_arr[i - 1, j + 1] < sum_arr[i - 1, min_index]:
            min_index = j + 1
    return (i - 1, min_index)

for i, j in np.ndindex((h - 1, w)):
    sum_arr[i + 1, j] += sum_arr[min_parent(i + 1, j)]

And here's the problem: this code snippet takes way too long to execute for only 1e6 operations (About 5s on average on my machine)

What is a better way of implementing this?


texts:
I have a MVC WinForms application. I am using Dependency Injection with Ninject as the IoC container.

public class SqlObjectExplorerController : ToolController, ISqlObjectExplorerController
{
    private ISqlObjectExplorerView view = null;
    private SqlServerStructureProvider structureProvider;
    private IProgress<IProgressInfo> progress;

    public SqlObjectExplorerController(ISqlObjectExplorerView view)
    {
        if (view == null)
            throw new ArgumentNullException("view");

        this.view = view;
        InitializeEventHandlers();
        ...
    }

    private void InitializeEventHandlers()
    {
        (view as ToolView).Initialize += new EventHandler(async (s, e) => await RefreshObjectExplorerAsync());
        view.OnRefreshObjectExplorerClicked += new EventHandler(async (s, e) => await RefreshObjectExplorerAsync());
        view.OnAddServerInstanceClicked += new EventHandler(async (s, e) => await AddServerInstanceAsync());
        view.OnNewSqlQueryClicked += new EventHandler<NewSqlQueryRequestEventArgs>((s, e) => OpenNewSqlQueryDocument(e));
        view.OnExpandRequested += new EventHandler<BeforeExpandEventArgs>((s, e) => BuildSubStructureForDatabaseNode(e));
    }

    private async Task RefreshObjectExplorerAsync()
    {
        await InitializeObjectExplorerAsync();
        view.InitializeObjectExplorer(ServerCache);
    }

    ... // Lots more code.

My question concerns the use of async/await in setting up the likes of += new EventHandler(async (s, e) => await RefreshObjectExplorerAsync());. There are some tasks I need to do on a background thread, so I am using async/await, my questions are about my understanding:

In doing async (s, e) => await SomeMethodAsync() I am merely setting up an event handler equivalent to private async void SomeMethodAsync(object s, EventArgs e) { ... }. Which I think is fine in this case of the fire-and-forget Task I want to undertake, is it?
I don't think there are any problems in setting this up these async handlers in the ctor of the controller, am I right?

The code seems to work fine, but is there something I am not seeing?


texts: jQuery dropdown plugin to prevent scanning the whole DOM on every click

texts:
Here is a simple plugin I have written for a jQuery dropdown effect. Simple show / hide (although open classes may be better).

When you click the HTML the event searches the whole DOM for a specific class and then hides it (or removes the open class), even if the dropdown is already close.

Is there a way to only apply the events to open dropdowns somehow?

$.fn.dropdown = function () {

        return this.each(function () {

            // Initial varaibles
            var $this = $(this),
                $toggle = $this.find('.dropdown-toggle'),
                $dropdown = $this.find('.dropdown-menu');

            // When clicking a dropdown toggle
            $toggle.click( function(e){

                // Stop the default behaviour
                e.preventDefault();

                // Clear any open dropdowns
                clearDrops();

                // Stop the event from bubbling up the DOM tree
                e.stopPropagation();

                // Toggle the dropdown
                $dropdown.toggle();

            });

            // Clear the dropdowns
            var clearDrops = function () {
                // Search the entire DOM for dropdowns & hide them
                // THERE MUST BE A BETTER WAY
                $('.dropdown-menu').hide();
            };

            // Trigger the closing of dropdowns when clicking on the HTML
            $('html').bind('click', clearDrops);

        });

    };

$('.dropdown').dropdown();


texts: Notification system using PHP+jQuery+Ajax

texts:
I have this code to display a counter on the side of . I want to know if this code is good on security and perfomance.

I just started using jquery and ajax, i had heard people saying that someone could disable the javascript and do bad things. What you guys think about my code?

                    titutlo

script:

select.php

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

    $status = 'unread';

    $sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND
    userid = :userid");
    $sql->bindParam(':userid', $userid, PDO::PARAM_INT);
    $sql->bindParam(':status', $status, PDO::PARAM_STR);
    $sql->execute();
    $countNT = $sql->rowCount();

    echo $countNT;

    $conn = null;

    ?>

update.php

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE userid = :userid");
$sql->bindParam(':user_id', $userid, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();

echo $countNT;

$conn = null;
?>


texts:
I've prepared a function using cURL to get a remote file to the local storage:

/**
 * cURL - Get Remove File
 *
 * Function using CURL the get a remote file to the local storage.
 *
 * @param str $url              Full remote URL
 * @param str $xml_path         Internal path to the storage the file
 * @param str $xml_file         Filename of the xml file to save
 * @param arr $access           Access credentials (usr;pwd)
 *
 * @return bollean
 */
function get_remote_file($url, $xml_path, $xml_file, $access = null) {

  $curl_handle = curl_init();
  curl_setopt($curl_handle, CURLOPT_HEADER, 0);
  curl_setopt($curl_handle, CURLOPT_URL, $url);
  curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,true);
  if ($access) {
    curl_setopt($curl_handle, CURLOPT_USERPWD, $access["usr"].":".$access["pwd"]);
  }
  curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
  $buffer = curl_exec($curl_handle);
  curl_close($curl_handle);

  if ($buffer != false) {
    file_put_contents($xml_path.$xml_file, $buffer);
    return true;
  }

    return false;

}

While is working fine, even with password protected files, I'm not too comfortable with CURL, so I wonder if this can be optimized or improved.


texts: Has the following query been made in the optimum way?

texts:
SELECT p.name,m.name
FROM parts p
INNER JOIN Manufacturers m ON p.man_id=m.id
ORDER BY p.name DESC

If not, what should be done for its optimization?

Here is the two tables:

CREATE TABLE `Manufacturers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(30) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB

CREATE TABLE `parts` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(30) NOT NULL,
    `man_id` int(11) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB


texts: Storing and iterating over multiple NSError pointers

texts:
How would you refactor this kind of code? I've unsuccessfully tried several approaches (NSArray, NSPointerArray, plain C array), but always ran into pointer type checking error.

NSError *error1;
NSError *error2;
NSError *error3;
//imagine MANY of them
[object1 methodWithError: &error1];
[object2 methodWithError: &error2];
[object3 methodWithError: &error3];
BOOL wasErrorOfCode1 = ([error1 code] == 1) || ([error2 code] == 1) || ([error3 code] == 1);
if (wasErrorOfCode1) {
//do stuff


texts: Determining the next payment renewal date

texts:
I am not very good a JavaScript, surely not date manipulation, but I hacked together the script below with the purpose to determine the next payment renewal date based on a start date and payment term. The script does what it is supposed to do. The script is part of a data transformation, which runs for every row in the data transformation (Pentaho). It has 1.1 million rows, so performance is very important. Who has ideas on increasing performance (currently only 18 rows / sec on my i5).

var renewaldate = new Date(START_DATE.getTime());
var renewalday = START_DATE.getDate();
var renewalmonth = START_DATE.getMonth();
var renewalyear = START_DATE.getYear();
var paymentterm= 12 / PAYMENTS_PER_YEAR;
var today = new Date();

while (renewaldate - today < 0) {
    renewalmonth = renewalmonth + paymentterm;
    if (renewalmonth > 12) {
        renewalmonth = renewalmonth - 12;
        renewalyear++;
    }
    renewaldate.setFullYear(renewalyear, renewalmonth, renewalday);
}


texts: Project Euler Problem 35: counting circular primes below 1 million

texts:
Project Euler Problem 35 asks:

  The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

  How many circular primes are there below one million?

import itertools
import math
import time

prime_list = []
#num = 14
count = 0
limit = 100000
time.clock()

def get_primes(n):
    numbers = set(range(n, 1, -1))
    #primes = []
    while numbers:
        p = numbers.pop()
        prime_list.append(p)
        numbers.difference_update(set(range(p*2, n+1, p)))
    #return primes

get_primes(limit)

print "Done", time.clock()

for r in xrange(2,limit):
    #b = 1
    if r in prime_list:
        #print r,count
        num = str(r)
        if (all(int(num[i:]+num[:i]) in prime_list for i in xrange(len(num)))):
            count += 1
print count,time.clock()

I am generating all possible primes with another function and it is giving me output in 60-80 ms for limit=1000000

Still the loop is taking around 19 seconds for finding cicular prime count under limit=100000


texts:
I decided to start working on the Euler project exercises. I'm doing fine for now but the seventh problem is running quite slow and I can't think of anything to make it work faster. It takes around 1300-1500 ms to finish which doesn't satisfy me while I know it can be done in maybe 20-30 milliseconds.

int index = 1;
List<int> primes = new List<int> { 1 };
int i = primes[index - 1];
Stopwatch sw = new Stopwatch();
sw.Start();
while (primes.Count<10001)
{
    i += 2;
    bool isPrime = true;
    for (int j = 2; j < i / 2; j++)
    {
        if (i%j != 0) continue;
        isPrime = false;
        break;
    }
    if (!isPrime) continue;
    primes.Add(i);
    index++;
}
sw.Stop();
Console.WriteLine(primes[10000]);
Console.WriteLine("Time to calculate in milliseconds : {0}", sw.ElapsedMilliseconds);
Console.ReadKey();


texts:
How does this look?  It has been over a year since my database concepts class and I have never worked with MySQL.  I have chosen InnoDB as my engine because of foreign key support using UTF-8 based on advice from an earlier review.  Everything works as it should when deleting and updating, but I am worried I am doing something that may be considered bad practice.

The main table Tracker manages different survey name and descriptions.  The table Card holds information on each person who has been surveyed.  Survey holds the results of each Card response for the survey being tracked by Tracker and has a unique composite key.

If a cardID is deleted or updated the corresponding composite key of Survey will be deleted or updated.  If  a trackID is deleted or updated this will delete or update the corresponding cardID fields in Card.

ERD design image:

Is this the right way to apply a composite key in this way? Are there any changes that should be made? Are there any suggestions for changes?

CREATE TABLE `Tracker` (
 `trackID` int(11) NOT NULL AUTO_INCREMENT,
 `tName` varchar(40) DEFAULT NULL,
 `tDesc` varchar(200) DEFAULT NULL,
 PRIMARY KEY (`trackID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE `Card` (
 `cardID` int(11) NOT NULL AUTO_INCREMENT,
 `trackID` int(11) NOT NULL,
 `fName` varchar(21) NOT NULL,
 `mName` varchar(1) DEFAULT NULL,
 `lName` varchar(21) DEFAULT NULL,
 `email` varchar(50) NOT NULL,
 `isMember` int(1) NOT NULL,
 PRIMARY KEY (`cardID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE `Survey` (
 `cardID` int(11) NOT NULL,
 `trackID` int(11) NOT NULL,
 `q0` int(1) NOT NULL,
 `q1` int(1) DEFAULT NULL,
 `q2` int(1) DEFAULT NULL,
 `q3` int(1) DEFAULT NULL,
 `q4` int(1) DEFAULT NULL,
 `q5` int(1) DEFAULT NULL,
 PRIMARY KEY (`cardID`, `trackID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE,
 FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;


texts: How do I lessen the memory usage of my solution to LeetCode 495: Teemo Attacking

texts:
How to make changes in my code so that it can take the least memory possible.?
This is a leetcode program , I have tested all the testcases and it has passed, I tried to reduce the memory usage, but by far now, I have not been able to understand.
I want to look into this so that I can understand the usage of memory spaces better. Any input would be helpful. Thank you very much. I will also post the link to the question, but since the logic is already clear to me, The only question is that is this a good solution or memory heavy?
   class Solution {
    public int findPoisonedDuration(int[] timeSeries, int duration) {

        int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
        int numberOfSeconds = duration;

        if (timeSeries.length >0)
            old_goalpost = timeSeries[0]+duration-1;
        else
            numberOfSeconds=0;

        if (timeSeries.length >0)
        for (i=1;i<timeSeries.length;i++)
        {
            new_goalpost =  timeSeries[i]+duration-1;

            diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));

            numberOfSeconds = numberOfSeconds +diff;
            old_goalpost = new_goalpost;

        }
        return numberOfSeconds;

    }
}

the question is this

And it has passed all the test cases.

If you want, this is the link to the question
https://leetcode.com/problems/teemo-attacking/
this code is 99.97% faster but memory heavy
class Solution {
    public int findPoisonedDuration(int[] timeSeries, int duration) {

        int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
        int numberOfSeconds = duration;

        if (timeSeries.length >0)
            old_goalpost = timeSeries[0]+duration-1;
        else
            numberOfSeconds=0;

        if (timeSeries.length >0)
        for (i=1;i<timeSeries.length;i++)
        {
            new_goalpost =  timeSeries[i]+duration-1;
            diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));
            numberOfSeconds = numberOfSeconds +diff;
            old_goalpost = new_goalpost;

        }
        return numberOfSeconds;

    }
}


texts:
How is it and can it be optimised?

sentence = input("Enter a sentence you want to convert to pig latin: ")

sentence = sentence.split()
for i in range(len(sentence)):
    if sentence[i][0] in "aeiou":
        sentence[i] += 'yay'
    else:
        sentence[i]=sentence[i][1:]+sentence[i][0]
        sentence[i]+='ay'
sentence = ' '.join(sentence)

print(sentence)


texts: Implementing a zipwithindex predicate in prolog

texts:
I want to implement a predicate of the form:

zipwithindex(?List1, ?List2)

which is true when the elements of List2 are the same as in List1 but are paired with the index of the element.

This is what I have:

zipwithindex([],I,S,S).
zipwithindex([H|T],I,S0,S):-
  append(S0,[H/I],S1),
  I1 is I+1,
  zipwithindex(T,I1,S1,S).
zipwithindex(List1,List2):-
  zipwithindex(List1,0,[],List2).

Is there a better way to implement this?


texts:
I wrote a calculator in Ruby. These are the rules:

Write the first number, in a new line the      arithmetic operator, and in another line the last number.
Use + for addition, - for subtraction, * for multiplication and / for division.

Implementation:

val1 = gets.to_i
sym = gets.chomp
val2 = gets.to_i

def addition(val1, val2)
    return val1+val2
end

add = addition(val1, val2)

def subtraction(val1, val2)
    return val1-val2
end

sub = subtraction(val1, val2)

def division(val1, val2)
    return val1/val2
end

div = division(val1, val2)

def multiplication(val1, val2)
    return val1*val2
end

mult = multiplication(val1, val2)

if sym == "+"
puts add
elsif sym == "-"
puts sub
elsif sym == "/"
puts div
elsif sym == "*"
puts mult
else puts "error"
end


texts:
I had an assignment recently to build a FixedArray using Ruby. It's supposed to simulate a FixedArray in C, that is, an array that allocates a certain amount of arbitrary memory when initialized, and that this amount of memory can neither increase nor decrease. It cannot dynamically resize itself like Ruby's default Array (because at a low-enough level, there's no such thing as arrays that can resize themselves...only FixedArrays). If you try to access an index that is out of bounds, you get an exception.

Note that I cannot use Ruby's default Array (since that's kinda misses the point of the assignment, in my opinion), so you get something like this:

class OutOFBoundsException < RuntimeError
end

class FixedArray
  attr_reader :size

  def initialize(size)
    @size = size
    size.times do |index|
      self.instance_variable_set(:"@index#{index}", nil)
    end
  end

  def get(index)
    if instance_variable_defined?(:"@index#{index}")
      self.instance_variable_get("@index#{index}")
    else
      raise OutOFBoundsException
    end
  end

  def set(index, value)
    self.instance_variable_set(:"@index#{index}", value)
    value
  end

end

This seems rather hacky to me though. I'm having to use metaprogramming in order to create FixedArrays, and metaprogramming ought to be used as a last resort. Is there a better solution that can allow me to create FixedArrays?


texts: GUI in Tkinter to log events for a web-scraper

texts:
I'm creating a GUI with tkinter that will handle starting/stopping/and logging events for a web-scraper (scraper not created yet).

The current code is working... but I've been gathering my information from so many different sources I'm sort of lost in the mire on how to improve it. The biggest problem right now is that I feel like the loop and stop functions should be removed from the class they are currently in (maybe put in a new class?) but I'm really not sure. Eventually they will be starting/stopping the scraper.

This is essentially a learning experience for me since I'm new to Python and learn best by doing (I know scrapers don't need GUIs). Any suggestions or recommendations on how I can best organize it currently to prepare for later is appreciated as well.

The TextHandler code and comments are from what I found here.

import tkinter as tk
import tkinter.scrolledtext as tkst
from tkinter import ttk
import logging

def popupmsg(msg):
    popup = tk.Tk()
    popup.wm_title("!")
    label = ttk.Label(popup, text=msg)
    label.pack(side="top", fill="x", pady=10)
    b1 = ttk.Button(popup, text="Okay", command=popup.destroy)
    b1.pack()
    popup.mainloop()

class TextHandler(logging.Handler):

    def __init__(self, text):
        # run the regular Handler __init__
        logging.Handler.__init__(self)
        # Store a reference to the Text it will log to
        self.text = text

    def emit(self, record):
        msg = self.format(record)

        def append():
            self.text.configure(state='normal')
            self.text.insert(tk.END, msg + '\n')
            self.text.configure(state='disabled')
            # Autoscroll to the bottom
            self.text.yview(tk.END)

        # This is necessary because we can't modify the Text from other threads
        self.text.after(0, append)

class Menu(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menubar = tk.Menu(container)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Save settings", command=lambda: popupmsg("Not supported just yet!"))
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=quit)
        menubar.add_cascade(label="File", menu=filemenu)

        tk.Tk.config(self, menu=menubar)

class HomePage(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent)

        bottomframe = tk.Frame(root)
        bottomframe.pack(side=tk.BOTTOM)

        topframe = tk.Frame(root)
        topframe.pack(side=tk.TOP)

        topframe = tk.Frame(root)
        topframe.pack(side=tk.TOP)

        st = tkst.ScrolledText(topframe, state='disabled')
        st.configure(font='TkFixedFont')
        st.pack()

        # Create textLogger
        text_handler = TextHandler(st)

        # Add the handler to logger
        logger = logging.getLogger()
        logger.addHandler(text_handler)
        root.flag = True

        def stop():
            root.flag = False

        def loop():
            if root.flag:
                logger.error("error")
                root.after(1000, loop)
            else:
                logger.error("Loop stopped")
                root.flag = True
                return

        startButton = tk.Button(bottomframe, text="Start", command=loop)
        startButton.pack()

        stopButton = tk.Button(bottomframe, text="Stop",  command=stop)
        stopButton.pack()

        exitButton = tk.Button(bottomframe, text="Exit",  command=quit)
        exitButton.pack()

if __name__ == "__main__":
    root = Menu()
    root.wm_title("Scraper")
    HomePage(root)
    root.mainloop()


texts: Exporting array of tabs to new workbooks, save them based on tab name

texts:
Brief:

This is a question geared towards optimization and general better coding practices. I'm self-taught in VBA so I'm cautious of bad practices, but they do come up.

My Reasoning:

I break the links (break_links) because these new files would be sent out and I don't want the external references to cause errors within the spreadsheet formulas. It also makes for better historical files IMO so as the main file is updated we have the historical numbers saved rather than referencing the new numbers.

I did take this component from somewhere online, so I'm still unsure how things work when you put something like (ByRef wb As Workbook) into the sub name ie: when to do it, how to do it, etc.

The Name reference is a cell that has a fiscal year and period labeled for historical files.

My Complaint:

Despite turning off screen updating and all that it still works like a clunky recorded macro where I sit for about 20-30 seconds while it does it's thing, and I'm just exploring to see if there's anything I can do to improve this.

Sub NewWorkbooks()
'This will make seperate workbooks for each of the tabs listed
Dim wb As Workbook
Dim NewBook As Workbook
Dim ws As Worksheet
Dim Name As String
Name = ActiveWorkbook.Worksheets("Reference Tables").Range("_Name")

Call TurnOffFunctions
Set wb = ActiveWorkbook

For Each ws In Workbooks("P&L Master Sheet"). _
Worksheets(Array("Accessories", "Leather", "Residential", "Rugs"))
    ws.Copy
    Set NewBook = ActiveWorkbook
    With NewBook
        Call break_links(NewBook)
        .SaveAs Filename:="C:\Users\Monthly P&L's\Historical Files\" & "P&L " & Name & " - " & ws.Name
        .Close 'SaveChanges:=True
    End With
Next

Call TurnOnFunctions

End Sub
Sub break_links(ByRef wb As Workbook)
Dim Links As Variant
On Error Resume Next
Links = wb.LinkSources(Type:=xlLinkTypeExcelLinks)
On Error GoTo 0

If Not IsEmpty(Links) Then
    For i = 1 To UBound(Links)
        wb.BreakLink _
        Name:=Links(i), _
        Type:=xlLinkTypeExcelLinks
    Next i
End If

End Sub
Private Sub TurnOffFunctions()

    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

End Sub
Private Sub TurnOnFunctions()

    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.DisplayAlerts = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

End Sub


texts: Structured instructions for simple extraction script

texts:
I have a rather simple task in trying to extract keywords from input.dat which looks like:

func1
{
        yes         true;
        keyword123  (1.1 0 -0.3);
        gamma       (0 1 0);
        dir         (1 0 0);
func2
{
        yes         false;
        keyword123  (1.1 0 -0.3);
        gamma       (0 0 1);
        dir         (1 0 0);

In this case I want to get the first entry in the vector of keyword123. If the lines containing the keyword aren't identically, the script should stop with an error. I feel that this should be a one- or twoliner in PERL using RegEx but it took me some time to get the following script:

#!/usr/bin/perl -w

use strict;

my $path = "./input.dat";

# array @grepped of lines containing keyword
my @grepped=();
open(FILE,"$path") or die "error on opening $path: $!\n";
while (my $line = <FILE>) {
        if ($line=~ /keyword123/i){push(@grepped,"$line")};
}
close(FILE);

# get array @unique of unique lines
my %seen;
my @unique = grep {!$seen{$_}++} @grepped;

# continue with $unique if keyword-line is unique
my $unique;
if (scalar @unique eq 1) {
        $unique=$unique[0];
} else {
        die "entry not unique, exiting: $!\n";
}

# get string between brackets
$unique =~ /\((.+?)\)/;
my $final = $1;

# cut after first space
$final =~ s/\s.*//s;
print "keyword123: $final\n";

The script is giving the correct output but this can't be the best work, so any help/hint would be highly appreciated.


texts:
I have collected a large amount of data about the train network in my country. Now, I am writing some code that calculates the average amount of delay on the entire train network, for each day, in a given period of time. Important to note: every train has a unique train-number. Each train-number only occurs once each day.

The average amount of delay is calculated in two ways:

Worst case: For every train, the maximum amount of delay that train suffers on the given day is used for the computation.
Average case: For every train, the average amount of delay is computed over all the stops of the train and used for the computation.

To further understand my code, I have to explain a portion of my database design. Each train has train_id, origin, destination. Each route has route_id, train_id, date. As mentioned before, each train_id occurs only once each day. So the combination of train_id and date is unique. Each stop has stop_id, arrival_delay, departure_delay, route_id. Each stop is associated with only one route.

start = date(2014, 10, 27)
stop = date(2014, 12, 14)
diff = stop - start
period = pd.date_range(start, stop)
zeros = np.zeros((diff.days+1, 2))

#DataFrame with worst-case and avg delay on entire network, per day
#Delay is computed in a worst-case scenario, i.e. max delay of a train
#and in avg-case scenario, i.e. avg of avg of arrival and avg of departure delay
delays = pd.DataFrame(zeros, index = period, columns = ['Worst case', 'Avg case'])

while(start <= stop):
    t = time(0, 0, 0)
    dt = datetime.combine(start, t)

    #Get all routes for a specified date.
    #Every trainID rides only once each day, so there is no point in asking all the trainIDs first
    routes = #Gets all routes for given date out of database

    worst_train_delays = []
    avg_train_delays = []

    for routeRow in routes:
        routeID = routeRow[0]
        stops = #Gets all stops for given routeID out of database
        max_delay = 0
        arrivals = []
        departures = []

        for stopRow in stops:
            arrival_delay = stopRow[2]
            departure_delay = stopRow[5]
            arrivals.append(arrival_delay)
            departures.append(departure_delay)
            if max(arrival_delay, departure_delay) > max_delay:
                max_delay = max(arrival_delay, departure_delay)

        worst_train_delays.append(max_delay)
        avg_arrival = np.mean(arrivals)
        avg_departure = np.mean(departures)
        avg_train_delays.append(np.mean([avg_arrival, avg_departure]))

    key = start.isoformat()
    delays['Worst case'][key] = np.mean(worst_train_delays)
    delays['Avg case'][key] = np.mean(avg_train_delays)

    delta = timedelta(days=1)
    start = start + delta

The above code computes the average delay, per day, for a period of 49 days. There are about 4000 trains on the network, with each on average 10 stops. These equates to reading approx. 2.000.000 values.

Could I improve this code in terms of speed, performance, memory usage?


texts:
I have code for a function to calculator the addition of two sorted List. Each element of List is tuple type (xi, yi) that represents graph individual (x,y) points at coordinate system.

  two input List is sorted by x value and length of A, B list may be different
  [(Ax0, Ay0),..., (Axi, Ayi), (Axi+1, Ayi+1),, ...(Axn, Ayn)][(Bx0, By0),..., (Bxi, Byi), (Bxi+1, Byi+1),, ...(Bxk, Byk)]

example 1:
A:[(1, 1]]=> one point: 1, at x coordinate, 0 at y coordinate
B:[(0, 0]]=> one point: 0, at x coordinate, 0 at y coordinate
=> graph_addition(A, B) == [(0,0), (1,1)]
a line with two point (0,0) and (1,1)

example 2:
A:[(3, 3), (5,5)]=> one line at (3,3), (5,5)
B:[(4, 4), (5, 5), (10, 8)]=> 2 segment line:
ex: graph_addition(A, B) = [(3, 3), (4, 8.0), (5, 10)]
3 segment line with 3 point [(3, 3), (4, 8.0), (5, 10), (10, 8)]
For A when x at 4, y should be 4 based on slope calculation

example 3:
A:[(3,3), (5,5), (6,3), (7,5)]
B:[(0,0), (2,2), (4,3), (5,3), (10,2)]
explanation
when x = 0 at B line, y=0, at A line y = 0 => (0, 0)
when x = 2 at B line, y=2, at A line y = 0 => (0, 0)
when x = 4 at B line, y=3, at A line y = (5-3 / 5-3 * 4) => (4, 7)
when x = 5 at B line, y=3, at A line y = 5 => (5, 8)
when x = 6 at B line, y= (2 - 3)/(10-5) * 6, at A line y = 3 => (6, 0)
when x = 7 at B line, y= (2 - 3)/(10-5) * 7, at A line y = 5 => (7, 1.5)
when x = 10 at B line, y=3, at A line y = (5-3 / 5-3 * 4) => (4, 7)
=> [(0, 0), (2, 2), (3, 5.5), (4, 7.0), (5, 8), (6, 5.8), (7, 7.6), (10, 2)]

Is there a better way for me to not using bruteforce way to calculate x, y values?

def graph_addition(A, B):
     if not A or not B: return A or B
     res = []
     i = j = 0
     while i < len(A) and j < len(B):
         if A[i][0] < B[0][0]:
             x, y = A[i]
             i += 1
         elif B[j][0] < A[0][0]:
             x, y = B[j]
             j += 1
         elif A[i][0] < B[j][0]:
             x = A[i][0]
             y = (B[j][1] - B[j - 1][1]) / (B[j][0] - B[j - 1][0]) * (x - B[j - 1][0]) + B[j - 1][1] + A[i][1]
             i += 1
         elif A[i][0] > B[j][0]:
             x = B[j][0]
             y = (A[i][1] - A[i - 1][1]) / (A[i][0] - A[i - 1][0]) * (x - A[i - 1][0]) + A[i - 1][1] + B[j][1]
             j += 1
         else:
             x = A[i][0]
             y = A[i][1] + B[j][1]
             i += 1
             j += 1
         res.append((x, y))
     if A[i:]: res += A[i:]
     if B[j:]: res += B[j:]
     return res


texts:
I have two functions to split string to array of strings.
Input string is: (1Letter E|V|R) + 8 number, last component of string (1Letter + V) + 8 or less numbers.

I'v got two functions advised to use, both of them are working properly. But I can't decide which one is better to use.

1st:

- (NSArray *) componentSaparetedByLength:(NSUInteger) length{
        NSMutableArray *array = [NSMutableArray new];
        NSRange range = NSMakeRange(0, length);
        NSString *subString = nil;
        while (range.location + range.length <= self.length) {
            subString = [self substringWithRange:range];
            [array addObject:subString];
            //Edit
            range.location = range.length + range.location;
            //Edit
            range.length = length;
        }

        if(range.location<self.length){
            subString = [self substringFromIndex:range.location];
            [array addObject:subString];
        }
        return array;
}

2nd:

NSMutableArray *brokenString=[NSMutableArray new];

int start=0;
for (; start<mainString.length-9; start+=9) {
     [brokenString addObject:[mainString substringWithRange:NSMakeRange(start, 9)]];
}
[brokenString addObject:[mainString substringFromIndex:start]];
NSLog(@"->%@",brokenString);


texts:
I'm making a comparing section, which I've just started typing, trying to get something working. It's working now, but as you can see its pretty messy.  I feel this could be done in one or two less queries, or I should break it apart into smaller methods.

foreach (XMLObject source in Sources)
{
    var matchedElement =
        destList.FirstOrDefault(s.ElementName == source.ElementName);
        // checks to see if it exists in one list but not the other

    if (matchedElement == null) // element is in one list and not the other
    {
        var alter =
            lstAlteration.FirstOrDefault(
                a => a.ElementName == source.ElementName && a.ChangeInfo.ChangeFrom == source.ElementName);
            // check to see if the the element is a Removal (Changed From would not be blank)

        if (alter == null) // Removal has not been triggered
        {
            alter = new Alteration
                        {
                            ElementName = source.ElementName,
                            ChangeInfo = new ChangeDetail( {ChangeTo = source.ElementName}
                        };
        }
        else
        {
            alter.ChangeInfo.ChangeTo = source.ElementName;
        }

        lstAlteration.Add(alter);
    }
}


texts: How do I refine my code in Sikuli? Seems very long and redundant

texts:
I'm only just beginning in programming.

The goal of the program is to check to make sure images are properly rendered within a program(within a VM)

. Below is the code, and I am asking what I can do to clean it up.

I don't think you can tell much without the .png's, but I would appreciate it if anyone knows where/how I can optimize my code.

Thank you very much for any help,

var=(0) #Empty Variable
jpgl=0 #NUMBER PASSES
vm = App("C:\Program Files (x86)\VMware\VMware Workstation\\vmware.exe")
switchApp("vm")
reg=( )
reg.find( )
#------------------------------------
#BEGINNING SPECIAL CASES/NAVIGATION
if not exists( ):
    switchApp("vm")
    type(Key.BACKSPACE)
    onAppear( ,type(Key.BACKSPACE))
if exists( ):
    click( )
#if exists( ):#attempt to get rid of.
#   click( )
else:
    exists( )
    click( )
    exists( )
    click( )
    wait(1)
    if not exists ( ):#if the image hasn't already loaded, wait the maximum 5 seconds
        wait(5)
#END FOLDER NAVIGATION
#----------------------------------
#BEGIN IMAGE CHECK 1
    if not exists ( ):
        print("B-JPEG_L-20.jpg not displayed correctly")
    if exists( ):
        print("B-JPEG_L-20.jpg Unable to play")
        click( )
    else:
        jpgl=jpgl+1#if the image exists, it moves on by clicking "next"
        click( )
        wait(1)
        if not exists ( ):
            wait(5)
#DONE IMAGE CHECK 1
#----------------------------------
#BEGIN IMAGE CHECK 2
.....

#end code


texts:
I have UserGroups for Users to be assigned to in a ListBox in HTML form. Items from listbox can be multi-selected or completely unselected.

In summary currently, I am getting a int[] of GroupId from client into my action and I am pulling existing assigned usergroups for the user into the action as well. Then I am comparing the Length of both int[] to determine whether UserGroups for the User was added or removed which is depicted in the following flow chart:

Actual code:

var existUserGroups = db.Users.Where(u => u.ID == user.ID).Single().UserGroups;
var existUserGroupsIds = db.Users.Where(u => u.ID == user.ID).Single().UserGroups.Select(ug => ug.ID).ToArray<int>();
var newUserGroupsIds = user.GroupId ?? new int[0];

//No change made
if (!existUserGroupsIds.SequenceEqual(newUserGroupsIds))
{
    //Add
    if (newUserGroupsIds.Length > existUserGroupsIds.Length)
    {
        for (int i = 0; i < newUserGroupsIds.Length; i++)
        {
            if (!existUserGroupsIds.Any(id => id == newUserGroupsIds[i]))
            {
                int id = newUserGroupsIds[i];
                existUserGroups.Add(db.UserGroups.Where(ug => ug.ID == id).Single());
            }
        }
    }
    //Remove
    else if (newUserGroupsIds.Length < existUserGroupsIds.Length)
    {
        var diff = existUserGroupsIds.Except(newUserGroupsIds);
        if (diff != null && diff.Count() > 0)
        {
            for (int i = 0; i < diff.Count(); i++)
            {
                int id = diff.ElementAt(i);
                existUserGroups.Remove(db.UserGroups.Where(ug => ug.ID == id).Single());
            }
        }
    }
    //Update
    else
    {
        existUserGroups.Remove(existUserGroups.ElementAt(0));
        int id = newUserGroupsIds[0];
        existUserGroups.Add(db.UserGroups.Where(ug => ug.ID == id).Single());
    }

    db.SaveChanges();
}

This is working but the code seems to be very tangled. So, please suggest how I can improve this code or how devs usually handle such situations.


texts: Join strings from a List while also formating them

texts:
The code I have wrote works fine, this inquiry being purely for educational purposes. I want to know how others would do this better and cleaner. I especially hate the way I add the list items to another list before they are joined. There has to be a more efficient way.

I realize an easy way to make this simple would be to store "OU=" and "DC=" in the database with their associated text, but that just feels unseemly to me.

I am building a string for the container argument of the PrincipalContext class for an LDAP call.

The "lst" List<string> contains DataRows of LDAP Organization Units like "Accounts", "Users", etc.

// Get ou list
List<string> lst = db.sda(sql).Rows.OfType<DataRow>().Select(dr => dr.Field<string>("txt")).ToList();

string OU = string.Empty;
List<string> lst = new List<string>();

foreach (string ou in Web.Info.Ldap.ouList)
{
    lst.Add(string.Format("OU={0}", ou));
}
OU = string.Join(",", lst);

Result:

  OU=Users,OU=Accounts,OU=Employees

I do the same thing to a list called dcList that produces the same kind of string:

DC = string.Join(",", lst);

Result:

  DC=severname,DC=another_value,DC=com

to which I join together with OU to get the complete string, like so:

string container = string.Join(",", OU, DC);

End result:

  OU=Users,OU=Accounts,OU=Employees,DC=sever,DC=othervalue,DC=com


texts: Square root approximations, implemented two ways

texts:
Which version is more efficient in calculating the square root ?

There are 2 versions I have written to calculate square root programatically. Note reqs strictly state not using library functions ?

This is puzzling, the first method takes one extra iteration over the 2nd one but returns the more accurate answer of 3.00.

Why does it take an extra iteration ?

So, which one is more efficient ?
Do you find any bugs in this code ?
When will it overflow ?
Do both approaches seem logical, one is trying to calculate the difference between square of approximation and actual number, whereas other trying to bisect the interval. Would you pick one over the other ?

public void squareRoot()
{
    double n = 9;
    double epsilon = 0.001;
    double guess = n*n;
    double low = 0;
    double high = n;
    int cnt=0;
    while(Math.abs(guess*guess-n)>epsilon)
    {
         guess = (low + high)/2;
        if(guess*guess>n)
            high = guess;
        else
            low = guess;
        cnt+=1;
        System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
    }

    if(guess*guess-n<epsilon)
    {
        System.out.println("The square root is:"+guess);
    }
}

public void anotherSquareRoot()
{
    double n = 9;
    double epsilon = 0.001;
    double guess = n*n;
    double low = 0;
    double high = n;
    int cnt=0;
    while(high-low>epsilon)
    {
         guess = (low + high)/2;
        if(guess*guess>n)
            high = guess;
        else
            low = guess;
        cnt+=1;
        System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
    }

    if(guess*guess-n<epsilon)
    {
        System.out.println("The square root is:"+guess);
    }
}


texts:
I'm currently writing unit tests in Selenium (C#). I need to do two things in this particular test:

  Check if 2 errors (with html container) are displayed and check if another (given) error is not displayed.

The test looks like this:

bool errorWindowVisible = tmethods.IsElementVisible(driver, By.XPath("//div[@class='message error']"));
if (errorWindowVisible == false)
{
  Assert.Fail("No error notification displayed.");
}

string errorTextTemp = "Error 1 text";
bool productIssue = tmethods.IsElementVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]"));
errorTextTemp = "Error 2 text";
bool productIssueB = tmethods.IsElementVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]"));
if (productIssue == false || productIssueB == false)
{
  Assert.Fail("No information about error cause.");
}

// Checking if another one is not visible
errorTextTemp = "Extra error";
bool uploadedFileIssue = tmethods.IsElementNotVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]"));
if (uploadedFileIssue == false) // Should be set to true
{
  Assert.Fail("Extra error shown.");
}

I use two methods here:

public bool IsElementVisible(IWebDriver driver, By element)
{
    if (driver.FindElements(element).Count > 0)
    {
    if (driver.FindElement(element).Displayed)
        return true;
    else
        return false;
    }
    else
    {
    return false;
    }
}

public bool IsElementNotVisible(IWebDriver driver, By element)
{
    if (driver.FindElements(element).Count > 0)
    {
    if (driver.FindElement(element).Displayed)
        return false;
    else
        return false;
    }
    else
    {
    return true;
    }
}

So, all of that is working, but I am not sure about quality of that code.
On the other hand, I don't need anything over-fancy. It just should be good, clean and understandable.

Should I keep it intact or update some parts?


texts: Generic DialogueBox class with different parameters

texts:
I have implemented a DialogueBox class which can be static, singleton, service locator, etc.
I have written it as a singleton pattern and implemented it in Unity3d engine. It is a part of a game.
I have ShowDialogueBox method with many parameters. How can I handle it?
The parameters are message, ok button label, cancel button label, has the cancel button or not, actions to be invoked when users click on ok or cancel button.

Is it more suitable to apply Builder pattern for it?

Because the method is not sometimes flexible and I have to provide all parameters.

In addition, my messages are not static and sometimes I need to display a message with parameters like cost value, etc. Therefore, I should add another parameter like params to the method or create the message with params before calling the method?
Also, It is appropriate to pull out Localizer from DialogueBox class?

//DialogueBox.GetInstance().ShowDialogueBox("BuyMessage",()=>{},
 //       ()=>{}, "Buy", "Cancel",true)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogueBox : MonoBehaviour
{
    [SerializeField] private Text _cancelButtonText;
    [SerializeField] private Text _okButtonText;
    [SerializeField] private GameObject _cancelButtonObj;
    [SerializeField] private GameObject _okButtonObj;
    [SerializeField] private Text _messageText;
    [SerializeField] private GameObject _dialogueBoxObj; //DialogueBox GameObject(Panel)
    private static DialogueBox _instance;

    private Action OKButtonPressedAction = delegate { };
    private Action CancelButtonPressedAction = delegate { };

    public static DialogueBox GetInstance()
    {
        return _instance;
    }

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void ShowDialogueBox(string messageKey, Action okButtonPressed,
        Action cancelButtonPressed = null, string okKey = "OK", string cancelKey = "Cancel",
        bool hasCancelButton = true)
    {
        //Localizer manages languages with key/message pair for example:
        //Localizer.GetInstance().Dictionary[key]---> returns message for the current language

        _messageText.text = Localizer.GetInstance().Dictionary[messageKey];
        _okButtonText.text = Localizer.GetInstance().Dictionary[okKey];
        if (hasCancelButton)
        {
            _cancelButtonObj.SetActive(true); //Show the cancel button
            _cancelButtonText.text = Localizer.GetInstance().Dictionary[cancelKey];
        }
        else
            _cancelButtonObj.SetActive(false);

        OKButtonPressedAction = okButtonPressed;

        CancelButtonPressedAction = cancelButtonPressed;
    }

    public void OnOKButtonPressed() //It is called when a user clicks on OK button
    {
        _dialogueBoxObj.SetActive(false);
         if( OKButtonPressedAction!=null)
            OKButtonPressedAction();
    }
    public void OnCancelButtonPressed() //It is called when a user clicks on OK button
    {
        _dialogueBoxObj.SetActive(false);
        if(CancelButtonPressedAction!=null)
            CancelButtonPressedAction();
    }
}


texts: Android Gradle script in multi-module project

texts:
I have a multi-module Android project built by Gradle with the new Android-plugin 0.10+.

All modules are mainly configured from the root project.

I've enable the new code coverage feature. The major problem is that only some modules contain test code and when I enable code coverage on modules that don't contain test code, it fails.

I would like to avoid enabling code-coverage in each module build.gradle file so that when someone add test code in a module that wasn't tested, there is no need to modify the build.gradle.

I ended up with the following code where code coverage is enabled only when the androidTest sourceSet contains at least one .java source file. It works as expected, but I'm wondering if there is a nicer way of doing this.

Here is the relevant portion of the root project build.gradle script:

configure(subprojects.findAll()) {
    if(it.name.equals('MyApp')){
        apply plugin: 'android'
    }else{
        apply plugin: 'android-library'
    }

    android {
        ...
        //my question is really about the follong 4 lines :
        //is there a simpler way to get java source file count in the androidTest sourceSet ?
        def androidTestJavaSourceFileCount = 0
        sourceSets.androidTest.allJava.each {
            androidTestJavaSourceFileCount ++
        }
        println("androidTestJavaSourceFileCount in androidTest for module $project.name : $androidTestJavaSourceFileCount")
        buildTypes {
            debug {
                testCoverageEnabled = androidTestJavaSourceFileCount > 0
            }
        }

        jacoco {
            version = '0.6.2.201302030002'
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                res.srcDirs = ['res']
                assets.srcDirs = ['assets']
           }
       }
 }


texts:
I wrote a little script that asks the user to choose a number between the 0 and 9. Wile he/she is entering a choice, the program tells him/her if the number is too high and too low.

Nothing fancy, just a couple of while and ifs. It's very ugly and has imperative code with mixed responsibilities. I was wondering if there are some Ruby idioms that would make this code more readable and compact. I'm looking for some functions like in functional languages, or maybe there are special Ruby functions I'm not aware off. I don't want to define functions and classes for this simple program.

keepGoing = true
numberToGuess = rand(10)
firstRun = true
response = ''
while keepGoing
    if firstRun
        puts 'Find the magic number between O and 9'
        firstRun = false
    end
    proposedN = gets.chomp.to_i
    if proposedN == numberToGuess
        firstRun = true
        puts "You found the correct number : #{numberToGuess}"
        puts 'Another try ? (Y/N)'
        numberToGuess = rand(10)
        response = gets.chomp
        while response != 'N' and response != 'Y'
            puts 'Please fill in either Y or N'
            response = gets.chomp
        end
        response == 'N' ? keepGoing = false : keepGoing = true
        response = ''
    else
        if proposedN > numberToGuess
            puts 'Too high'
        else
            puts 'Too low'
        end
    end
end