texts: Print strings in order with dynamic arrays

texts:
I accomplished the following task to practice allocating on the heap.

reading words from stdin
sorting them in lexicographical order
printing the sorted words to stdout

To accomplish this is allocate the size of each word and the count of words.

I would like to hear any suggestions for improvements. Is there maybe an easier way to sort the words?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

struct Word {
    char* signs;    // pointer to a word
    int sz;
    int capacity;
};

// allocates factor 2 of the current capacity
void reserve_space_for_letter(char **c, int *capacity)
{
    if (*capacity == 0) {   // allocate the first time
        *capacity = 1;
        *c = malloc(sizeof(char) * ((*capacity)));
    }
    else {
        *capacity *= 2;     // double the new capacity
        *c = realloc(*c, sizeof(char) * (*capacity));
    }
}

void reserve_space_for_words(struct Word** w, int *capacity)
{
    if (*capacity == 0) {   // allocate the first time
        *capacity = 1;
        *w = malloc(sizeof(struct Word) * ((*capacity)));
    }
    else {
        *capacity *= 2;     // double the new capacity
        *w = realloc(*w, sizeof(struct Word) * (*capacity));
    }
}

void print_words(struct Word* words,int sz)
{
    int i = 0;
    for (i = 0; i < sz; ++i) {
        printf("%s ", words[i].signs);
    }
}

int cmp(void const *lhs, void const *rhs) {
    struct Word left = *(const struct Word *)lhs;
    struct Word right = *(const struct Word *)rhs;

    return strcmp(left.signs, right.signs);
}

void deallocate_words(struct Word* words, int sz)
{
    int i = 0;
    for (i = 0; i < sz; ++i) {
        free(words[i].signs);
    }
    free(words);
}

int main()
{
    struct Word* words;     // Pointer to several words
    int sz = 0;
    int capacity = 0;

    int ch=0;
    bool in_word = true;

    reserve_space_for_words(&words, &capacity); // reserve space for first word
    ++sz;
    words[sz - 1].capacity = 0;
    words[sz - 1].sz = 0;

    while ((ch = getc(stdin)) != EOF) {

        if (words[sz - 1].sz == words[sz - 1].capacity) {       // if current letter sz = capacity
            reserve_space_for_letter(&words[sz - 1].signs, &words[sz - 1].capacity);
        }

        if (!isalnum(ch) && in_word) {      // end of current word;
            words[sz - 1].signs[words[sz - 1].sz] = '\0';
            in_word = false;
            continue;
        }
        else if (!isalnum(ch) && !in_word) {        // not in a word so dont bother doing sth
            continue;
        }
        else if (isalnum(ch) && !in_word) {     // the next word is reached
            in_word = true;

            if (sz == capacity) {       // maximum size of words reached
                reserve_space_for_words(&words, &capacity); // reserve space for first word
            }
            ++sz;       // iterate to the new word
            words[sz - 1].capacity = 0;
            words[sz - 1].sz = 0;

            reserve_space_for_letter(&words[sz - 1].signs, &words[sz - 1].capacity);
        }

        words[sz - 1].signs[words[sz - 1].sz] = ch;    // append the sign in the array
        ++words[sz - 1].sz;
    }
    qsort(words, sz, sizeof(struct Word), cmp);
    print_words(words, sz);
    deallocate_words(words, sz);

    getchar();
    return 0;
}


texts:
Can the following code be simplified? I think that the program that I have created is very excessive and quite slow. The program runs fine, but I would like to understand if this could actually be programmed better.

I have commented on every line of the code. Any kind of feedback on the program will be great, as I have only been programming for a couple of weeks now.

# Python 3.4.3. Using MacOS (Version 10.12.5)
# Username and Password...
# The programs purpose: A user must enter the correct username and password for a site called FaceSnap...
# The correct username is elmo and the correct password is blue.

userName = input("Hello! Welcome to FaceSnap! \n\nUsername: ") #Ask's the User for Username input
password = input("Password: ") # Ask's the user for their password

count = 0 # Create a variable, to ensure the user has limited attempts at entering their correct username and password
count += 1 # The user has already had one attempt above, therefore count has been incremented by 1 already.

while userName == userName and password == password: # The Input will always lead to this while loop, so we can see if their username and password is wrong or correct.

    if count == 3: # Counter, to make sure the user only gets a limited number (3)of attempts
        print("\nThree Username and Password Attempts used. Goodbye") # Lets the user know they have reached their limit
        break # Leave the Loop and the whole program

    elif userName == 'elmo' and password == 'blue': # The userName and password is equal to 'elmo' and 'blue', which is correct, they can enter FaceSnap!
        print("Welcome! ") # Welcomes the User, the username and password is correct
        break # Leave the loop and the whole program as the username and passowrd is correct

    elif userName != 'elmo' and password != 'blue': # The userName and password is NOT equal to 'elmo' and 'blue', the user cannot enter FaceSnap
        print("Your Username and Password is wrong!") # Lets the user know that the Username and password entered is wrong.
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # Increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet

    elif userName == 'elmo' and password != 'blue': # The userName is equal to 'elmo', but password is NOT equal to 'blue', the user cannot enter FaceSnap
        print("Your Password is wrong!") # Lets the user know that their password is wrong
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet

    elif userName != 'elmo' and password == 'blue': # The userName is NOT equal to 'elmo', however password is equal to 'blue', the user cannot enter FaceSnap
        print("Your Username is wrong!") # Lets the user know that their username is wrong
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # Increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet


texts: JavaScript Armstrong Number Validator (ES6)

texts:
I have the following function which takes in an input and validates if that input is an Armstrong number or not:

  An Armstrong Number is a number such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3 ** 3 + 7 ** 3 + 1 ** 3 = 371.

Here's a link to the program on codepen.

const isArmstrong = input => {
  const expandedInputExpression = `
    ${input[0]} ** 3 + ${input[1]} ** 3 +
    ${input[2]} ** 3`;

  const expandedInputValue = Array.from(input)
    .map(digit => digit)
    .reduce((total, currentDigit) => total + currentDigit ** 3, 0);

  if (expandedInputValue === parseInt(input)) {
    console.log(`${input} is an Armstrong number since ${expandedInputExpression} = ${input}`);
    return true;
  } else {
    console.log(`
    ${input} is not an Armstrong number because ${expandedInputExpression}( ${expandedInputValue}) is not equal to ${input}`);
    return false;
  }
};

Is there any way to refactor and simplify the function?


texts: node.js library for extracting words from a text

texts:
I'm looking for feedback on my library for extracting words from a text: https://npmjs.org/package/uwords

The extracted word is defined as sequence of Unicode characters from Lu, Ll, Lt, Lm, Lo groups. So the code of the main part is (https://github.com/AlexAtNet/uwords/blob/master/index.js#L9):

module.exports = function (text) {
    var words, word, index, limit, code;

    words = [ ];
    word = null;

    for (index = 0, limit = text.length; index < limit; index += 1) {
        code = text.charCodeAt(index);
        if (-1 === _.indexOf(letters, code, true)) {
            if (null !== word) {
                words.push(word.join(''));
                word = null;
            }
        } else {
            if (null === word) {
                word = [ ];
            }
            word.push(String.fromCharCode(code));
        }
    }

    if (null !== word) {
        words.push(word.join(''));
    }

    return words;
};

and the array letters was created as follows (https://github.com/AlexAtNet/uwords/blob/master/gruntfile.js#L59):

    grunt.registerTask('create-letters-json', 'letters.json', function () {
        var letters, compacted;

        letters = [
            require('unicode/category/Lu'),
            require('unicode/category/Ll'),
            require('unicode/category/Lt'),
            require('unicode/category/Lm'),
            require('unicode/category/Lo')
        ].reduce(function (list, item) {
            list.push.apply(list, Object.keys(item).map(function (value) {
                return parseInt(value, 10);
            }));
            return list;
        }, [ ]).sort(function (a, b) { return a - b; });

        compacted = (function (list) {
            var result, item, idx, value;

            result = [ ];

            item = { begin : list[0], end : list[0] };
            result.push(item);

            for (idx = 1; idx < list.length; idx += 1) {
                value = list[idx];
                if (item.end + 1 === value) {
                    item.end = value;
                } else {
                    item = { begin : list[idx], end : list[idx] };
                    result.push(item);
                }
            }

            for (idx = 0; idx < result.length; idx += 1) {
                item = result[idx];
                if (item.begin === item.end) {
                    result[idx] = item.begin;
                } else {
                    result[idx] = [ item.begin, item.end ];
                }
            }

            return result;
        }(letters));

        require('fs').writeFileSync(__dirname + '/letters.json',
            JSON.stringify(compacted, null, 2));
    });

It is quite naive approach but I think that it will work in most of the cases. What do you think?


texts: Program to generate numbers, finding average and largest values and rounding the largest to 100

texts:
As this code is not in English, I will explain it first:

Creates ten numbers in an array between 0 and 100 as student grades.
Calculates the largest number and average value of these ten numbers in the array.
100, the largest grade, is subtracted from the largest number in the array. (e.g 100-96=4)
New value (which is 4 in this case, explained in example above) is added to all numbers in the array. It's also printed just below average value and largest value.
New values in the array that are unable to surpass the average value are printed down below, which prints a sentence in Turkish that roughly translates to:

"%dth student with %d grade has failed the lesson by staying under the average value."

#include<time.h>
#include<stdio.h>
#include<stdlib.h>

int main() {

int sum=0,fark,avg,imax;
int puan[10];
srand(time(NULL));
for(int i=0; i<10; i++)
{
    puan[i]=rand()%101;
    printf("%d. ogrencinin notu = %d ",i+1,puan[i]);
    printf("\n");
    if(i==0)
    {
        imax=puan[i];
    }
    else if(puan[i]>imax)
        {
            imax=puan[i];
        }
    sum += puan[i];
}
avg=sum/10;
fark= 100 - imax;
printf("\nEn yuksek not = %d ve not ortalamasi %d.\n",imax,avg);
printf("Her ogrencinin notuna %d puan eklendi.\n",fark);
printf("\n");
for(int i=0;i<10;i++)
{
    puan[i] += fark;
}
for(int i=0;i<10;i++)
{
    if(puan[i]<avg)
    {
        printf("%d. ogrenci aldigi %d notuyla ortalamanin altinda kalarak dersten basarisiz olmustur.\n",i+1,puan[i]);
    }
}
return 0;
}

Can I shorten this code? Is there a shorter way to make it work in the same way? This was the best my friend and I could come up with.


texts: Calculating sum of primes using the CPU and GPU

texts:
This is a little baffling to me as to why the CUDA code runs about twice as slow as the CPU version. I am just counting all the primes from 0 to (512 * 512 * 512). The CPU version executed in about 97 seconds whereas the GPU version took 182 seconds.

CPU: Intel Core i7 @ 4 GHz
GPU: NVIDIA GTX 960

Any ideas why?

#include <cuda.h>
#include <iostream>
#include <cstdint>
#include <stdio.h>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <climits>

using namespace std;

__host__ __device__  bool is_prime(uint32_t n)
{
    if(n == 2)
        return true;
    if(n % 2 == 0)
        return false;
    uint32_t sr = sqrtf(n);

    for(uint32_t i = 3; i <= sr; i += 2)
        if(n % i == 0)
            return false;
    return true;
}

__global__ void prime_sum(unsigned int* count)
{
    uint32_t n = (blockIdx.y * gridDim.y + blockIdx.x) * blockDim.x + threadIdx.x;
    if(is_prime(n))
        atomicAdd(count, 1);
}

CPU version

int main()
{
    time_t start = time(0);
    int pcount = 0;
    for(uint32_t i = 0; i < (512 * 512 * 512); i++)
    {
        if(is_prime(i)) pcount++;
    }
    start = time(0) - start;
    std::cout << pcount << "\t" << start << std::endl;

    return 0;
}

CUDA version

int main()
{
    time_t start = time(0);
    unsigned int* sum_d;
    cudaMalloc(&sum_d, sizeof(unsigned int));
    cudaMemset(sum_d, 0, sizeof(unsigned int));

    prime_sum<<< dim3(512, 512), 512 >>>(sum_d);

    unsigned int sum = 0;
    cudaMemcpy(&sum, sum_d, sizeof(unsigned int), cudaMemcpyDeviceToHost);
    start = time(0) - start;
    std::cout << sum << "\t" << start << std::endl;
    cudaFree(sum_d);

    return 0;
}


texts:
For asynchronous requests, I use Alamofire.
I have created one method for requesting async data.

func requestData(method: Method, urlString: String, onSuccess: (AnyObject) -> Void , onFailure: (NSError) -> Void,  sender: UIViewController, postParams:AnyObject? = nil) {

    let AFmanager = Manager(configuration: seesionConfiguration)

    let URL = NSURL(string: urlString)!
    let urlRequest = NSMutableURLRequest(URL: URL)
    urlRequest.HTTPMethod = method.rawValue

    if let param: AnyObject = postParams {
        urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(param, options: nil, error: nil)
    }
    if method == .POST {
        urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    }
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

    AFmanager.request(urlRequest)
        .responseJSON { (request, response, JSONResult, error) in
            if (error == nil) {
                onSuccess(JSONResult!)
            } else {
                onFailure(error!)
            }
    }
}

Here, I have made postParams of type AnyObject as parameter can be of any dictionary type. Is there another way of defining the method so that postParams can be checked to be of type dictionary?

Any other improvement/suggestion?


texts:
Looking for constructive criticism on my code below for detecting a memory leak in a data structure.

    MemoryLeak = {

  uniq_id: (new Date()).getTime(),
  checked: 1,
  is_seen: [],

  checkLeaks: function(obj) {
    var self = MemoryLeak

    if(!obj || (typeof obj == 'function') || self.checked > 20000)
      return;

    if ((self._isArray(obj) || self._isObject(obj))) {
      if (self._isArray(obj)) {
        self._logTooBig(obj, obj.length)
        for (var i = 0; i < obj.length; i++) {
          self._checkIfNeeded(obj[i])
        }
      }
      else if (self._isObject(obj)) {
        self._logTooBig(obj, self._keys(obj).length)

        for (var key in obj) {
          self._checkIfNeeded(obj[key])
        }
      }
    }
  };

  _checkIfNeeded: function(obj) {
    if (!obj)
      return;

    var self = MemoryLeak;
    self.checked++

    if ((self._isArray(obj) || self._isObject(obj))) {
      if(obj.__leaks_checked == self.uniq_id)
        return;
      obj.__leaks_checked = self.uniq_id

      setTimeout(self._partial(self.checkLeaks, obj), 5);
    }
  };

  _logTooBig: function(obj, limit) {
    if (limit > 200) {
      console.log('Object too big, memory leak? [size: ' + limit + ']')
      console.log(obj)
      console.log('-------')
    }
  };

  _keys: function(obj) {
    var rval = [], prop
    for (prop in obj)
      rval.push(prop)
    return rval;
  };

  _isArray: function(obj) {
    try {
      return obj instanceof Array
    }
    catch(e) {
      return false;
    }
  };

  _isObject: function(obj) {
    return (typeof obj == 'object')
  };

  _partial: function(fn) {
    var args = Array.prototype.slice.call(arguments)
    args.shift()
    return function() {
      var new_args = Array.prototype.slice.call(arguments)
      args = args.concat(new_args)
      return fn.apply(window, args)
    }
  }
}


texts: Building a 64 × 64 particle accelerator frame in Minecraft with a computercraft turtle

texts:
I dont think this will work anywhere besides in minecraft with computercraft but it's all correct syntax. I just feel like it has some lines of code I could eliminated somehow and made it a cleaner script. I appreciate any constructive criticism to help me further understand what I'm misunderstanding.

function placef()
  turtle.select(1)
  x = 1
  if turtle.getItemCount(x) == 0 then
  repeat turtle.select(x+1)
  x = x + 1
  if x == 17 then
  x = 1
  y = 2
  end
  if y == 2 then
  os.reboot()
  end
  until turtle.getItemCount(x) > 0
 end
 turtle.place()
end

function placeup()
  turtle.select(9)
  x = 9
  if turtle.getItemCount(x) == 0 then
  repeat turtle.select(x+1)
  x = x + 1
  if x == 17 then
  x = 9
  y = 2
  end
  if y == 2 then
  os.reboot()
  end
  until turtle.getItemCount(x) > 0
  end
  turtle.placeUp()
end

function place()
  turtle.select(9)

x = 9
  if turtle.getItemCount(x) == 0 then
  repeat turtle.select(x+1)
  x = x + 1
  if x == 17 then
  x = 9
  y = 2
  end
  if y == 16 then
  os.reboot()
  end
  until turtle.getItemCount(x) > 0
  end
  turtle.placeDown()
end

function repairOT()
  turtle.select(1)
  x = 1
  if turtle.getItemCount(x) == 0 then
  repeat turtle.select(x+1)
  x = x + 1

  if x == 17 then
  x = 1
  y = 2
  end
  if y == 2 then
  os.reboot()
  end
  until turtle.getItemCount(x) > 0
  end
  if turtle.compareDown() == false then
  place()
  turtle.turnRight()
  else
  turtle.turnRight()
  end
  if turtle.compare() == false then
  placef()
  turtle.turnLeft()
  else
  turtle.turnLeft()
  end

turtle.forward()
end

function repairBI()
  turtle.select(1)
  x = 1
  if turtle.getItemCount(x) == 0 then
  repeat turtle.select(x+1)
  x = x + 1
  if x == 17 then
  x = 1
  y = 2
  end
  if y == 16 then
  os.reboot()
  end
  until turtle.getItemCount(x) > 0
  end
  if turtle.compareUp() == false then
  placeup()
  turtle.turnLeft()
  else
  turtle.turnLeft()
  end
  if turtle.compare() == false then
  placef()
  turtle.turnRight()
  else
  turtle.turnRight()
  end
 turtle.forward()
end

These functions are where I think I could do away with alot of lines of code but I'm not sure how. Maybe an anonymous function and a class. Don't really quite understand using those very well yet.

https://pastebin.com/JDZSibmn There is the full script just in case anyone wants to see it. The rest is just loops.


texts: Print a character frequencies as a vertical graph

texts:
I've been solving K&R 1-14.

Exercise 1-14. Write a program to print a histogram of the frequencies of different characters in its input.

After several edits, it looks good to me now. But it's my first time to write a long code(it's long to me). I wonder if there is more simple and shorter code with the same logic or I wrote a bad style code or not. I also wonder whether my vertical graph looks good and well written.  Any suggestion will be so appreciated!
#include <stdio.h>

/*  print a graph of the frequencies of different characters */

#define GRAPH_HEIGHT 20

main()
{
    int af[26] = {0};
    int max = 1;
    int c;
    int i, j;

    /* get characters */
    while ((c = getchar()) != EOF) {
        if (c >= 'a' && c <= 'z')
            if (++af[c - 'a'] > max) {
                ++max;
                continue;
            }
        if (c >= 'A' && c <= 'Z')
            if (++af[c - 'A'] > max)
                ++max;
    }

    /* calculate a relative frequencies */
    for (i = 0; i < 26; ++i) {
        af[i] = GRAPH_HEIGHT * af[i] / max;
    }

    /* print characters on a graph */
    for (i = GRAPH_HEIGHT; i > 0; --i) {
        printf("%2d |", i);
        for (j = 'a'; j <= 'z'; ++j) {
            if (af[j - 'a'] == i) {
                printf(" | ");
                --af[j - 'a'];
            }
            else
                printf("   ");
        }
        printf("\n");
    }

    printf("   " "*" "---------------" "---------------" "---------------" "---------------" "---------------" "---"  "\n");
    printf("   ");
    for (i = 'a'; i <= 'z'; ++i) {
        printf("%3c", i);
    }

    printf("\n");
}


texts: Query for finding possible "Not An Answer" posts

texts:
I have this query in SEDE to try to find possible not an answers to flag. (I already went through a lot of them, for Stack Overflow, so I don't really recommend anyone else using this one since isn't that helpful anymore.)

As you can see, it looks to be a lot longer and redundant than it probably needs to be. Is there any way to shorten this?

SELECT
    p.Id as [Post Link],
    len(p.Body),
    p.CreationDate as Date
FROM
    Posts as p
JOIN
    Users as u
ON
    p.OwnerUserId = u.Id
JOIN
    Posts as q
ON
    p.ParentId = q.Id
WHERE
    u.Reputation < 126
  and
    len(p.Body) < 300
  and
    p.Body LIKE '%a href=%'
  and
    p.Score < 3
  and
    p.PostTypeId = 2
  and
    p.CommentCount < 3
  and
    q.ClosedDate IS NULL
  and
    q.FavoriteCount < 3
  and
    q.CommunityOwnedDate IS NULL
  and
    q.Body NOT LIKE '%plugin%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%plugin%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%plug-in%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%plug-in%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%tool%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%tool%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%framework%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%framework%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%API%'
  and
    q.Body NOT LIKE '%API%'
  and
    q.Title NOT LIKE '%IDE%'
  and
    q.Body NOT LIKE '%IDE%'
  and
    q.Title NOT LIKE '%library%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%library%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%cms%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%cms%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%open source%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%open source%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%application%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%application%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%software%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%software%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%tutorial%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%tutorial%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%book%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%book%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%module%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%module%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%resource%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%resource%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%engine%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%engine%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%lightweight%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%lightweight%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%opensource%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%opensource%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%technologies%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%technologies%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%simulator%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%simulator%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%compiler%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%compiler%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Body NOT LIKE '%editor%' COLLATE SQL_Latin1_General_CP1_CI_AS
  and
    q.Title NOT LIKE '%editor%' COLLATE SQL_Latin1_General_CP1_CI_AS
ORDER BY
    len(p.Body) ASC


texts: Palindrome-testing Java program for an interview

texts:
In an interview I was asked to write a function that would take an input word and return true if the word is a palindrome. At first I used an approach using StringBuilder but the interviewer said that wasn't allowed and to use a for loop instead. I scored 7/9 so I'm guessing it's possible to improve this:

public static boolean isPalinedrome(String word) {

    for(int i = 0; i < word.length(); i++) {
        if(word.charAt(i) != word.charAt(word.length() - 1 - i)) {
            return false;
        }
    }
    return true;
}

I added the following to the main() section to test

String input = "racecar";
if(isPalinedrome(input)) {
    System.out.println(input + " is a palinedrome");
} else {
    System.out.println(input + " is not a palinedrome");
}

The way I test it seems to be ugly. Is there a standard way to test a new function? I guess if you're in an advanced enough environment you would have test cases for JUnit to run against it, but anything simpler that could be done in an interview with a cloud IDE?


texts: Are there any bugs or ways to make my divisor code better?

texts:
After coding my divisor code which I did as a practice for my GCSE stuff which I have to take soon, I have decided to ask the community if there are any bugs or ways I can improve my code.

import time, math
from array import *
def programme():
    num = input("Enter your Number: ")
    try:
        intnum = int(num)
        if(intnum < 0):
            error("POSITIVE NUMBERS ONLY")
        else:
            numbers = array("i",[])
            starttimer = time.time()
            i = 1
            print("\nThe divisors of your number are:"),
            while i <= math.sqrt(intnum):
                if (intnum % i) == 0:
                    numbers.insert(0,i)
                    numbers.insert(0,int(intnum/i))
                    print(i,":", int(intnum/i))
                i += 1
            numbers = sorted(numbers, reverse = True)
            print("The Highest Proper Divisor Is\n--------\n",str(numbers[1]) , "\n--------\nIt took"  ,round(time.time() - starttimer, 2)  ,"seconds to finish finding the divisors." )
    except ValueError:
       error("NOT VALID NUMBER")
    except OverflowError:
       error("NUMBER IS TO LARGE")
    except:
       error("UNKNOWN ERROR")

def error(error):
    print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running):
    programme()
    print("----------------------------------")
    restart = input("Do You Want Restart?")
    restart = restart.lower()
    if restart in ("yes", "y", "ok", "sure", ""):
        print("Restarting\n----------------------------------")
    else:
        print("closing Down")
        running = False

I don't care how small the improvement is all I want are ways in which I can make it better!

When inputting 262144 I get

Enter your Number: 262144

The divisors of your number are:
1 : 262144
2 : 131072
4 : 65536
8 : 32768
16 : 16384
32 : 8192
64 : 4096
128 : 2048
256 : 1024
512 : 512
The Highest Proper Divisor Is
--------
 131072
--------
It took 0.09 seconds to finish finding the divisors.
----------------------------------
Do You Want Restart?


texts:
To learn Haskell, I've been going at this challenge, which is to check a list of phone numbers to ensure that no number is a prefix of another. However, my code is way too slow. I am really new to Haskell so I don't know what to look for in performance optimization.

I have generated a sample input which takes 5s (uncompiled via runhaskell) on my machine. What can I do to speed this up?

main = do
    content <- getContents
    let
        allLines = lines content
        caseCount = read (head allLines) :: Int
        cases = tail allLines
    putStr $ unlines $ map toYesNo (processCases cases caseCount)

toYesNo b
    | b = "YES"
    | otherwise = "NO"

processCases :: [[Char]] -> Int -> [Bool]
processCases [] num = []
processCases cases 0 = []
processCases cases remaining =
    let
        caseLines = read (head cases) :: Int
        current = take caseLines (tail cases)
    in (if (checkListConsistency current) then True else False)
        : (processCases (drop (caseLines+1) cases) (remaining-1))

checkListConsistency :: [[Char]] -> Bool
checkListConsistency [] = True
checkListConsistency list =
    let
        number = head list
        rest = tail list
    in if checkNumberConsistency number rest
        then checkListConsistency rest
        else False

checkNumberConsistency :: [Char] -> [[Char]] -> Bool
checkNumberConsistency number [] = True
checkNumberConsistency number list =
    foldr (&&) True (map (checkNumberConsistencyVsNumber number) list)

checkNumberConsistencyVsNumber :: [Char] -> [Char] -> Bool
checkNumberConsistencyVsNumber number number2 =
    let
        numberLength = length number
        number2Length = length number2
    in if numberLength > number2Length
        then notStartsWith number number2
        else notStartsWith number2 number

notStartsWith _ [] = False
notStartsWith [] _ = True
notStartsWith (hl:tl) (hs:ts)
        | hl == hs = notStartsWith tl ts
        | otherwise = True


texts: Finding consecutive primes matching p, p + 4, p + 6, p + 10, p + 12, p + 16

texts:
Someone asked about this question on the main StackOverflow. The full question is:

  Given a value N, find p such that all of [p, p + 4, p + 6, p + 10, p + 12, p + 16] are prime.

  The sum of [p, p + 4, p + 6, p + 10, p + 12, p + 16] should be at least N.

My thinking is:

Sieve all primes under N
Ignore primes below (N-48)/6
Create consecutive slices of length 6 for the remaining primes.
Check if the slice matches the pattern.

Here's my solution. I'd appreciate some feedback.

from itertools import dropwhile, islice
def get_solutions(n):
    grid = [None for _ in range(n+1)]
    i = 2
    while i < n+1:
        if grid[i] is None:
            grid[i] = True
            for p in range(2*i, n+1, i):
                grid[p] = False
        else:
            i += 1
    sieve = (index for index, b in enumerate(grid) if b)
    min_value = (n - 48) / 6
    reduced_sieve = dropwhile(lambda v: v < min_value, sieve)
    reference_slice = list(islice(reduced_sieve, 6))
    while True:
        try:
            ref = reference_slice[0]
            differences = [v - ref for v in reference_slice[1:]]
            if differences == [4, 6, 10, 12, 16]:
                yield reference_slice
            reference_slice = reference_slice[1:] + [next(reduced_sieve)]
        except StopIteration:
            break

n = 2000000

print(next(get_solutions(n)))

# or for all solutions
for solution in get_solutions(n):
    print(solution)


texts:
How does the following look to list the directories on a posix system? This is actually the first piece of C code that I've written where I've actually been able to use for a real-world problem!
#define _GNU_SOURCE
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>

#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

struct linux_dirent {
    unsigned long  d_ino;
    off_t          d_off;
    unsigned short d_reclen;
    char           d_name[];
};

void print_files(char* dir, FILE* out)
{
    // open the file
    int fd = open(dir, O_RDONLY | O_DIRECTORY);
    if (fd == -1) handle_error("Error opening file.\n");

    // grab a buffer to read the file data
    #define BUF_SIZE (1024*1024*1)
    char* buffer = malloc(sizeof *buffer * BUF_SIZE);
    if (buffer == NULL) handle_error("Error malloc.\n");

    // do the getdents syscall writing to buffer
    int num_read = syscall(SYS_getdents, fd, buffer, BUF_SIZE);
    if (num_read == -1) handle_error("Error getdents syscall.\n");
    close(fd);

    for (long buffer_position = 0; buffer_position < num_read;) {

        struct linux_dirent *d = (struct linux_dirent *) (buffer + buffer_position);
        char d_type = *(buffer + buffer_position + d->d_reclen - 1);

        // skip on . and .. in the listing
        if (d->d_name[0] == '.') {
            buffer_position += d->d_reclen;
            continue;
        }

        // path = dir + '/' + name
        char path[400];
        strcpy(path, dir);
        strcat(path, "/");
        strcat(path, d->d_name);

        // recursive call, as necessary
        if (d_type == DT_DIR)
             print_files(path, out);
        else if (d_type == DT_REG)
            fprintf(out, "%s\n", path);

        // advance buffer position
        buffer_position += d->d_reclen;

    }

    free(buffer);

}

int main(int argc, char *argv[])
{
    char dir[1024];
    strcpy(dir, argc > 1 ? argv[1] : ".");
    FILE *out = fopen("c-log.txt", "w");
    fprintf(out, "-------------[ START ]---------------------\n");
    print_files(dir, out);
}
```


texts:
#include <iostream>
    #include <conio.h>
    #include <windows.h>
    #include <math.h>
    using namespace std;
    #define RUNS 1000
    char z[100000];
    int i,j,k,c;

    void main(void)
      {
      DWORD starttime,endtime;
      float totaltime;

      starttime = GetTickCount();//get start time
      for(k=0;k<RUNS;k++)
      {
          c=0;

      //for (i=0;i<10000;i++) z[i]=0; //clear array
      memset(z,0,100000);
        z[0]=1; // 0 is not a prime
        z[1]=1;  // 1 is not a prime
            //now remove all evens from 4 up
            for(i=4;i<100000;i=i+2) z[i]=1; //remove evens
            //now loop through remaing up to square root of max number
            for(i=3;i<316;i=i+2)
            {
            if(z[i]==0) for(j=2*i;j<100000;j=j+i) z[j]=1;
            }
      }

      endtime=GetTickCount();//get finish time
      //calc time
      for(i=0;i<100000;i++)
      {
      if(z[i]==0) {cout<<i<<" ";c++;}
      }
      cout<<"primes found="<<c<<endl;
      totaltime=((float)endtime-(float)starttime)/(1000.0*RUNS);//calculate total time in secs
      cout<<"Totaltime="<<totaltime<<" sec\n";

      printf("Press any key to end");

      getch();
      }

I'm trying to find any optimization for my sieve of Eratosthenes code for counting first 100000 prime numbers.
The program first mark all even numbers, than square root of max number.
The program already does take fraction of the seconds to count these prime numbers, but I`m looking for any optimization to make it even quicker.


texts:
I've defined myself a function for caching requests and their responses in a browser environment; I'm using ClojureScript.

(defn make-requester [namespace time-limit fun]
  (fn [cont & params]
    (let [cache (ls/get-item namespace)
          key (pr-str params)]
      (if
        (and
          (contains? cache key)
          (time/fresh? time-limit (:time (get cache key))))
        (cont (:value (get cache key)))
        (apply fun
               (concat [(fn [value]
                          (let [time (time/get-time)
                                updated (assoc cache key {:value value :time time})]
                            (ls/set-item namespace updated)
                            (cont value)))]
                       params))))))

Where
ls/get-item, ls/set-item are just getting/setting items in the local storage
and the time/ functions do what they say. The http/ functions are from the cljs-http module.

Example of using this:

(def get-status
  (make-requester
    "status"
    30000 ; 30 seconds
    (fn [cont url params]
      (go
        (cont (:body (<! (http/get url params))))))))

(get-status
  println
  "http://jsonplaceholder.typicode.com/posts/1"
  {:with-credentials? false})

This is the first time I'm doing any async operations in ClojureScript and I'd like to improve the code in any way. Can the async bit be improved? Can the apply bit be improved? Is there no spread ... shorthand? Is this the correcy way to serialzie/deserialize clojure data structures? Is the code Clojure-y enough?


texts:
I aim to improve my PHP OOP skills and made a simple calculator. Visitors can choose 2 numbers and a prefix, so they can add, subtract, divide and so forth. The output is the sum. The good thing is it's working, but is it also clean coding? Also, is it wise to use the switch statement in a function?

I hope to get some tips so I can improve and learn.

class calcdata {

public $number1;
public $prefix;
public $number2;

public function __construct() {
    $this->number1 = $number1 = $_POST['number1'];
    $this->prefix = $prefix = $_POST['prefix'];
    $this->number2 = $number2 = $_POST['number2'];

}

public function result(){

switch($this->prefix){
case "+":
return ($this->number1 + $this->number2);
break;
case "-":
return ($this->number1 - $this->number2);
break;
case "/":
return ($this->number1 / $this->number2);
break;
case "*":
return ($this->number1 * $this->number2);
break;
default:
return "Only use: \" +, -, / of * \" ";
}
}
}

$show = new calcdata();
echo $show->result();

    </body>
 </html>


texts: Trim leading zeroes from second component of a string

texts:
I have a collection of strings as follows:

  44.01
  44.02
  44.03
  44.04
  44.12
  46.05
  46

... and so on.

I want to remove leading zeros from the component of the string after the full stop.

As you can see from above, not all strings have a sub-component and not all sub-components will have leading zeros.

Is there a more elegant way of doing that from my attempt?

    List<string> codesWithSubCodes = new List<string>
    {
        "44.01", "44.02", "44.03", "44.04", "44.05", "44.06", "44.07", "44.08"
    };

    var codes = new List<string>();
    foreach (var code in codesWithSubCodes)
    {
        if (code.Contains('.'))
        {
            var prefix = code.Split('.')[0];
            var subCode = code.Split('.')[1].TrimStart('0');
            codes.Add(prefix + '.' + subCode);
        }
        else
        {
            codes.Add(code);
        }
    }

    foreach (var code in codes)
    {
        Debug.WriteLine(code);
    }


texts: Populating dropdown lists, using SQL vs. using expression trees and reflection

texts:
I'm working with a large enterprise SQL Server database with dozens of tables that are used mainly as lookups to populate dropdown lists, etc. These tables all follow the convention of having (table)Name as the string value of the item. For example the State table has a StateName column with values like California, Florida, etc.

There is an old method used to load data for a dropdown that uses raw SQL, it looks like this:

public async Task<IEnumerable<string>> GetLookupOptions(string table)
{
    List<string> values = new List<string>();

    using (var command = _context.Database.GetDbConnection().CreateCommand())
    {
        command.CommandText = $"SELECT {table}Name FROM {table} WHERE IsApproved = 1";

        _context.Database.OpenConnection();

        using (var result = await command.ExecuteReaderAsync())
        {
            do
            {
                while (result.Read())
                {
                    values.Add(result.GetString(0));
                }
            } while (result.NextResult());
        }
    }

    return values;
}

This isn't testable using InMemoryDatabase and only works against an actual database connection. I have rewritten it using Reflection and Expressions to query the DbContext.DbSet<T> based on the table name provided, like this:

public IEnumerable<string> GetLookupOptions(string table)
{
    // Get the Type for State and then replace its name with whatever entity this is querying.
    // This is hacky but it's used so the AssemblyQualifiedName will always have correct
    // version info.
    Type t = typeof(State);
    t = Type.GetType(t.AssemblyQualifiedName.Replace("State", table));

    // Get lambda used to filter <table> where IsApproved is true.
    object whereLamda = this.GetType()
        .GetMethod(nameof(CreateWhereExpression), BindingFlags.NonPublic | BindingFlags.Instance)
        .MakeGenericMethod(t)
        .Invoke(this, new object[0]);

    // Get lambda used to select <table>Name from <table>.
    object selectLamda = this.GetType()
        .GetMethod(nameof(CreateSelectExpression), BindingFlags.NonPublic | BindingFlags.Instance)
        .MakeGenericMethod(t)
        .Invoke(this, new object[] { table });

    // Get the DbSet<T> for the <table>.
    object set = _context.GetType()
        .GetMethod("Set")
        .MakeGenericMethod(t)
        .Invoke(_context, new object [0]);

    IEnumerable<MethodInfo> whereMethods = typeof(Enumerable)
        .GetMethods().Where(m => m.Name == nameof(Enumerable.Where));

    // Apply Where() method to DbSet.
    object filteredApproved = whereMethods
        .ElementAt(0)
        .MakeGenericMethod(t)
        .Invoke(set, new object[] { set, whereLamda });

    IEnumerable<MethodInfo> selectMethods = typeof(Enumerable)
        .GetMethods().Where(m => m.Name == nameof(Enumerable.Select));

    // Apply Select() method to filtered query.
    object r = selectMethods
        .ElementAt(0)
        .MakeGenericMethod(t, typeof(string))
        .Invoke(filteredApproved, new object[] { filteredApproved, selectLamda });

    return r as IEnumerable<string>;
}

private Func<T, string> CreateSelectExpression<T>(string tableName)
{
    var param = Expression.Parameter(typeof(T));
    var expr = Expression.Property(param, $"{tableName}Name");

    return Expression.Lambda<Func<T, string>>(expr, param).Compile();
}

private Func<T, bool> CreateWhereExpression<T>()
{
    var param = Expression.Parameter(typeof(T));
    var expr = Expression.Equal(
        Expression.Property(param, "IsApproved"),
        Expression.Constant(true));

    return Expression.Lambda<Func<T, bool>>(expr, param).Compile();
}

My concerns are:

Getting the correct Where and Select methods from Reflection, I don't like relying on ElementAt(). Both methods have overloads with 2 parameters.
Any and all other problems. Have I created a monster?


texts: How do I make my html object-to-table array script run faster? (Pandas)

texts:
I have a data frame that has several columns, one of which contains html objects (containing tables). I want a column of table arrays.
My problem is that this piece of code takes a long time to run. Is there any way I can optimize this? I tried list comprehension, which doesn't significantly improve run time.
Some suggested that I restructure the logic. Any suggestions how?
    df = htmldf
    countries = dict(countries_for_language('en'))
    countrylist = list(countries.values())
    arrayoftableswithcountry = []

    arrayofhtmltables = []

        for idx, row in df.iterrows():
            #print("We are now at row ", idx+1, "of", len(df),".")
            inner_html = tostring(row['html'])
            soup = bs(inner_html,'lxml')
            tableswithcountry = []
            outputr = []

            for idex,item in enumerate(soup.select('table')):
                #print("Extracting", idex+1, "of", len(soup.select('table')),".")
                table = soup.select('table')[idex]
                rows = table.find_all('tr')
                output = []
                outputrows = []

                for row in rows:
                    cols = row.find_all('td')
                    cols = [item.text.strip() for item in cols]
                    output.append([item for item in cols if item])

                if methodsname == 'revseg_geo':
                    if '$' in str(output):
                        for country in countrylist:
                            if country in str(output):
                                tableswithcountry.append(output)
                                outputr.append(table)

            arrayoftableswithcountry.append(tableswithcountry)
            arrayofhtmltables.append(outputr)

    df['arrayoftables'] = arrayoftableswithcountry
    df['arrayofhtmltables'] = arrayofhtmltables
    print('Made array of tables.')
    df.drop(columns=['html'])


texts: Computing the double Integral using MonteCarlo techniques using Julia

texts:
I decided to try and learn Julia for doing scientific computing, and I decided to tackle the problem of finding

$$ \int_{D_{\frac{1}{4}}} x^4 + y^2 dA $$

where \$ D_{\frac{1}{4}} \$ is the part of the unit circle in the first cuadrant.

My code in Julia is the following:

using Distributions
e = 10.0^(-3);
p = 0.85;
variance = 4;

N = floor(Int, variance / ((1-p)*((e/2)^2))) + 1

u = Uniform(0,2);
x = rand(N);
y = rand(N);
z = rand(u, N);

result = sum((x.^2 + y.^2 .<= 1) & (z .<= x.^4 + y.^2))*2.0 / N

which gives the nice  result \$ = 0.2945746303294543 \$

I kindly ask for how to improve my implementation, and reduce the footprint of memory (it uses almost 2 to 3gb in RAM).


texts: Simple console directive, revised using provider

texts:
I recently created my first directive based on jQuery plugin and I asked for review here: Angular console like window - first directive

I've edited my directive so now instead of $rootScope it uses provider.
Below is my code:

(function() {
  'use strict';

  angular
    .module('misiu.providers', [])
    .provider('simpleConsole', function() {

      var events = [];
      var separator = '::'; //default

      //public methods
      this.$get = function() {
        return {
          addLog: function(data) {
            addEvent('log', 'Log' + separator + data);
          },
          addError: function(data) {
            addEvent('error', 'Error' + separator + data);
          },
          clear: function() {
            events.length = 0;
          },
          events: events
        };
      };

      //private method
      var addEvent = function(type, data) {
        if (events.length > 0 && events[0].type === type && events[0].data === data) {
          events[0].count++;
        } else {
          events.unshift({
            type: type,
            data: data,
            count: 1
          });
        }
      };

      //this is available only in config
      this.setSeparator = function(value) {
        separator = value;
      };
    });

  angular
    .module('misiu.directives', ['misiu.providers'])
    .directive('simpleConsole', ['simpleConsole', function(simpleConsole) {
      return {
        restrict: 'E',
        template: [
          '
',
          '
',
          '{{event.data}}1" class="count">{{event.count}}',
          '
',
          '
'
        ].join(''),
        link: function($scope, element) {
          $scope.events = simpleConsole.events;
        }
      };
    }]);
})();

and Plunker to see results.

I'd like to ask for review. Especially that provider part, because I'm not sure if all functions in it are correctly declared - private methods should be private, setSeparator should be available only in config section and addLog,addError should be the only two public methods available inside controllers and directives.

Any other general tips are welcome.


texts:
I have a relatively long method, and I'm wondering:

How readable is it?
Is a method this long okay, or will it be bad later on?

Note: This method enables users to select from a console menu - UpArrow and DownArrow change option, and LeftArrow and RightArrow change amount.

Here is the method (from here):

    public static List<Item> Spend(string[] text,List<Item> items,int currency,out int currencyLeft,string singular=null,string textZero=null){
        Initiate(items.Count);
        var maxNameLength=items.Max(n=>n.Name.Length);
        var sellIsEnabled=items.All(v=>v.Value>=0);
        var maxCurrencyLength=Math.Max(items.Aggregate(currency,(i,j)=>j.Value).Length()+text.Take(3).Aggregate(0,(i,j)=>i+j.Length)+
            Math.Max(0,(singular=singular??text[1].RemoveLast()).Length-text[1].Length),textZero?.Length??0);
        var line=Top+1;
        var totalItems=items.Select(i=>new Item(i)).ToList();
        while(true){
            switch(Input){
                case UpArrow:
                    Option--;
                    Index--;
                    break;
                case DownArrow:
                    Option++;
                    Index++;
                    break;
                case LeftArrow:
                    if(totalItems[Option].Amount-items[Option].Amount>0){
                        totalItems[Option].Amount--;
                        currency+=items[Option].Cost;
                    } else if(sellIsEnabled&&totalItems[Option].Amount>0){
                        totalItems[Option].Amount--;
                        currency+=items[Option].Value;
                    } else{
                        Input=ReadKey(true).Key;
                        continue;
                    }
                    break;
                case RightArrow:
                    if(currency-items[Option].Cost>=0){
                        totalItems[Option].Amount++;
                        currency-=items[Option].Cost;
                    } else if(sellIsEnabled&&currency-items[Option].Value>=0&&totalItems[Option].Amount-items[Option].Amount<0){
                        totalItems[Option].Amount++;
                        currency-=items[Option].Value;
                    } else{
                        Input=ReadKey(true).Key;
                        continue;
                    }
                    break;
                case Enter:
                    currencyLeft=currency;
                    return totalItems;
                default:
                    Input=ReadKey(true).Key;
                    continue;
            }
            if(Input==LeftArrow||Input==RightArrow){
                totalItems[Option].Amount.WriteAt(maxNameLength+3,line,maxLength:totalItems[Option].Amount.Length()+2);
                (currency!=0||textZero==null?text[0]+(currency==0?"no":currency.ToString())+(currency==1?singular:text[1])+text[2]:textZero).WriteAt(0,Top+MaxLines+2,maxCurrencyLength);
            }
            Maths.RMod(ref Option,TotalOptions);
            Select.TurnPage();
            if(ThePage.Was(Turned)){
                var maxAmountLength=totalItems.Max(t=>t.Amount.Length());
                var top=Top;
                foreach(var i in Indices){
                    items[i].Name.WriteAt(2,++top,maxNameLength);
                    totalItems[i].Amount.WriteAt(maxNameLength+3,top,maxAmountLength);
                }
                for(var i=Indices.Count;i<MaxLines;i++) "".WriteAt(2,++top,1+maxNameLength+maxAmountLength);
            }
            if(Input==UpArrow||Input==DownArrow){
                ' '.WriteAt(Left,line);
                '>'.WriteAt(Left,line=Index+Top+1);
            }
            Input=ReadKey(true).Key;
            PagePlus=0;
        }
    }


texts: Looping through a tree to get branch or leaf

texts:
This is my solution to a problem from MIT's 6.034 Artificial Intelligence course (see the heading Tree reference on 6.034 Artificial Intelligence, Lab 0). Can you please help me improve my solution (keep in mind I am a beginner with no formal education in Computer Science)? To be clear, I am NOT taking this for school credit, this is an old class from 2010 available through MIT OpenCourseWare. SOURCE

  Your job is to write a procedure that is analogous to list
   referencing, but for trees. This "tree_ref" procedure will take a tree
   and an index, and return the part of the tree (a leaf or a subtree) at
   that index. For trees, indices will have to be lists of integers.
   Consider the tree in Figure 1, represented by this Python tuple: (((1, 2), 3), (4, (5, 6)), 7, (8, 9, 10))

  To select the element 9 out of it,
   we’d normally need to do something like tree[3][1]. Instead, we’d
   prefer to do tree_ref(tree, (3, 1)) (note that we’re using zero-based
   indexing, as in list-ref, and that the indices come in top-down order;
   so an index of (3, 1) means you should take the fourth branch of the
   main tree, and then the second branch of that subtree). As another
   example, the element 6 could be selected by tree_ref(tree, (1, 1, 1)).

  Note that it’s okay for the result to be a subtree, rather than a
   leaf. So tree_ref(tree, (0,)) should return ((1, 2), 3).

My Solution:

def tree_ref(tree, index):
  try:
    index = list(index)
    if not isinstance(tree, tuple) or len(index) == 0:
      return tree
    else:
      return tree_ref(tree[index[0]], index[1:])
  except IndexError:
    return "INPUT OUT OF RANGE"


texts:
I don't see any way to refactor this, but something tells me I'm missing something.

if val.instance_of?(Hash) then
    @fields.has_key?(key) ? @fields[key].merge!(val) : @fields.merge!({key => val})
elsif val.instance_of?(Array) then
    @fields.has_key?(key) ? @fields[key].push(val) : @fields.merge!({key => Array.new.push(val)})
else
    @fields.has_key?(key) ? @fields[key] << val : @fields.merge!({key => val})
end

The point of the method is to take a hash and insert a value of different types if the key doesn't exist:

{:key => "value}, {:key = ["value"]}, or {:key => {:k => "value"}}

or append if it does:

{:key=> "value1value2"}, {:key => [["value1"], ["value2"]], {:key => {:k1 => "value1", :k2 => "value2"}}

it does work as intended, so my issue is thinking that there is likely an easier way to do it.


texts: Leetcode online Find the judge, graph with highest degree

texts:
Here is the problem.

  In a town, there are N people labelled from 1 to N.  There is a rumor
  that one of these people is secretly the town judge.

  If the town judge exists, then:

  The town judge trusts nobody.

  Everybody (except for the town judge) trusts the town judge.

  There is exactly one person that satisfies properties 1 and 2.

  You are given trust, an array of pairs trust[i] = [a, b] representing
  that the person labelled a trusts the person labelled b.

  If the town judge exists and can be identified, return the label of
  the town judge.  Otherwise, return -1.

  Example 1:

  Input: N = 2, trust = [[1,2]]
  Output: 2
  Example 2:

  Input: N = 3, trust = [[1,3],[2,3]]
  Output: 3
  Example 3:

  Input: N = 3, trust = [[1,3],[2,3],[3,1]]
  Output: -1
  Example 4:

  Input: N = 3, trust = [[1,2],[2,3]]
  Output: -1
  Example 5:

  Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
  Output: 3

  Note:

  1 <= N <= 1000
  trust.length <= 10000
  trust[i] are all different
  trust[i][0] != trust[i][1]
  1 <= trust[i][0], trust[i][1] <= N

And here is my solution.

(Logic :- Check the degree of every node, +1 for incoming and -1 for outgoing. If any node is having degree as N-1 then that is the node.)

public int findJudge(int N, int[][] trust) {
        // Create graph of N and then check degree, should be N-1
        final int NOT_FOUND = -1;
        final int trustArrayLength = trust.length;

        // Degree array should have value starting from 1 to N+1
        final int[] degreeArray = new int[N + 1];

        for (int i = 0; i < trustArrayLength; i++) {
            int[] itemInTrustArray = trust[i];

            // Since its outbound connection, decrease the degree by 1.
            degreeArray[itemInTrustArray[0]]--;

            // Since its inbound connection, increase the degree by 1.
            degreeArray[itemInTrustArray[1]]++;
        }

        // Now iterate though the degreeArray to find the index having degree as N-1.
        for (int i = 1; i <= N; i++) {
            if (degreeArray[i] == N - 1) {
                return i;
            }
        }
        return NOT_FOUND;
    }

Pleae let me know, the area of improvement.


texts: Unit testing code that calls RESTful API

texts:
I'm writing a library which calls a RESTful API and then performs some work on the data.

I've architected my code like this:

I have a class (let's call it APIRequestor) that initiates a call to the API via an injected HTTPRequestor library (which basically wraps a cURL request). That class, after retrieving the response, will perform some operations on that data and then return an APIResult object to the caller.

In order to test the APIRequestor, I created a HTTPRequestorMock which extends HTTPRequestor that, rather than wrapping a cURL request, it simply reads a result from a file I have on disk that way I can test different scenarios.

Below is the code for the APIRequestor object:

<?php
namespace APITests;

require_once "PHPUnit/Autoload.php";
require_once "../classes/APIRequestor.php";
require_once 'HTTPRequestorMock.php';

class APIRequestor extends \PHPUnit_Framework_TestCase {

    public function setUp() {}
    public function tearDown() {}

    public function getMockedRequestor() {
        $requestor = new \APIClasses\APIRequestor();
        $requestor->HTTPLibrary = new HTTPRequestorMock();
        return $requestor;
    }

    public function testResponseIDsNoResults() {
        $requestor = $this->getMockedRequestor();
        $requestor->HTTPLibrary->overrideFilepath = "./mock_assets/ResponseIDsNoResults.xml";
        $responseIDs = $requestor->getResponseIDsSinceResponseID(0);
        $this->assertTrue(count($responseIDs) === 0, "More than zero results returned.");
    }

}

Is this a good design?
Can I improve this design in order to make future additions more testable?
Is this the common practice for removing a dependency on an external server for the sake of my unit tests?


texts:
I made this script to calculate the amount of silence in seconds in an audio file. Is this a good method to do this, and if yes, can it be improved? It takes about 4 seconds for 20 audio files of 100-200 seconds of audio each, which seems pretty long to me.

The audio file is split in windows of win_size seconds. Every window that is below sil_threshold is considered 'silent'. By multiplying the number of silent windows by the window size, the number of silent seconds is obtained.

import numpy as np
from scipy.io import wavfile

def calc_silence(audio, sil_threshold=0.03, win_size=0.25, ret="sec"):
    """Calculates total silence length in this audio file.

    Keywords:
        audio:          location of the audiofile OR a (samplerate, audiodata) tuple
        sil_threshold:  percentage of the maximum window-averaged amplitude
                        below which audio is considered silent
        win_size:       length of window in sec (audio is cut into windows)
        ret:            the return type; can be one of the following:
                        - "sec": return the number of silent seconds
                        - "frac": return the frac of silence (between 0 and 1)
                        - "amp": return a list of amplitude values (one for each window)
                        - "issil": return an np-array of 0s and 1s (1=silent) for each window
                        - "chunk": return a list of (start, end, is_silent) tuples,
                            with start and end in seconds and is_silent is a boolean
    """

    if isinstance(audio, tuple):
        samplerate, data = audio
    else:
        # read the sample rate and data from the wave file
        samplerate, data = wavfile.read(audio)

    win_frames = int(samplerate * win_size) # number of samples in a window
    win_amps = [] # windows in which to measure amplitude
    for win_start in np.arange(0, len(data), win_frames):
        # Find the end of the window
        win_end = min(win_start + win_frames, len(data))
        # Add the mean amplitude for this frame to the list of window amplitudes
        win_amps.append(np.nanmean(np.abs(data[win_start:win_end])))

    # Calculate the minimum threshold for a window to be silent
    threshold = sil_threshold * max(win_amps)

    # Find the windows that are silent
    sils, = np.where(win_amps <= threshold)

    # The silence length is the number of silent windows times the window length
    sil = len(sils) * win_size

    if ret == "sec":
        return sil
    elif ret == "frac":
        return len(sils) / len(win_amps)
    elif ret == "amp":
        return win_amps
    elif ret == "issil":
        return (win_amps <= threshold).astype(int)
    elif ret == "chunk":
        chunks = []
        t0, t1 = 0, 0
        is_sil = win_amps[0] <= threshold
        for wi, amp in enumerate(win_amps):
            winsil = amp <= threshold
            if winsil == is_sil:
                t1 = (wi + 1) * win_size
            else:
                chunks.append((t0*win_size, t1*win_size, is_sil))
                t0 = (wi + 1) * win_size
                is_sil = not is_sil
        chunks.append((t0*win_size, len(win_amps)*win_size, is_sil))
        return chunks
    else:
        raise ValueError("Unknown return format: {}".format(ret))


texts: Flattening lists of Vectors and Matrices into arrays

texts:
For many optimisation methods the parameters must be given as a single vector, such as Optim.jl. But for many interesting functions the parameters/coeffients to be optimised are matrices, or a mixture of matrices and vectors. Often this mix can be put into a composite type.

I got sick of rewriting methods for doing this foreach occurrence, so I made some general ones, including using staged functions to produce them for composite types.

function pack{T}(sources::AbstractArray{T}...)
    total_length = sum(map(length,sources))
    package = Vector{T}(total_length)
    @inbounds pack!(package, sources...)
    package
end

function pack!{T}(output::Vector{T}, sources::AbstractArray{T}...)
    ii = 1
    for s in sources
        output[ii:ii+length(s)-1]=vec(s)
        ii+=length(s)
    end
    output
end

function unpack!{T}(package::Vector{T}, dests::AbstractArray{T}...)
    ii = 1
    for s in dests
        s[:]= package[ii:ii+length(s)-1]
        ii+=length(s)
    end
    dests
end

function unpack{T}(package::Vector{T}, sizes::Union{Int,Tuple{Vararg{Int}}}...)
    ds = [Array{T}(sz) for sz in sizes]
    @inbounds unpack!(package, ds...)
    ds
end

@generated function pack(x)
    Expr(:call, pack, [:(x.$fn) for fn in fieldnames(x)]...)
end
@generated function pack!(dest, x)
    Expr(:call, pack!, [:dest, [:(x.$fn) for fn in fieldnames(x)]...]...)
end

@generated function unpack!(package, x)
    Expr(:block,
        Expr(:call, unpack!, [:package, [:(x.$fn) for fn in fieldnames(x)]...]...),
        :(x)
    )
end

I was cautious with my use of inbounds to only have it where I knew the vectors were the right size since I was creating them.

In C, I could have accomplished this by simply unioning the struct of arrays with a array. But I can't work out how to do that in Julia, even when going down into pointer stuff. I don't think even immutable composite types are guaranteed bits-type if they have array members.


texts:
Think of the numpad number layout.

hvd = horizontal, vertical or diagonal

coord = 1,2 or 3 if horizontal or vertical and 1 or 2 if diagonal (1 is up, 2 is down)...

hello('v', 2) - Asking for the second vertical column etc

def hello(hvd, coord):
    if hvd == 'h':
        print "horizontal it is"
        if coord == 1:
            print "789"
        elif coord == 2:
            print "456"
        elif coord == 3:
            print "789"
        else:
            print "coord is wrong"
    elif hvd == 'v':
        print "vertical it is"
        if coord == 1:
            print "741"
        elif coord == 2:
            print "852"
        elif coord == 3:
            print "963"
        else:
            print "coord is wrong"
    elif hvd == 'd':
        print "diagonal it is"
        if coord == 1:
            print "159"
        elif coord == 2:
            print "753"
        else:
            print "coord is wrong"
    else:
        print "hvd is wrong"

I just want a critique on this function. I am interested in knowing if there is a nicer way to do what I am doing and if there is anything wrong with my code.

It seems quite hard to look at especially since it contains place holder statements and the actual statements I want might be 10 lines long each... Would be unwieldy surely?


texts: Restructuring multiple variables into an array

texts:
I'm using Groovy to grab properties from a page and each of the properties are grouped into a specific type:

Groovy:

String headerImage = null
String sidebarImage = null
String footerImage = null

String mainVideo = null
String sidebarVideo = null
String overviewVideo = null

//Images
headerImage = properties["headerImage"]
sidebarImage = properties["sidebarImage"]
footerImage = properties["footerImage"]

//Videos
mainVideo = properties["mainVideo"]
sidebarVideo = properties["sidebarVideo"]
overviewImage = properties["overviewImage"]

I'm then outputting those values into my jQuery plugin with JSTL like below. Is there a better way to output the values into a jQuery plugin maybe by grouping them into an array or something? Also I only added three in this example in reality I have about 10 in each section so you can image how ugly that looks when I'm putting those values in my jQuery plugin.

$(document).ready(function () {
    $('.mediaGallery').mediaFilters({
        images: '${headerImage},${sidebarImage},${footerImage}',
        videos: '${mainVideo},${sidebarVideo},${overviewImage}',
    });
});


texts:
Inspired by Monday's Reddit daily programmer challenge, I wrote a function to check whether two strings are anagrams. It doesn't take the same input as the challenge, though, since I don't want to handle user input (yet).

For the lazy ones, the task is to write a function that checks whether the letters in the first word can be shuffled (and upcased/downcased) to create the second word. Punctuation and whitespace isn't important.

This is more or less the first code I've written in Rust, so any kind of feedback is welcome:

/// Returns the sorted alphabetic symbols of a string in lowercase.
fn normalize(s : &str) -> Vec<char> {
    let mut characters : Vec<char> = s.to_lowercase()
        .chars()
        .filter(|x| x.is_alphabetic())
        .collect();
    characters.sort();
    characters
}

/// Returns true if the sets of alphabetic symbols coincide.
pub fn is_anagram(a : &str, b : &str) -> bool{
    normalize(a) == normalize(b)
}

#[test]
fn is_anagram_test() {
    assert!( is_anagram("Clint Eastwood","Old West Action"));
    assert!( is_anagram("wisdom","mid sow"));
    assert!(!is_anagram("Reddit","Eat Dirt"));
    assert!( is_anagram("Schoolmaster","The classroom"));
    assert!( is_anagram("Vacation Times", "I'm Not as Active"));
    assert!( is_anagram("12431b53c11a5324", "abc"));
}

I'm not particularly fond of using a mut Vec<char> just to use sort, but I guess it's the same situation as in C++, where std::sort will also modify a container in-place. The code was written with previous experience in C++, but with the following Haskell code in mind:

isAnagramOf :: String -> String -> Bool
isAnagramOf = (==) `on` (sort . map toLower . filter isLetter)


texts: Depth-first Search Non-Reursive Implementation in Clojure

texts:
I've created a non-recursive dfs implementation in Clojure. I'm using the wikipedia article on dfs as a guide. I'm very new to Clojure and functional programming in general. Any tips to improve readability, make the code more idiomatic, or improve performance would be very helpful. I'm aware there is already question about a recursive dfs implementation in Clojure, but I feel like this code is different enough to warrant a separate post.

(def graph {'a '(b c e) 'b '(a d f) 'c '(a g) 'd '(b) 'e '(a f) 'f '(b e)})

(defn label
  [v discovered]
  (cons v discovered))

(defn get-edges
  [g v]
  (get g v))

(defn labeled?
 [v discovered]
  (cond
    (some #(= v %) discovered) true
    :else false))

(defn build-stack
 [S edges]
  (concat S edges))

(defn dfs
  [g v]
   (loop
    [discovered '() S (cons v ())]
     (cond
      (empty? S) (reverse discovered)
      (labeled? (last S) discovered) (recur discovered (butlast S))
      :else
       (recur
         (label (last S) discovered)
         (build-stack (butlast S) (get-edges g (last S)))))))


texts:
I'm working on some Scala problems given here, specifically:

sealed abstract class Tree[+T]
case class Node[+T](value: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
  override def toString = "T(" + value.toString + " " + left.toString + " " + right.toString + ")"
}
case object End extends Tree[Nothing] {
  override def toString = "."
}
object Node {
  def apply[T](value: T): Node[T] = Node(value, End, End)
}

While implementing an insert into a height balanced tree I have the following function:

def insert(node: Tree[Char], value: Char): Tree[Char] = {
    if(node.eq(End)){
      Node(value,End,End)
    }
    else{
      val internalNode = node.asInstanceOf[Node[Char]]
      if(internalNode.left.height == internalNode.right.height){

          if(Random.nextBoolean()){ //choose left
            internalNode.left = insert(internalNode.left,value)
          }else{
            internalNode.right = insert(internalNode.right,value)
          }

      }
      else if(internalNode.left.height > internalNode.right.height){ //insert into right
          internalNode.right = insert(internalNode.right,value)
      }
      else{ //insert into left
          internalNode.left = insert(internalNode.left,value)
      }
      internalNode
    }

  }

Could you please let me know how I could improve this code.

Is there a way I can avoid doing the casting in asInstanceOf?
How can I improve the if else checks?

General feedback is also much appreciated.


texts: Improving performance when sorting array of structs by multiple fields

texts:
I have an array of a struct containing 5 byte values.
I need to sort this array by each value in a different order depending on the situation.
These arrays are sometimes quite small (10-30 elements), sometimes quite large (1024-16384).

Below is the code I'm using. The reason this has become a bottleneck for me is due to having to make it an array again which reallocates memory for it if I understand correctly (for both the sort and turning it back to an array). My desire is to sort the array the way I want (which can be one of the 3 below situations) without having to do something like ToArray and instead populate the array that exists.

I may be entirely wrong about sorting like this or my analysis of the problem, which is why I'm here. If anyone can point me to a better way to do this, please let me know. This program needs to be able to call this routine hundreds (sometimes thousands) of times per second.

public enum eCubeType : byte {
    Air = 0,
    Dirt = 1
}

public struct strCubeFace {
    public byte X, Y, Z, LightLevel;
    public eCubeType CubeType;
}

Function call snippet including array sorting code:

        if (iSide == 0 || iSide == 1) {
            Faces = Faces.OrderBy(c => c.Y).ThenBy(c => c.CubeType).ThenBy(c => c.LightLevel).ThenBy(c => c.X).ThenBy(c => c.Z).ToArray();
            SmartMesh0();
        }
        if (iSide == 2 || iSide == 3) {
            Faces = Faces.OrderBy(c => c.Z).ThenBy(c => c.CubeType).ThenBy(c => c.LightLevel).ThenBy(c => c.X).ThenBy(c => c.Y).ToArray();
            //SmartMesh1();
        }
        if (iSide == 4 || iSide == 5) {
            Faces = Faces.OrderBy(c => c.X).ThenBy(c => c.CubeType).ThenBy(c => c.LightLevel).ThenBy(c => c.Y).ThenBy(c => c.Z).ToArray();
            //SmartMesh2();
        }

Edit for @svick or anyone else wanting to know more details:

This is in regards to a 3D procedural map generator that expands as the player moves outwards. The terrain is geometrically similar to that of Infiniminer or Minecraft. This lends itself well to combining like faces of the cube based terrain to lower vertices by 50% or higher (usually higher).

After generating the points I need to represent each cube, it's light level, and so on; I then iterate over every solid block that is adjacent to transparent/translucent blocks to create the strCubeFace structure I use to represent individual faces.

Unless I am simply doing this whole process in a very "bad" way for performance, I need to sort 6 of these arrays per chunk (grouping of 32x256x32 cubes), one for each face. It is indeed always a different array each time it is needed to be sorted. It doesn't necessarily need to be an array, but as I already know the total number of cubes adjacent to transparent/translucent blocks, setting up a simple array of the max size made the most sense to me (once the array is populated, if the number of faces in each specific array is larger than the array's length, I simply re-size the array down prior to the sort). It is my belief that most other collection storage techniques would incur a higher processing penalty or a higher memory storage penalty.

The only reason I am sorting these to begin with, which is probably most important to know/understand, is so that I can iterate over the sorted array of faces to very quickly/easily create the vertices necessary to combine like faces.

Sorry for rambling so much, but this is a rather big project and I'm not so good at condensing down my reasoning for any of these things without nearly writing a paper on the subject since it's all so intertwined. I'd nearly just post the whole project for review, but that would seem inappropriate (that and my code is borderline illegible at times as I'm currently just a hobbyist).


texts: Batch rename files with Mac Bash,while the dir index should be recorded

texts:
I need to batch rename images with Mac Bash,while the directory index should be recorded.

To rename files ,turn

Root---A----0.png
|      |
|      ----1.png
|
-------B----0.png
       |
       ----1.png

to

Root---A----0_0.png
|      |
|      ----0_1.png
|
-------B----1_0.png
       |
       ----1_1.png

Here is my code, it is ok to deal with the situation that dir A has a name of spacing.

Base=$(pwd)
num=0
IFS='
' # split on newline only
for path in *
    do
    if [[ -d $path ]]; then
        NewPath="${Base}/${path}"
        for f in "$NewPath"/*
            do
            dir=`dirname "$f"`
            base=`basename "$f"`
            name="${dir}/${num}_${base}"
            mv ${f} "$name"
        done
        num=$((num + 1))
    fi
done

Any way to do it more brilliantly? find is a good option to handle files recursively.


texts: Listing people with their phone numbers (if any)

texts:
I have the following tables in my database:

people:          phones:
+----+------+    +-----------+------------+-------------+
| id | name |    | person_id | number     | description |
+----+------+    +-----------+------------+-------------+
|  1 | Jade |    |         1 | 1234567890 | home        |
|  2 | Ben  |    |         1 |  987654321 | office      |
+----+------+    +-----------+------------+-------------+

I use a query with INNER JOIN to select the name and phone numbers for each person:

SELECT
   id,
   name,
   group_concat(
      concat(
         number,
         ' (',
         description,
         ')'
      ) ORDER BY description SEPARATOR ','
   ) AS phones
FROM people INNER JOIN phones
ON person_id = id
GROUP BY id;

Results from the above query:

+----+------+--------------------------------------+
| id | name | phones                               |
+----+------+--------------------------------------+
|  1 | Jade | 1234567890 (home),987654321 (office) |
+----+------+--------------------------------------+

But I want to use this query to go through all the people in my database and not just the ones with phone numbers, so I added the following row to the phones table:

INSERT INTO phones VALUES (0, 0, NULL);

And then modified the ON statement of the query to:

ON person_id = id OR person_id = 0

That way every person gets selected even if he has no phone numbers registered in the database:

+----+------+--------------------------------------+
| id | name | phones                               |
+----+------+--------------------------------------+
|  1 | Jade | 1234567890 (home),987654321 (office) |
|  2 | Ben  | NULL                                 |
+----+------+--------------------------------------+

Is this a proper way to achieve this? I don't really like the idea of having to make sure that the 0, 0, NULL row will always stay in the database in order to ensure the queries will work as intended. (since the company I develop this for might decide to clear the database)

This implementation requires calling an ensureNullRow() function every time before using this query, is this a good solution or would you do it differently?


texts:
I have done a bare bones implementation of a singly linked list in C++, which works:

Node class

template <typename T>
class ListNode{
    template <typename U > friend class SinglyLinkedList;
private:
    T data_;
    ListNode<T>* next_;
public:
    ListNode(void):
            data_{0},
            next_{nullptr}{}
    ListNode(T data_):
            data_{data_},
            next_{nullptr} {}

};

List class:

template <typename T>
class SinglyLinkedList{
private:
    ListNode<T>* head_;
    std::size_t size_;
public:
    SinglyLinkedList():
            head_{nullptr},
            size_{0}{}

    void insert(T item){
        ListNode<T> * p{new ListNode<T>(item)};
        if (size_ == 0){
            head_ = p;
        }else{
            p->next_ = head_;
            head_ = p;
        }
        size_++;
    }
    std::size_t getSize(){
        return size_;
    }

};

Here's what I'm looking to learn and understand:

Where is the newed up Node in the insert deleted (released)?
Is there a way to implement this without new at all?
Is there a difference between the following lines?

ListNode(void): data_{0}, next_{nullptr}{}

and

ListNode(void): data_(0), next_(nullptr){}


texts: Balanced parenthesis, with backslash escaping

texts:
Given a Balanced Parenthesis problem.

  "Balanced Parenthesis

  Create a program that checks if in a given string expression all the parenthesis are balanced.

  For Example:

  (test) - valid

  (no() - invalid

  ()(()) - valid

  (123(456)(7))( - invalid

  (val()id) - valid

  Also, take into account the "\" escape sequences:

  (nope\) - invalid

  (v\(al) - valid

  Too easy? Try doing the same for [] and {} and <>.

  (The description from Sololearn application)"

This is my solution. Do you have any advice? Is it clear enough?

import java.util.Stack;

public class BalancedParenthesis {

private static final Stack<Character> STACK = new Stack<>();
private static final String BRACELETS = "({[<)}]>";
private static final int SEPARATOR = BRACELETS.length() / 2;
private static final char BACKSLASH = '\\';

public static boolean isBalanced(String str) {
    int index; char ch;
    STACK.clear();
    for (int pos = 0; pos < str.length(); pos++) {
        ch = str.charAt(pos);
        if (ch == BACKSLASH) {
            pos ++;
            continue ; }
        index = BRACELETS.indexOf(ch);
        if (isBaceletFind(index)) {
            if (isOpenBracelet(index)) STACK.push(ch);
            else if (isPopable(index)) STACK.pop();
            else return false; }
    }
    return STACK.empty();
}

private static boolean isPopable(int index) {
    return !STACK.empty() && STACK.peek() == BRACELETS.charAt(index - SEPARATOR);
}

private static boolean isBaceletFind(int index) {
    return index != -1;
}

private static boolean isOpenBracelet(int index) {
    return index < SEPARATOR;
}

public static void checkBalance(String str) {
    System.out.print("\"" + str + "\" is");
    System.out.println((isBalanced(str) ? "" : " not") + " balanced");

}
public static void main(String[] args) {
    checkBalance("");
    checkBalance("\\");
    checkBalance("\\(");
    checkBalance("(({[<>]}))");
    checkBalance("))");
    checkBalance("(({[<(>]}))");
    checkBalance("(({[<\\(>]}))");
}
}


texts:
I studied segment tree recently and I made this code of segment tree and its queries. Is my code correct in terms of time complexity?
class segmentTree{
private:
    vector<int> mini;
    vector<int> tree;
    vector<int> maxi;
    int n;

Here in the constructor I passed the dynamic array.
public:

    segmentTree(vector<int> a)
    {
        mini=a;
        tree=a;
        maxi=a;
        n=tree.size();
    }

makeTree function builds three segment trees for different queries like sum, maximum and minimum.
    void makeTree()
    {
        reverse(tree.begin(),tree.end());
        reverse(mini.begin(),mini.end());
        reverse(maxi.begin(),maxi.end());
        for(int i=0;i<tree.size();i+=2)
        {
            tree.pb(tree[i]+tree[i+1]);
            mini.pb(min(mini[i],mini[i+1]));
            maxi.pb(max(maxi[i],maxi[i+1]));
        }
        tree.PB();
        mini.PB();
        maxi.PB();
        reverse(tree.begin(),tree.end());
        reverse(mini.begin(),mini.end());
        reverse(maxi.begin(),maxi.end());
    }

The sum function calculates the sum of given range.
    int sum(int a,int b)
    {
        a+=(n);
        b+=(n);
        int sum=0;
        while(a<=b)
        {
            if(a%2==1)
            {
                sum+=tree[a-1];
                a++;
            }
            if(b%2==0)
            {
                sum+=tree[b-1];
                b--;
            }
            a/=2;
            b/=2;
        }
        return sum;
    }

The minimum function finds the minimum value of given range.
    int minimum(int a,int b)
    {
        a+=(n);
        b+=(n);
        int minu;
        while(a<=b)
        {
            if(a%2==1)
            {
                minu=mini[a-1];
                a++;
            }
            if(b%2==0)
            {
                minu=mini[b-1];
                b--;
            }
            a/=2;b/=2;
        }
        return minu;
    }

The maximum function finds the maximum value of given range.
int maximum(int a,int b)
    {
        a+=(n);
        b+=(n);
        int maxu;
        while(a<=b)
        {
            if(a%2==1)
            {
                maxu=maxi[a-1];
                a++;
            }
            if(b%2==0)
            {
                maxu=maxi[b-1];
                b--;
            }
            a/=2;b/=2;
        }
        return maxu;
    }
};


texts:
I'm building an image filtering application, and I'm new to the Java frameworks that I need to do so. Right now, I can apply a simple 3x3 kernel blur to my thing by overwriting the RGB values of the destination picture pixel by pixel using the RGB averages from the original photo. I'm trying to increase the speed at which I can perform these filter calculations so there's less lag in my app.

I've done some surface level optimization, but if there's anything you see that could better utilize the cache or an entirely different framework that's faster than BufferedImage.getRGB(), I'd love to hear!

public void boxBlur(ImageView iv) {
       for (int height = 0; height < sourceImage.getHeight(); height++) {
           for (int width = 0; width < sourceImage.getWidth(); width++) {
               int[][] kernel = new int[][]{ // Contruct RGB array to manipulate. Edges are accounted for in construction
                   {(height == 0 || width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height - 1), (height == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width, height - 1), (height == 0 || width >= sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height - 1)},
                   {(width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height), sourceImage.getRGB(width, height), (width == sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height)},
                   {(height >= sourceImage.getHeight() - 1 || width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height + 1), (height >= sourceImage.getHeight() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width, height + 1), (height >= sourceImage.getHeight() - 1 || width >= sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height + 1)}
               };
               int redAvg = 0, blueAvg = 0, greenAvg = 0;
               for (int i[] : kernel) {
                   for (int j : i) {
                       redAvg += getRed(j); // Get bitwise value from RGB int
                       greenAvg += getGreen(j);
                       blueAvg += getBlue(j);
                   }
               }
               redAvg /= 9; // 9 is size of kernel
               greenAvg /= 9;
               blueAvg /= 9;
               destinationImage.setRGB(width, height, 65536 * redAvg + 256 * greenAvg + blueAvg); // setRGB() takes the integer value of an rgb color
           }
       }
       iv.setImage(updateDisplay());
   }


texts: Cardinal direction enum from range input

texts:
Still learning JS and I made the following function to convert degrees into cardinal directions respectively. My first iteration of the code was over 50 lines and I was able to get it down to 13 using a for loop.

Is there a way to optimize or simplify the code down even more? Is my logic and implementation ideal?

https://codepen.io/bbbenji/pen/JjPGNmY

function setCardinalDirection() {
  value = document.querySelector('#orientation').value // Get current value from range input
  document.querySelector(".degrees").textContent = value // Inject current input value into label
  direction = document.querySelector(".direction") // Define intercardinal direction display element

  degrees = 22.5 // Define range between two intercardinal directions
  cardinal = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N"]

  for ( i = cardinal.length; i >= 0; i-- ) { // Iterate through cardinal array backwards
    if ( value < degrees/2 + degrees * i ) {
      cardinalOut = cardinal[i]
    }
  }

  direction.textContent = cardinalOut // Inject current cardinal value into label
}

document.querySelector("#orientation").addEventListener('input', function(event) {
 setCardinalDirection()
})

window.addEventListener("load", function(){
 setCardinalDirection()
})
<form>

    Orientation: ° ()

  <input id="orientation" type="range" min="0" max="360" step="1" value="145">
</form>


texts: Extracting dynamic behaviors of state machines to modules

texts:
This is my initial class. (I am not trying to reinvent state-flows again, just practicing)
As you can see straight forward, it dynamically generates methods like .recommend,.recommend!, .recommendation_sent?

class Project < ActiveRecord::Base

  STATUS_TRANSITIONS =
  {
    initial: :not_started,
    not_started: { value: "On the board" },
    recommendation_sent: { value: "Recs: Recommendations Sent", event: :recommend},
    restarted: { event: :restart, to: :not_started }
  }

  after_initialize :default_status

  def default_status
    self.status ||= STATUS_TRANSITIONS[STATUS_TRANSITIONS[:initial]][:value]
  end

  STATUS_TRANSITIONS.except(:initial).each do |k,v|
    value = v[:to] ?  STATUS_TRANSITIONS[v[:to]][:value] : v[:value]
    if value.present?
      define_method "#{k}?" do
        self.status == value
      end
    end
    if v[:event].present?
      define_method v[:event] do
        self.status = value
      end
      define_method "#{v[:event]}!" do
        self.send(v[:event])
        self.save
      end
    end
  end

  def status_class
    if self.not_started?
      "label-info"
    elsif self.recommendation_sent?
      "label-warning"
    else
      "label-primary"
    end
  end

end

Now, I would like to clean up my model and extract behavior to a separate module and would like to present a pleasant dsl like this:

class Project < ActiveRecord::Base

  include StatusMachine

  status_machine initial: :not_started do

    transition :not_started, value: "On the Desk", css: "label-info"

    transition :recommendation_sent, value: "Recs: Recommendations Sent", event: "recommend", color: "label-success"

    transition :restarted, to: :not_started, event: "restart"

  end

 end

My solution looks like this:

module StatusMachine

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods

    @@states = {}
    @@initial = nil

    def transition t, opts
      if opts[:to]
        to = @@states[opts[:to]]
        value = to[:value]
        css = to[:css]
        state = { value: value, event: opts[:event], to: opts[:to], css: css }
      else
        state = { value: opts[:value], event: opts[:event], to: opts[:to], css: opts[:css] }
      end
      @@states[t] = state
      value = state[:value]

      self.class_eval do
        if value.present?
          define_method "#{t}?" do
            self.status == value
          end
        end
        if opts[:event].present?
          define_method opts[:event] do
            self.status = value
          end
          define_method "#{opts[:event]}!" do
            self.send(opts[:event])
            self.save
          end
        end
      end
    end

    def status_machine opts
      yield
      @@initial = @@states[opts[:initial]][:value]
      self.class_eval do
        after_initialize :default_status
        def default_status
          self.status ||= @@initial
        end

        def status_css
          @@states.values.find{|e| e[:value] == self.status }[:css]
        end
      end
    end
  end
end

Being quite new to meta world, I am not sure if this is the way to do such stuffs so I would like to see comments on my implementation. And also the "transition" method is ugly. I tried to refactor that, extracting to a separate method, but I don't want to add another class method to expose. And if I do private class method, things will be way more complicated. How can I approach this?


texts:
I'd like to find the best way to format date to YYYY, YYYYMM or YYYYMMDD.
Here is what I've got so far:

# gets the position of a character in the format
def get_pos(format, letter, number):
    it_number = 0
    it_pos = 0
    for char in format:
        if char == letter:
            it_number += 1
            if it_number == number:
                return(it_pos)
        it_pos += 1
    return(-1)

# loops through all the characters forming a number
def format_loop(string, old_format, letter):
    new = ''
    pos = -2
    it = 1
    while(pos != -1):
        pos = get_pos(old_format, letter, it)
        if(pos >= 0):
            new += string[pos]
        it += 1
    return(new)

# format a date
def date_format(string, old_format, new_format, delim):
    new = format_loop(string, old_format, 'Y')
    if(new_format in 'MD'):
        new += delim + format_loop(string, old_format, 'M')
    if(new_format == 'D'):
        new += delim + format_loop(string, old_format, 'D')
    return(new)

The function's intake parameters are, in order, the date string to format, its current format, the desired format in the form of 'Y', 'M' or 'D' and an optional delimiter to put in between the numbers.

I'm open for suggestions on shortening and optimising the code as well as on coding style and variables/functions naming.


texts: WordPress rest api basic auth with IP check

texts:
I'd like to use basic auth with the WordPress API, but restrict the capability to a single IP address. I've updated the existing code from here: https://github.com/WP-API/Basic-Auth accordingly.

It seems to work fine but I would be interested in any comments about security or improvements that could be made.

class BasicAuth
{
    public static function addAction(): void
    {
        $instance = new static;
        add_filter('determine_current_user', [$instance, 'json_basic_auth_handler'], 20);
        add_filter('rest_authentication_errors', [$instance, 'json_basic_auth_error'], 20);
    }

    protected $result;

    /**
     * Based on: https://github.com/WP-API/Basic-Auth
     * @param int|bool $user
     * @return int|bool|null $user
     */
    function json_basic_auth_handler($user)
    {
        $this->result = null;
        // Don't authenticate twice
        if (!empty($user)) {
            return $user;
        }
        // Check that we're trying to authenticate
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            return $user;
        }
        // Check client IP
        if (!$this->checkIpPermitted()) {
            return $user;
        }
        $username = $_SERVER['PHP_AUTH_USER'];
        $password = $_SERVER['PHP_AUTH_PW'];
        /**
         * In multi-site, wp_authenticate_spam_check filter is run on authentication. This filter calls
         * get_currentuserinfo which in turn calls the determine_current_user filter. This leads to infinite
         * recursion and a stack overflow unless the current function is removed from the determine_current_user
         * filter during authentication.
         */
        remove_filter('determine_current_user', 'json_basic_auth_handler', 20);
        $user = wp_authenticate($username, $password); /** @var WP_User|WP_Error $ */
        add_filter('determine_current_user', 'json_basic_auth_handler', 20);
        // Authentication failure
        if (is_wp_error($user)) {
            $this->result = $user;
            return null;
        }
        // Authentication success
        $this->result = true;
        return $user->ID;
    }

    protected function checkIpPermitted(): bool
    {
        $options = get_option(OptionsPage::CONNECT_OPTIONS);
        $ip = $options['ip'] ?? '';
        if (($_SERVER['REMOTE_ADDR'] ?? null) !== $ip) {
            $this->result = new WP_Error('ip-blocked', 'Invalid request');
            return false;
        }
        return true;
    }

    function json_basic_auth_error($error)
    {
        // Passthrough other errors
        if (!empty($error)) {
            return $error;
        }
        // WP_Error if authentication error, null if authentication method wasn't used, true if authentication succeeded.
        return $this->result;
    }
}


texts:
I wrote a small particle engine in Java for my Pong clone.

I read that changing a texture is very expensive in OpenGL, so I tried to change the texture as few times as possible.  Therefore I change the texture in the render method of the emitter and not in the render method of every particle.  Although my framerate drops from about 8000 FPS to 4000 FPS while there are about 60 particles on the screen.

So, is it possible to improve my particle engine when it comes to rendering? I am only asking for the rendering, because when I use the engine, but disable its rendering, nothing changes in the FPS.

This is the render Method of the particle emitter:

public void render() {
    //Initialize....
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    BloodParticle.PARTICLE_TEXTURE.bind();

    for(Integer index : this.getBlockedParticles()){
        this.getParticles()[index].render();
    }

    GL11.glDisable(GL11.GL_TEXTURE_2D);
}

And this is the code for the particle self:

public void render() {
    if(!this.isAlive()){
        return;
    }

    // Store matrix
    GL11.glPushMatrix();

    // Set to particle's position and scale
    GL11.glTranslatef(this.getPosition().getX(), this.getPosition().getY(), 0);
    GL11.glScalef(3.5f, 3.5f, 1.0f);

    // Set the current alpha.
    GL11.glColor4f(1.0f, 1.0f, 1.0f, this.getAlphaFade());

    //Draw the texture on a quad.
    GL11.glBegin(GL11.GL_QUADS);
    {
        GL11.glTexCoord2f(0, 0);
        GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
                -PARTICLE_TEXTURE.getImageHeight()/2.0f);

        GL11.glTexCoord2f(0, 1);
        GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
                PARTICLE_TEXTURE.getImageHeight()/2.0f);

        GL11.glTexCoord2f(1, 1);
        GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
                PARTICLE_TEXTURE.getImageHeight()/2.0f);

        GL11.glTexCoord2f(1, 0);
        GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
                -PARTICLE_TEXTURE.getImageHeight()/2.0f);

    }
    GL11.glEnd();

    //Get the matrix again.
    GL11.glPopMatrix();
}