texts: Appending data to a web page from a form using a JavaScript class

texts:
Recently I've been reading about classes in JavaScript and decided to code this simple form to test them out.
Even if the code works I am still pretty sure I lack understanding of classes and other js utilities, for example:

did I need to use constructor in this class? if not when should I use it?
is there a more efficient way to append multiple elements to the page?
is the try and catch used properly in this case?
generally speaking - is it correct example of where i should be using classes at all?

I'm not concerned with the looks of it but with functionality. Thanks for your help.

const outp = document.getElementById('err');

class data{
  constructor(email, url, number){
    this.email = email;
    this.url = url;
    this.number = number;
  }
  static append(){
    var par = document.createElement('P');
    var em = document.createTextNode(email.value);
    var ur = document.createTextNode(url.value);
    var num = document.createTextNode(number.value);
    par.appendChild(em);
    par.appendChild(ur);
    par.appendChild(num);
    document.body.appendChild(par);
  }
}

document.getElementById('submit').addEventListener('click', () => {
  outp.innerHTML = "";
  let email = document.getElementById('email').value;
  let url = document.getElementById('url').value;
  let number = document.getElementById('number').value;
  try{
    if(email == '' || url == '' || number == '' ) throw "Empty";
    data.append();
  }
  catch(err){
    outp.innerHTML = err;
  }
})
<!DOCTYPE html>

    <meta charset="utf-8">
    <link type="text/css" rel="stylesheet" href="style.css" />
    <title></title>

        Email
        <input type="email" id="email" required />

        Url
        <input type="url" id="url" required />

        Number
        <input type="number" id="number" required />

      <button type="button" id="submit">Submit</button>


texts: Should we create a new constant or modify an existing one

texts:
I was fixing a bug in the code and it was something like this:

int const ROW_LOC = 1;
//....
Foo ( x , y , ROW_LOC ) ;

so it was passing that constant to a method ... and this ROW_LOC constant is being used in multiple other places in the code too.

For ONLY ONE place in the code because this constant was getting passed to some method that was working with a zero-based index I did like this:

SomeOtherFooMethd ( x , str , ROW_LOC -1 );

So my question is: Do I need to create a separate constant with value Zero for this one method call or you would continue using the same ROW_LOC and like I did just decremneting it by 1 in this case?


texts: Django template filter - sort by multiple keys

texts:
I have prepared an implementation of sort_by_keys filter:

{% for donation in donations|sort_by_keys:'date,-value' %}
    <img src="{{ donation.stamp_img_url }}" />
{% endfor %}

Example data:

donations = [
    {
        date: '29-07-2014',
        value: 150,
    },
    {
        date: '07-10-2014',
        value: 450,
    },
    {
        date: '29-07-2014',
        value: 500,
    },
]

Expected result:

donations|sort_by_keys:'date,-value'

Should return:

[
    {
        date: '29-07-2014',
        value: 500,
    },
    {
        date: '29-07-2014',
        value: 150,
    },
    {
        date: '07-10-2014',
        value: 450,
    },
]

My implementation:

@register.filter
def sort_by_keys(value, keys):
    _list = list(value)

    def compare(item1, item2):
        for key in item1.__keys_for_sort.split(','):

            if key.startswith('-'):
                key = key.replace('-', '')

                if getattr(item1, key) > getattr(item2, key):
                    return -1
                elif getattr(item1, key) < getattr(item2, key):
                    return 1
            else:
                if getattr(item1, key) < getattr(item2, key):
                    return -1
                elif getattr(item1, key) > getattr(item2, key):
                    return 1

        return 0

    for item in _list:
        setattr(item, '__keys_for_sort', keys)

    _list = sorted(_list, cmp=compare)

    for item in _list:
        delattr(item, '__keys_for_sort')

    return _list

I really don't like the idea of injection special attributes like __keys_for_sort, to have possibility of using this value in comparator, but I don't know how to write this better.


texts: Simple program to print from a buffer until a newline is found

texts:
For practice, I wrote a small program that goes through a string in the data section (although, it could be easily adapted to take user input), and print out the characters in the string until it finds a newline, then stops.
This is by far the most complicated assembly program I've ever written. It's the first time I've ever used a jump and cmp. It's simple, but there's likely improvements I can make, so I thought I'd try to get feedback.
I decided to write it in 32-bit because the system calls are a little easier to wrap my head around. I'll transition to x86-64 once I know what exactly my school is going to be using; because I've seen both so far in slides.
firstjmp.asm
global _start

section .data
    input: db `1234567890\n`

section .text
    _start:
        mov esi, input  ; Current head of string

        .loop:
            mov eax, 4
            mov ebx, 1
            mov ecx, esi
            mov edx, 1
            int 0x80

            inc esi

            cmp BYTE [esi], 10
            jne .loop  ; Stop looping once we've found the newline

        mov eax, 1
        mov ebx, 0
        int 0x80

nasm firstjmp.asm -g -f elf32 -Wall -o firstjmp.o
ld firstjmp.o -m elf_i386 -o firstjmp

┌─[brendon@parrot]─[~/Desktop/Classes/CompArc/Lab4/asm]
└──╼ $./firstjmp
1234567890┌─[brendon@parrot]─[~/Desktop/Classes/CompArc/Lab4/asm]


texts: Finding unique top sums from multiple lists

texts:
My question arises from this post on MSE where I have provided an answer to solve the question :

There are multiple lists given. The number of lists is arbitrary.
Each list contains numbers and is sorted descendingly.
We shall take exactly \$1\$ element from each list and calculate the sum of elements.How would you go about finding the top \$N\$ sums?

Here the top sums need not to be different, just the indices of them. I wanted to write an algorithm to find the top \$N\$ unique sums, namely where the sum of elements is different. What I have done is using the same approach described in the linked post. The problem is that for some inputs there are lots of duplicate sums, so the research for the unique ones gets slower and slower. I post the implementation in python
import time

def top_solutions_2(N,lists):

    N_best = []
    k, len_k_lists = len(lists), [len(x) for x in lists]
    init_sol = (sum(x[0] for x in lists),tuple(0 for x in range(k)))
    comp_list, new_vals = [[init_sol]], []
    seen = {init_sol[1]}

    for _ in range(N) :

        curr_best = [float('-inf')]
        for x in comp_list :
            if x and x[-1][0] > curr_best[0] : curr_best = x[-1]

        N_best.append(curr_best)

        inds = []

        for arr in comp_list :

            while arr :

                comp_val = arr.pop()

                if curr_best[0] > comp_val[0] : arr.append(comp_val); break

                inds.append(comp_val[1])

        comp_list.append([])

        for ind in inds :

            for x in range(k) :

                if len_k_lists[x] > ind[x]+1 : r = tuple(c if i != x else c+1 for i,c in enumerate(ind))
                else : continue

                if r not in seen :
                    curr_sum = curr_best[0]+lists[x][r[x]]-lists[x][r[x]-1]
                    comp_list[-1].append((curr_sum,r))
                    seen.add(r)

        comp_list[-1].sort()

    return N_best

for N in range(10,60,10) :

    lists = [ [23,5,3,2,1],
              [19,9,8,7,0],
              [17,12,4,2,1],
              [15,13,11,9,2],
              [21,17,13,9,4],
              [16,13,12,11,1],
              [27,23,21,18,4],
              [31,25,24,12,1],
              [27,22,14,7,3],
              [9,8,7,6,5]]

    a = time.time()
    top_solutions_2(N,lists)
    b = time.time()
    print("Top {} in {} sec".format(N,b-a))

where the output is
Top 10 in 0.0 sec
Top 20 in 0.07787561416625977 sec
Top 30 in 0.5308513641357422 sec
Top 40 in 2.2048890590667725 sec
Top 50 in 7.203002452850342 sec

How can a more efficient algorithm with a lower complexity and/or a lower running time be made?And also, how can my approach be improved in efficiency?
Thank you in advance


texts: Business logic validation as custom Bean Validation annotations?

texts:
This is not my solution but that of an existing application I am enhancing.

Basically what they are doing is annotating a Form.java with a custom validator that does all trivial AND business logic validation

@MyCreateFormValidator // which contains business logic validation
// validator uses Services / Repositories that actually queries the DB for checking
public class MyCreateForm {

    @NotEmpty
    private String name;

    // and more trivial validations
}

Question: I myself don't like the idea of this and would want to move the business logic validation on the Service layer instead of doing @Valid on the Controller level but maybe I am missing something.

Is my solution of moving to Service layer better than this?


texts: Newton's algorithm for a polynomial of arbitary degree

texts:
Improvement over the last one I posted (now deleted, had no answers and was only cubics). Uses Horner's algorithm this time...

package main

import (
    "fmt"
    "math"
)

const ε float64 = 0.01

type polynomial struct {
    coeffs []float64
    x      float64
}

// Both of these functions use Horner's algorithm

func evalPoly(p polynomial, n int) float64 {
    var result float64 = 0
    for i := 0; i < n; i++ {
        result = result*p.x + p.coeffs[i]
    }
    return result
}

func evalPolyDeriv(p polynomial, n int) float64 {
    var result float64 = 0
    for i := 0; i < n-1; i++ {
        result = result*p.x + float64(n-i-1)*p.coeffs[i]
    }
    return result
}

func f(p polynomial) float64 {
    return evalPoly(p, len(p.coeffs)) / evalPolyDeriv(p, len(p.coeffs))
}

func solveNewton(p polynomial) float64 {
    h := f(p)
    for math.Abs(h) >= ε {
        p.x -= h
        h = f(p)
    }
    return p.x - h
}

func main() {
    guess := float64(2)
    coeffs := []float64{1, -2, 1, -4} // Can be of arbitary length
    fmt.Println(solveNewton(polynomial{coeffs: coeffs, x: guess})) // 2.3146...
}


texts:
Activity

public class StopWatchActivity extends AppCompatActivity {

    int seconds;
    boolean running;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stop_watch);
        runTimer();
    }

    public void startTimer(View view){
        running = true;
    }

    public void stopTimer(View view){
            running = false;
        }

    public void resetTimer(View view){
            running = true;
            seconds = 0;
        }

    public void runTimer(){
        final TextView textView = (TextView) findViewById(R.id.timer);
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                    int hours = seconds / 3600;
                    int minutes = (seconds % 3600) / 60;
                    int sec = seconds % 60;
                    String time = String.format("%d:%02d:%02d", hours, minutes, sec);
                    textView.setText(time);
                if(running) {
                    seconds++;
                }
                handler.postDelayed(this, 1000);
            }
        });

    }
}

I am learning android. I made this app work from my reference book.

I want to know few things.

How do I improve my code?
Why should I use handler?
If other wasy to do this, thenWhy does this approach fails to update the layout?
What else should I consider in this app in terms of performance?
If third question cannot be answered in this domain, please leave that.


texts:
I am new to Express so I'd like to clear my code. This is Express with Redis support. I am getting someId and then I am searching it on Redis or using scraper which accepts this ID. I am then using just prepared template jade and rendering it.

exports.run = (req, res) ->
  return res.status(400).json(error: 'no someId') unless req.query.someId?

  orderId = req.query.someId
  redis.get someId, (err, response) ->
    if err?
      log.error config.redisErrorMessage if check err.message
      log.warn err, 'Error during redis.get'

    if response?
      res.setHeader('content-type', 'text/html')
      res.send response

    else
      scrapeData someId, res, (err, locals) ->
        if err?
          log.warn {err, orderId}, 'order not found'
          return res.status(404).json(error: err.message)

        if locals.redirect?
          return res.redirect 301, locals.redirectUrl

        res.app.render 'index', locals, (err, html) ->
          if err?
            log.warn err, 'render error'
            return res.status(404).json(error: err.message)

          else
            # render without waiting setex
            res.setHeader('content-type', 'text/html')
            res.send html

            # caching data after final render
            redis.setex orderId, config.REDIS_CACHE_INTERVAL, html, (err) ->
              if err?
                if check err.message
                  log.error err, config.redisErrorMessage
                else
                  log.error err, 'Error during redis.setex'


texts: UPDATE SQL with prepared stmt using only 1 variable

texts:
HTML form field names must be equal to SQL table field names.

Changing only table name and allowed fields can be used in many other update pages.

How can I improve this?

$allowed = array("name","surname","email","rank");
$items = '';
foreach($_POST as $key => $value) {
    if (in_array($key , $allowed)) {
        $items.="`".str_replace("`","``",$key)."`". "='$value', ";
    }
}
$items = substr($items, 0, -2);

$table = "users" ;
$userId = $_POST['userId'];

$sql = "UPDATE $table SET $items WHERE ID = ?";
if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param('i', $userId);
    $stmt->execute();
}

CODE REVIEW with PDO prepare statement

In accord with the answer, my first code was open to SQL injection and i change it
with PDO prepared statement like a suggestion.

$dbh = new PDO('mysql:host=localhost;port=0000;dbname=xxx','yyy','zzz',
array(PDO::ATTR_PERSISTENT => false,PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false));

$allowed = array("name","surname","email","rank");
$params = array();
$items = null;

foreach($_POST as $key => $value) {
    if (in_array($key , $allowed)) {
        $items .= "$key=:$key ,"; // create parametrized string
        $params[$key] = $value; // populate the array with allowed $_POST values
    }
}

$items = substr($items, 0, -2); // escaping the last coma
$table = "users" ;

$sql = "UPDATE $table SET $items WHERE ID = :userId ";
$params['userId'] = $_POST['userId']; // add the WHERE param value to array
$stmt = $dbh->prepare($sql);
$stmt->execute($params);

In this way, the variable $items doing all job :)


texts: Find the next prime number — flow control of nested `for` loops

texts:
This code works perfectly, but it bothers me.  Having a labeled, nested for loop, with a true condition, a break statement, and a continue label...it really bothers me.  But I couldn't figure out any other way to arrange the flow control here without sacrificing the efficiency.  Any ideas?

private static ArrayList<Integer> primeList = new ArrayList<Integer>(Arrays.asList(2,3));

public static int getNextPrime() {
    int testNum;
    search:
        for (testNum = (primeList.get(primeList.size() - 1) + 2); true; testNum += 2) {
            int prime = 0;
            for (int index = 1; prime * prime <= testNum; index++) {
                prime = primeList.get(index);
                if (testNum % prime == 0) continue search;
            }
            break;
        }
    primeList.add(testNum);
    return testNum;
}

From the names I am using, this should be fairly self-documenting, but to say it in English: This is part of a public class Primes that I wrote, specifically the part that actually does the finding of primes.  My various other methods (fillListToIndex, fillListToValue, findPrimeN—not shown) all ultimately rely on getNextPrime() for the actual primality testing.

All it does is find the next prime that has not already been found, memoize it, and return it.


texts: Object comparison method as an example of using the functional style

texts:
I just started learning about functional programming, and thought I would have a look at writing a simple object comparer as the basis for my implementation. Below is my result.

My assumption (in writing) is that functional code is intended to not modify external state, and not have side effects. If I functional style correctly, pure functions are ones who operate only on their operands.

The link to all the source code is on GitHub in a public repo, which can be found here. The most relevant bits are below:

public class DifferenceBag
{
    public string PropertyName { get; }
    public PropertyInfo PropertyInfo { get; }
    public object LeftHandValue { get; }
    public object RightHandValue { get; }
}

The main object constructor is here:

    private const BindingFlags PublicPropertyBindingFlags = BindingFlags.Public | BindingFlags.Instance;

    private readonly ImmutableList<PropertyInfo> _properties;
    public ObjectComparer()
    {
        var propertySet = typeof(T).GetProperties(PublicPropertyBindingFlags);

        var builder = ImmutableList.CreateBuilder<PropertyInfo>();
        for (var i = 0; i < propertySet.Length; i++)
        {
            var immutable = propertySet[i].GetCustomAttribute<ImmutableAttribute>();

            if (immutable != null && immutable.IsTargetMutable)
            {
                builder.Add(propertySet[i]);
            }

            var ignore = propertySet[i].GetCustomAttribute<IgnoreCompareAttribute>();

            if (ignore != null && !ignore.SkipProperty)
            {
                builder.Add(propertySet[i]);
            }
        }

        _properties = builder.ToImmutable();
    }

And the primary method:

    public static readonly IEnumerable<T> EmptyBag = new T[0];
    public IEnumerable<DifferenceBag> Compare(T source, T target)
    {

        if (source == null)
            throw new ArgumentNullException(nameof(source));

        if (target == null)
            throw new ArgumentNullException(nameof(target));

        // If either target is null or our property bag list is empty,

        // then just bail.

        if (_properties.Count == 0)
            return EmptyBag;

        var list = new LinkedList<DifferenceBag>();
        foreach (var property in _properties)
        {

            var src = property.GetValue(source);
            var tgt = property.GetValue(target);

            // By calling object.Equals(object, object), we can avoid null-reference exceptions.
            if (!object.Equals(src, tgt))
                list.AddLast(new DifferenceBag(property.Name, src, tgt, property));
        }

        return list;
    }
}

So, ObjectComparer<T> acquires the property list during construction. This is state, but it's local to the comparer instance. That state is then used during the IEnumerable<DifferenceBag> Compare(T, T) routine.

So, my questions are:

Is this an example of functional design?
If not #1, then how could I refactor into a functional design?
Is there any benefit #2?

My interest in this topic is not constrained to the context of this object, but the context of patterns in general.


texts: Scrape a reddit post submission for comments and save comments to JSON file (revised)

texts:
This is the revised code after incorporating the suggestions from user Roman Susi.
Link to the previous post here.

Notable edits: I have factored out the bigger functions into smaller tasks. The functions and variables have(hopefully) less ambiguous names, and the JSON object is now deepcop[ied].

I am still interested in making the code more Pythonic, factoring out the functions if need be, and wondering if my use of deepcopy is appropriate. I am open to any other suggestions.

Updated Code:

#!/usr/bin/python3
from copy import deepcopy
import json
import os
import praw

"""
Scrapes posts for comments and saves the comment ID and comment text to the
accompanying JSON file.
"""

JSON_DEFAULT_LOC = os.environ.get('JSON_LOCATION') or os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "survey_response.json")

def login():
    """ Create a reddit instance according to praw.ini configuration.
    Call reddit.user.me() as a check.
    Return reddit instance.
    """
    print("Authenticating")
    reddit = praw.Reddit("appname", user_agent="Chrome:com.example.bot-"
                                                "name:v1 (by /u/)")
    print("Authenticated as {}".format(reddit.user.me()))
    return reddit

def load_survey_responses(fp=None):
    """ Load the current survey response file as a JSON object.
    """
    if fp is None:
        fp = JSON_DEFAULT_LOC
    with open(fp, "r") as file:
        survey_results = json.load(file)
    return survey_results

def scrape_submissions(reddit):
    """ For each post specified in survey_responses.json, scrape the comments
    within the post and write the new or updated responses to the JSON dict.
    """
    survey_responses = load_survey_responses()
    shortlink_id_list = extract_shortlink_id(survey_responses)

    for sl_id in shortlink_id_list:
        submission = reddit.submission(id=sl_id)
        try:
            updated_responses = prepare_survey_update(submission,
                                                      sl_id,
                                                      survey_responses)
            write_comments_to_file(updated_responses)
            print("Comments from '{}' "
                  "saved to file".format(submission.subreddit))
        except OSError as e:
            print("Could not write to file: {}".format(e))

def extract_shortlink_id(survey_responses):
    return [survey_responses[sub][0]["shortlink"][-6:]
            for sub in survey_responses]

def prepare_survey_update(submission, sl_id, survey_responses):
    """ Combs through a submission's comments and replaces the "more comments",
    extracts the comments from the submission, and prepares file to be written
    with an updated JSON dictionary.
    """
    submission_replaced = replace_more_comments(submission)
    submission_comment = extract_submission_comment(submission_replaced)
    updated = update_response(survey_responses, submission_comment, sl_id)
    return updated

def replace_more_comments(submission):
    submission.comments.replace_more(limit=0)
    return submission

def extract_submission_comment(submission_replaced):
    submission_comment = [{comment.id: comment.body}
                          for comment in submission_replaced.comments.list()]
    return submission_comment

def update_response(old_responses, comment_to_add, sl_id):
    new_responses = deepcopy(old_responses)
    for i in new_responses:
        if sl_id in new_responses[i][0]["shortlink"]:
            new_responses[i][1]["responses"] = comment_to_add
    return new_responses

def write_comments_to_file(updated_json, fp=None):
    if fp is None:
        fp = JSON_DEFAULT_LOC
    with open(fp, "w") as fp:
        json.dump(updated_json, fp)

def main():
    reddit = login()
    scrape_submissions(reddit)

if __name__ == "__main__":
    main()


texts: Bitwise operation to get the weekday name

texts:
The function days_name receive a val (string) corresponding to weekdays in hexadecimal.

def days_name(val)
    value = val.to_i(16)
    week = Array.new

    if value.eql? 127
      week.push 'All'
    elsif value.eql? 0
      week.push 'No'
    else
      week.push 'mon' if (value & 1) > 0
      week.push 'tue' if (value & 2) > 0
      week.push 'wed' if (value & 4) > 0
      week.push 'thu' if (value & 8) > 0
      week.push 'fri' if (value & 16) > 0
      week.push 'sar' if (value & 32) > 0
      week.push 'sun' if (value & 64) > 0
    end
    week.join(' ')
end


texts: Finding objects with even references tidier

texts:
As the title says, I'm trying to make my code less horrible looking! For a university practical, I've to use recursive methods to return the even references in a collection of Integer objects stored in an ArrayList.

For example, if the input is [1, 2, 3, 4], my method should return [1, 3] (i.e. elements 0 and 2, the even elements).

My code works, but I feel is horrible:

import java.util.*;

public class ListMethods {

public static ArrayList<Integer> evenList (ArrayList<Integer> tList) {
    ArrayList<Integer> newList = ListMethods.deepClone(tList);
    int tempStorage = newList.size();

    if (newList.size() <= 0)
        return newList;
    else
    {
        if (newList.size()%2==0)
            tempStorage = newList.remove(newList.size()-2);
        newList.remove(newList.size()-1);
        newList = ListMethods.evenList(newList);
        if (tempStorage!=0)
            newList.add(tempStorage);
    }
    return newList;
}

public static ArrayList<Integer> deepClone (ArrayList<Integer> tList) {
    ArrayList<Integer> list = new ArrayList<Integer>();

    for (Integer i : tList)
        list.add(new Integer(i));
    return list;
}

public static void main (String[] args) {
    ArrayList<Integer> tempList = new ArrayList<Integer>();
    tempList.add(1);
    tempList.add(2);
    tempList.add(3);
    tempList.add(4);
    tempList.add(5);
    tempList.add(6);

    for (Integer i : tempList)
    { System.out.println (i); }

    ArrayList<Integer> evenList = ListMethods.evenList(tempList);
    System.out.println();

    for (Integer i : evenList)
    { System.out.println (i); }
}
}

The cloning section I have to include, at our lecturer's request. The real part I'm looking to tidy up is the if/else inside the evenList method.

Does anybody have any ideas?


texts: Vectorizing a sequence \$x_{i+1} = f(x_i)\$ with NumPy

texts:
I would like to populate a NumPy array with "accumulated" results from a custom function.

Currently, my code is:

import numpy as np
def f(x, mu):
    return mu * x * (1 - x)

def populate(x0, mu, n):
    s = np.zeros(n)
    x = x0
    for i in range(n):
        s[i], x = x, f(x, mu)
    return s

It does not take advantage of the vectorization performance of NumPy.

Is there any way to improve the speed of creating arrays like this?


texts: Comb Sort Multi-dimensional Array on Key

texts:
Previously: Comb Sort in VBA

I've been running two different comb sorts (on arrays) depending on whether I want to sort numbers or strings and I figured I would give using Variant a try instead. source here.

Additionally, I wanted to sort 1- or 2- dimensional arrays on a specific key column, but keeping rows together.

So, this sorts 2D arrays based on a key column.

code:

Private Sub CombSortArray(ByRef dataArray As Variant, Optional ByVal numberOfColumns As Long = 1, Optional ByVal sortKeyColumn As Long = 1, Optional ByVal sortAscending As Boolean = True)
    Const SHRINK As Double = 1.3
    Dim initialSize As Long
    initialSize = UBound(dataArray, 1)
    Dim gap As Long
    gap = initialSize
    Dim index As Long
    Dim isSorted As Boolean

    Do While gap > 1 And Not isSorted
        gap = Int(gap / SHRINK)
        If gap > 1 Then
            isSorted = False
        Else
            gap = 1
            isSorted = True
        End If
        index = 1
        Do While index + gap <= initialSize
            If sortAscending Then
                If dataArray(index, sortKeyColumn) > dataArray(index + gap, sortKeyColumn) Then
                    SwapElements dataArray, numberOfColumns, index, index + gap
                    isSorted = False
                End If
            Else
                If dataArray(index, sortKeyColumn) < dataArray(index + gap, sortKeyColumn) Then
                    SwapElements dataArray, numberOfColumns, index, index + gap
                    isSorted = False
                End If
            End If
            index = index + 1
        Loop
    Loop

End Sub

Private Sub SwapElements(ByRef dataArray As Variant, ByVal numberOfColumns As Long, ByVal i As Long, ByVal j As Long)
    Dim temporaryHolder As Variant
    Dim index As Long
    For index = 1 To numberOfColumns
        temporaryHolder = dataArray(i, index)
        dataArray(i, index) = dataArray(j, index)
        dataArray(j, index) = temporaryHolder
    Next
End Sub

And my testing procedure -

Option Explicit

Public Sub TestCombSort()
    Const SORT_KEY_COLUMN As Long = 1

    Dim targetSheet As Worksheet
    Set targetSheet = ActiveSheet
    Dim dataArray As Variant
    Dim lastRow As Long
    lastRow = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Row
    Dim lastColumn As Long
    lastColumn = targetSheet.Cells(1, targetSheet.Columns.Count).End(xlToLeft).Column

    dataArray = targetSheet.Range(targetSheet.Cells(1, 1), targetSheet.Cells(lastRow, lastColumn))
    Dim index As Long

    CombSortArray dataArray, lastColumn, SORT_KEY_COLUMN, True
    targetSheet.Range(targetSheet.Cells(1, lastColumn + 1), targetSheet.Cells(lastRow, (lastColumn * 2))) = dataArray

End Sub

And some delimited sample data:

47,H,84
40,J,54
30,L,33
28,N,28
52,P,50
11,R,75
79,T,29
46,V,34
65,X,84
36,Z,42
5,bb,2
19,dd,81
25,ff,98
66,hh,96
65,kk,68
33,mm,80
63,oo,67
52,qq,22

Something I have noticed is that rubberduck is telling me both procedures can be functions, but I'm not sure why I would do that.


texts: Improving the code, events in individual functions (refactoring)

texts:
code
It is necessary from this piece of code
const rectPos = { x: 0, y: 0 };
const currPos = { x: 0, y: 0 };

const mouseEvent = () => {
canvas.onmousedown = (e) => {
    const start = { x: e.offsetX, y: e.offsetY };
        canvas.onmousemove = (e) => {
            currPos.x = getXPixelRatio * Math.round((rectPos.x + e.offsetX - start.x) / getXPixelRatio);
            currPos.y = getYPixelRatio * Math.round((rectPos.y + e.offsetY - start.y) / getYPixelRatio);
            currPos.x = edge(currPos.x, 0, w - 25);
            currPos.y = edge(currPos.y, 0, h - 25);
            renderAll()
            drawRect(currPos.x, currPos.y);
        }
        document.onmouseup = (e) => {
            rectPos.x = currPos.x;
            rectPos.y = currPos.y;
            canvas.onmousemove = null
        }
    }
}

It is necessary to separate the event handler and the function itself
Something like this
const mouseDown = () =>{}
const mouseMove = () =>{}
const mouseUp = () =>{}

function mouseEvents() {
    canvas.addEventListiner("mousedown", mousedown)
    ....
}


texts:
I implemented this for the Prime Generator problem on SPOJ, but I am only getting 0.01s run-time, and would like to be able to match the run-times of the top submissions, which are all 0.00s.
What are some suggestions for optimizations that I can do to improve the efficiency of this algorithm?

Input: The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output: For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

#include <cmath>
#include <cstdio>
#include <vector>

using namespace std;

typedef vector<bool> VB;
typedef vector<int> VI;

VI sieve(int n) {

  VB is_prime(n, true);
  int sqrtn = sqrt(n);

  for (int i = 2; i <= sqrtn; ++i) {
    if (is_prime[i]) {
      for (int j = i * 2; j <= n; j += i) {
        is_prime[j] = false;
      }
    }
  }

  VI primes;
  int prime_size = is_prime.size();

  for (int i = 2; i <= prime_size; ++i) {
    if (is_prime[i]) {
      primes.push_back(i);
    }
  }
  return primes;
}

void segmented_sieve(int &m, int &n) {

  int range = n - m;
  VI primes = sieve(range + 1);
  VB is_prime(range + 1, true);

  for (const auto &prime : primes) {
    for (int i = (m / prime) * prime; i <= n; i += prime) {
      if (i >= m && i != prime) {
        is_prime[i - m] = false;
      }
    }
  }

  for (int k = 0; k <= range; ++k) {
    if (is_prime[k]) {
      printf("%d\n", m + k);
    }
  }
}

int main() {

  int t;
  scanf("%d", &t);

  while (t--) {
    int m, n;
    scanf("%d%d", &m, &n);
    if (m == 1) m++;
    segmented_sieve(m, n);
  }
  return 0;
}


texts: Two keyboard handlers for a video game character

texts:
The code below is equivalent. I can see pros and cons for both versions. Which is better: the short, clever way, or the long, ctrl+c way?

Short version:

character.on("key",function(key){
    var action = ({
            "a":{axis:"x",direction:-1},
            "d":{axis:"x",direction:1},
            "w":{axis:"y",direction:1},
            "s":{axis:"y",direction:-1}})[key[1]],
        stop = key[0]=="-";
    if (action)
        if (stop)
            this.walkdir[action.axis] = 0;
        else
            this.walkdir[action.axis] = this.lookdir[action.axis] = action.direction;
});

Long version:

character.on("key",function(key){
    switch (key){
        case "+a":
            this.walkdir.x = -1;
            this.lookdir.x = -1;
        break;
        case "+d":
            this.walkdir.x = 1;
            this.lookdir.x = 1;
        break;
        case "+w":
            this.walkdir.y = 1;
            this.lookdir.y = 1;
        break;
        case "+s":
            this.walkdir.y = -1;
            this.lookdir.y = -1;
        break;
        case "-a":
            if (this.walkdir.x == -1)
                this.walkdir.x = 0;
        break;
        case "-d":
            if (this.walkdir.x == 1)
                this.walkdir.x = 0;
        break;
        case "-w":
            if (this.walkdir.y == 1)
                this.walkdir.y = 0;
        break;
        case "-s":
            if (this.walkdir.y == -1)
                this.walkdir.y = 0;
        break;
        case "space":
            this.setStance("jumping");
        break;
    };
});


texts:
Could this code be improved? Would you suggest more sophisticated way of doing client-side signup validation?

<!DOCTYPE html>

SignUp Form

<form name="registrationForm" onsubmit="return validateForm()" action="registration" method="post">
    Email:<input type="text" name="username"/>

    Password:<input type="password" name="password"/>

    Repeat Password:<input type="password" name="passwordAgain"/>

    <input type="submit" value="signup"/>
</form>


texts: Sychronous wrapper around UIApplication.openURL:options:completion:

texts:
I am deprecating iOS 9 on a project. One of the differences in the framework is that the openURL method has changed.

iOS 9

- (BOOL)openURL:(NSURL *)url;

iOS 10

- (void)openURL:(NSURL *)url
         options:(NSDictionary<NSString *,id> *)options
completionHandler:(void (^)(BOOL success))completion;

Notice how the method changed from being synchronous to asynchronous.

Since I have a bunch of usages for the synchronous method, I want to create a synchronous wrapper around the asynchronous openURL:options:completion: method and I'm going to update the usages to call this asynchronous wrapper instead.

My first attempt looks like this:

- (BOOL)sync_openURL: (nullable NSURL *)url {
    __block BOOL result = nil;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self openURL:url options:@{} completionHandler:^(BOOL success) {
        result = success;
        dispatch_semaphore_signal(semaphore);
    }];
    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    }
    return result;
}

Is this a good replacement ? Can it be improved in anyway ?


texts: iOS4 alternatives for dismissViewControllerAnimated:completion:

texts:
My inspiration for creating this protocol came from iOS 5's "dismissViewControllerAnimated:completion:" addition to UIViewController.  I wanted this functionality in iOS 4.3.
I find using the modal view's -viewDidDissapear to invoke methods on the presenting view controller work's very well.  One benefit is the ability to delay deallocation on the modal view controller.  Please post any improvements I can make.

PresentorDelegateProtocol.h

@protocol PresentorDelegateProtocol <NSObject>
@optional

/*

Extra protocol methods defined in protocol for flexibility.
Main methods are:
- (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated;
- (void)modalViewDissapeared:(id)modalView;  //used in modal view's -viewDidDissapear

*/

- (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated;
- (void)modalViewDissapeared:(id)modalView;

// use the block in this method send messages to save state, etc.  This is the one I like to use.
- (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated withBlock:(void(^)())block;

// use in other classes that are not controlling dismissal of the modal view
- (void)executeBlockOnModalDissapearance: (void(^)())block;

@end

PresentingViewController.h

#import "PresentorDelegateProtocol.h"
@interface PresentingViewController : UIViewController <PresentorDelegateProtocol>
- (void)showModalVC;
@end

ModalViewController.h

#import "PresentorDelegateProtocol.h"
@interface ModalViewController : UIViewController
@property (nonatomic, assign) id <PresentorDelegateProtocol> presentorDelegate;
- (void)close;
@end

PresentingViewController.m

#import "PresentingViewController.h"
#import "ModalViewController.h"
@implementation PresentingModalViewController
- (void)showModalVC
{
    ModalViewController *modalVC = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil];
    modalVC.presentorDelegate = self;
    [self presentModalViewController:modalVC animated:YES];
}
- (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated
{
    if ([modalView isKindOfClass:[ModalViewController class]]) {
        NSLog(@"Can invoke based on class");
    }
    [self dismissModalViewControllerAnimated:animated];
}
- (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated withBlock:(void(^)())block
{
    block();
    /* execute block before or after calling to dismiss modal view */
    [self dismissPresentingModalViewController:modalView animated:animated];
    //block();
}
- (void)modalViewDissapeared:(id)modalView
{
    if ([modalView isKindOfClass:[ModalViewController class]]) {
        NSLog(@"Do stuff based on class.");
    }
}
- (void)executeBlockOnModalDissapearance: (void(^)())block
{
    block();
    NSLog(@"This delay's dealloc on modal view until block completes");
}
@end

ModalViewController.m

#import "ModalViewController.h"
@implementation ModalViewController
@synthesize presentorDelegate;

- (void)close
{
    if (1 == 0 /*need to do something before dealloc*/){
        [self.presentorDelegate dismissPresentingModalViewController:self animated:YES withBlock:^{
            NSLog(@"Do stuff with block.  Save, animate, etc");
        }];

    } else {
        [self.presentorDelegate dismissPresentingModalViewController:self animated:YES];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    if (1 == 0 /*stuff to do*/){
        [self.presentorDelegate executeBlockOnModalDissapearance:^{
        // do stuff before modal view is deallocated
        }];
    }
    [self.presentorDelegate modalViewDissapeared:self];

    presentorDelegate = nil;
    [super viewDidDisappear:animated];
}
@end;


texts: Money class for handling calculations with coins

texts:
The code follows the requested format of the output exactly for my assignment. But, for my own personal reference, is there a better way that I could have done anything? Are there any additional tips? Maybe some simple ways that I could gold plate against exceptions or errors? I know how try, catch and throw exceptions work. My instructor doesn't check for it, though, so I wasn't going to spend time on it.

class Money {

public static void main(String[] args){

    //Variable and Constant Declaration
    int price,amountpaid,dollars,quarters,dimes,nickels,change,remainder = 0;

    Scanner sc = new Scanner(System.in);

    DecimalFormat df = new DecimalFormat("#0.00");

        //Input
        System.out.println("Please enter the purchase price in cents: ");
        price = sc.nextInt();

        System.out.println("Please enter the amount tendered in cents: ");
        amountpaid = sc.nextInt();

        //Calculations
        remainder = amountpaid - price;

        change = remainder;

        dollars = remainder / 100;
        remainder = remainder % 100;

        quarters = remainder / 25;
        remainder = remainder % 25;

        dimes = remainder / 10;
        remainder = remainder % 10;

        nickels = remainder / 5;
        remainder = remainder % 5;

        pennies = remainder;

        //Output
        System.out.println("Purchase Price:\t $" + df.format((double)price/100) +
                                "\nAmount Tendered: $" + df.format((double)amountpaid/100) +
                                "\n \nYour Change is:  $" + df.format((double)change/100) +
                                "\n \n \t \t " + dollars + " one-dollar bills(s)\n \t \t "
                                + quarters + " quarter(s)\n \t \t " + dimes +
                                " dime(s)\n \t \t " + nickels + " nickle(s)\n \t \t " +
                                remainder + " penn(y/ies)");
        System.out.println("\nThank you for your business. Come back soon.");

} // End Main
} //End Class


texts: Async Queue implementation without locking

texts:
I wrote a quick implementation of an async queue that utilizes a backing ConcurrentQueue. It was pretty much based on an implementation given in this Stack Overflow answer. The only difference is that I got rid of the internal locks that implementation uses.

Since a ConcurrentQueue is already thread safe, I can't figure out why they chose to use a lock in their implementation. Normally I would ask them on Stack Overflow but the question is 4 years old and I would rather post my implementation here and have someone do a peer review to see if I have a potential threading issue.

/// <summary>
///     Asynchronous Queue.
/// </summary>
/// <typeparam name="T">
///     The queue's elements' type.
/// </typeparam>
public sealed class AsyncQueue<T> {
    /// <summary>
    ///     Items.
    /// </summary>
    private readonly ConcurrentQueue<T> _items;

    /// <summary>
    ///     Promises.
    /// </summary>
    private readonly ConcurrentQueue<TaskCompletionSource<T>> _promises;

    /// <summary>
    ///     Create an Asynchronous Queue.
    /// </summary>
    public AsyncQueue() {
        this._items = new ConcurrentQueue<T>();
        this._promises = new ConcurrentQueue<TaskCompletionSource<T>>();
    }

    /// <summary>
    ///     Dequeue an Item Asynchronously.
    /// </summary>
    /// <returns>
    ///     A task representing the asynchronous operation.
    /// </returns>
    public Task<T> DequeueAsync() {
        var dequeueTask = this.DequeueAsync(CancellationToken.None);
        return dequeueTask;
    }

    /// <summary>
    ///     Dequeue an Item Asynchronously.
    /// </summary>
    /// <param name="cancellationToken">
    ///     A cancellation token to cancel the asynchronous operation with.
    /// </param>
    /// <returns>
    ///     A task representing the asynchronous operation.
    /// </returns>
    public async Task<T> DequeueAsync(CancellationToken cancellationToken) {
        CancellationTokenRegistration? cancellationTokenRegistration = null;
        var promise = new TaskCompletionSource<T>();
        var itemFound = this._items.TryDequeue(out var item);
        if (!itemFound) {
            cancellationTokenRegistration = cancellationToken.Register(OnCancellationTokenCanceled, promise);
            this._promises.Enqueue(promise);
        }
        else {
            promise.TrySetResult(item);
        }

        try {
            item = await promise.Task;
            return item;
        }
        finally {
            cancellationTokenRegistration?.Dispose();
        }

        // <summary>
        //      On Cancellation Token Canceled.
        // </summary>
        void OnCancellationTokenCanceled(object cState) {
            var cPromise = (TaskCompletionSource<T>) cState;
            cPromise.TrySetCanceled();
        }
    }

    /// <summary>
    ///     Enqueue an Item.
    /// </summary>
    /// <param name="item">
    ///     An item to enqueue.
    /// </param>
    public void Enqueue(T item) {
        while (true) {
            var promiseFound = this._promises.TryDequeue(out var promise);
            if (!promiseFound) {
                this._items.Enqueue(item);
                break;
            }

            var promiseSet = promise.TrySetResult(item);
            if (promiseSet) {
                break;
            }
        }
    }
}

I wrote unit tests and it seems to work fine. I think there might be a rare race condition that happens in the following scenario, but I have not been able to trigger it and I want a second opinion:

Thread 1 enqueues an item
Thread 1 does not find an existing promise
Thread 1 is preempted
Thread 2 attempts to dequeue an item
Thread 2 does not find an existing item
Thread 2 is preempted
Thread 1 enqueues item
Thread 2 creates and enqueues a promise
Idle time until another enqueue or dequeue operation occurs


texts:
This code works just fine as I get the correct output. However I want to make my code more simple. I want to avoid using the setPrev(Node n) method and would rather set the reference to the previous node in the Node(String s) constructor directly somehow. I mainly want to know if this is the 'right' way to implement a Doubly linked list though.

public class DoublyLinkedList {
    private Node current;
    private Node first;
    private Node traverse;
    private int count = 0;
    public DoublyLinkedList(String s)
    {
        first = new Node(s);
        current = first;
    }
    public void add(String s){
        current.next = new Node(s);
        current.next.setPrev(current);
        current = current.next;
    }
    public void traverseForward(){
        count++;
        if(count==1)
            traverse = first;
        else
            traverse = traverse.next;
        System.out.println(traverse.toString());
    }
    public void traverseBackward(){
        count--;
        if(count < 1)
            traverse = null;
        else if(count == 1)
            traverse = first;
        else
            traverse = traverse.prev;
        System.out.println(traverse.toString());
    }
    private class Node{
        private Node next;
        private Node prev;
        private String name;

        public Node(String s)
        {
            this.name = s;
            this.next = null;
        }
        public void setPrev(Node n){
            this.prev = n;
        }
        public String toString(){
            return this.name;
        }
    }
}


texts:
This function will run every x seconds.

PAN: The name we are calling our fixed width file we are transmitting.

Private Sub Start()

    ' Get the data from the API so we can get ready to make the PAN File
    Dim Baker As New PAN.Maker
    Baker.SetIngredients(GetAPIData)

    ' Make the PAN file
    Baker.Make()

    ' Retrieve the PAN file from the baker
    Dim PAN As PANv1 = Baker.GetPAN()

    ' Transmit the PAN file, via FTP
    Dim PANSender As New PAN.Transmitter(GetFTPDetails)
    PANSender.Send(PAN)

End Sub

I create the Objects Maker and Transmitter in a PAN namespace to group the functionality. Is this wise?
I decide to use a method to set the data it needs before it can create the PAN file, rather than using a constructor. What is the preferred method in this case?
Am I using too many Objects to handle these tasks, when a more procedural structure would do?
Is the naming of the Baker and Transmitter confusing because they differ from the Objects name?
Are these straightforward and easily understandable OOP practices?


texts: Is_prime check in Python: can this be more pythonic?

texts:
I have the following function that checks if a number is prime:

def is_prime(n):
    """ Is n prime? """

    if n < 2:
        return False
    if n in (2, 3):
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False

    limit   = int(math.sqrt(n))
    divisor = 5

    while divisor <= limit:
        if n % divisor == 0 or n % (divisor + 2) == 0:
            return False
        divisor += 6

    return True

Most of it are checks and calculations to save up time, to make it faster than a simple loop through a range.

Can it be written in a more pythonic way? Can it be improved in some way?

Any other feedback is welcome too.


texts:
Could you suggest any improvements in this Lucas sequence's implementation:

from mpmath.libmp import bitcount as _bitlength

def _int_tuple(*i):
    return tuple(int(_) for _ in i)

def _lucas_sequence(n, P, Q, k):
    """Return the modular Lucas sequence (U_k, V_k, Q_k).
    Given a Lucas sequence defined by P, Q, returns the kth values for
    U and V, along with Q^k, all modulo n.
    """
    D = P*P - 4*Q
    if n < 2:
        raise ValueError("n must be >= 2")
    if k < 0:
        raise ValueError("k must be >= 0")
    if D == 0:
        raise ValueError("D must not be zero")

    if k == 0:
        return _int_tuple(0, 2, Q)
    U = 1
    V = P
    Qk = Q
    b = _bitlength(k)
    if Q == 1:
        # For strong tests
        while b > 1:
            U = (U*V) % n
            V = (V*V - 2) % n
            b -= 1
            if (k >> (b - 1)) & 1:
                t = U*D
                U = U*P + V
                if U & 1:
                    U += n
                U >>= 1
                V = V*P + t
                if V & 1:
                    V += n
                V >>= 1
    elif P == 1 and Q == -1:
        # For Selfridge parameters
        while b > 1:
            U = (U*V) % n
            if Qk == 1:
                V = (V*V - 2) % n
            else:
                V = (V*V + 2) % n
                Qk = 1
            b -= 1
            if (k >> (b-1)) & 1:
                t = U*D
                U = U + V
                if U & 1:
                    U += n
                U >>= 1
                V = V + t
                if V & 1:
                    V += n
                V >>= 1
                Qk = -1
    else:
        # The general case with any P and Q
        while b > 1:
            U = (U*V) % n
            V = (V*V - 2*Qk) % n
            Qk *= Qk
            b -= 1
            if (k >> (b - 1)) & 1:
                t = U*D
                U = U*P + V
                if U & 1:
                    U += n
                U >>= 1
                V = V*P + t
                if V & 1:
                    V += n
                V >>= 1
                Qk *= Q
            Qk %= n
    U %= n
    V %= n
    return _int_tuple(U, V, Qk)


texts: After effects expression to prevent objects to lay on odd pixels when a Keyframe is applied

texts:
I made a scripted expression for after effects a while ago. This script is preventing objects to lay on odd pixels when a Keyframe is applied.

// Amount of Keyframes
n = transform.position.numKeys;

// Time
t = time;

// Time of Keyframe
timeOfKeyframe = null;

if ( n != 0 ){
     // Time of first Keyframe
     timeOfFirstFrame = transform.position.key(1).time;

     // Time of last Keyframe
     timeOfLastFrame = transform.position.key(n).time;
}
else{
     timeOfFirstFrame = null;
     timeOfLastFrame = null;
}

if ( n == 0 || t < timeOfFirstFrame || t > timeOfLastFrame ){
     posX = Math.round(transform.position[0]);
     posY = Math.round(transform.position[1]);
     posZ = Math.round(transform.position[2]);

     [posX,posY,posZ];
}
else{
     for(i=1; i <= n; i++){
          if ( t == transform.position.key(i).time ){
               timeOfKeyframe = transform.position.key(i).time;
          }
          else{
               value;
          }
     }

     if (t == timeOfKeyframe) {
          keyValue = transform.position.valueAtTime(timeOfKeyframe);
          roundedValue = [Math.round(keyValue[0]),Math.round(keyValue[1]),Math.round(keyValue[2])];
     }
     else{
          value;
     }
}

It's working for three dimensional objects. Since I am actually not a real programmer I wanted to know if there is any better way to achieve this. It seems to be a very long expression.


texts:
I am building an iOS SDK to be consumed by apps. I am building an object that represents a physical place. The interface looks like so:

@interface RDPlace : NSObject

@property (nonatomic, strong, readonly) NSString *city;

@property (nonatomic, strong, readonly) NSString *country;

@property (nonatomic, strong, readonly) NSString *address;

@property (nonatomic, strong, readonly) NSString *zip;

@end

This is all working fine, but now I am attempting to make this work outside of the US. I found out that some places (Hong Kong was the one that prompted this discovery) don't have a zip code. I'm wondering what the best value to put in this SDK is. I believe I have 3 options:

RDPlaces with no zip have the property set to nil
RDPlaces with no zip have the property set to NSNull
RDPlaces with no zip have the property set to @"" (empty string)

What is the most friendly for consumers of this object, and how would one annotate this for swift?


texts:
Important fact: the number of the input is greater than 1.  How do I use this fact to speed up this solution?

public class subSetSumR{
// Solving Subset sum using recursion

public static boolean subSetSumRecur(int [] mySet, int n, int goal){
   if (goal ==0){
         return true;}
   if ((goal<0)|(n>=mySet.length))
      return false;
   if (subSetSumRecur(mySet,n+1,goal - mySet[n])){
      System.out.print(mySet[n]+" ");
      return true;}
   if (subSetSumRecur(mySet,n+1,goal))
      return true;
   return false;
}


texts:
In Python I am trying to create an API for a connected device. I want to be available for both threaded (using request) and async applications (using aiohttp).
What I've come up with is wrapping the get method of both requests and aiohttp in a decorator. This decorator is passed at init and API calls are explicitly wrapped using the passed decorator.

It works, but I'd like to know how others think of this approach ? Are there better ways or will I be running into issues later on ?

def threaded_gett(function):
    # The threaded decorator
    def wrapper(*args, **kwargs):
        url, params = function(*args)
        response = requests.get(url, params)
        _json = response.json()
        return function.__self__.process_response(_json)

    return wrapper

def async_gett(function):
    # The async decorator
    def wrapper(*args, **kwargs):
        url, params = function(*args)
        try:
            resp = yield from function.__self__.session.get(url, params=params)
        except Exception as ex:
            lgr.exception(ex)
        else:
            _json = yield from resp.json()
            yield from resp.release()
            return function.__self__.process_response(_json)

    # wrapping the decorator in the async coroutine decorator.
    wrapper = asyncio.coroutine(wrapper)
    return wrapper

class ThreadedApi(BaseApi):
    def __init__(self,threaded_gett):
        BaseApi.__init__(self,threaded_gett)

class AsyncApi(BaseApi):
    def __init__(self,async_gett):
        BaseApi.__init__(self,async_gett)

class BaseApi():
    def __init__(self,get_wrapper):
        self.status = get_wrapper(self.status)

    def status(self):
        return <status path>


texts:
I'm new to PDO, so I was wondering if you guys could check over my PDO code for efficiency (and if the PHP can be improved)

public function ValidateUser($username = '', $password = '')
{
    $prefix = "SELECT ";
    $type = 'COUNT(id)';
    $suffix = " FROM users WHERE username = :username LIMIT 1";
    if($grabUser = $this->db->prepare($prefix.$type.$suffix))
    {
        $grabUser->bindParam(":username", $username, PDO::PARAM_STR);
        $grabUser->execute();
        if(count($grabUser->fetchColumn()) <= 0)
        {
            return array(0,0);
        }
    }
    else {
        return array(0,0);
    }

    $type = 'salt';
    if($grabUser = $this->db->prepare($prefix.$type.$suffix))
    {
        $grabUser->bindParam(":username", $username, PDO::PARAM_STR);
        $grabUser->execute();
        $salt = $grabUser->fetch()['salt'];
        $password = $this->core->blueHash($password, $salt);
    }
    else {
        return array(0,0);
    }

    $stmt = "SELECT COUNT(id) FROM users WHERE username = :username AND password = :password LIMIT 1";
    if($checkFinal = $this->db->prepare($stmt))
    {
        $checkFinal->bindParam(":username", $username, PDO::PARAM_STR);
        $checkFinal->bindParam(":password", $password, PDO::PARAM_STR);
        $checkFinal->execute();
        if(!count($checkFinal->fetchColumn()) > 0)
        {
            return array(0,0);
        }
        return array(count($checkFinal->fetchColumn()),$password);
    }
    return array(0,0);
}

This code checks that the supplied username and password are correct and if so, an array is returned.

EDIT: AJAX file where ValidateUser() is used:

<?php
require_once "../../_global.php";
$core->ajaxCheck();

header("Content-Type: application/json");
$json = array();

if(USER_ID <= 0 && !LOGGED_IN)
{
    // DO ISSET CHECK :((
    $username = $core->input($_POST['name']);
    $password = $core->input($_POST['pword']);

    $valid = $users->ValidateUser($username, $password);
    if($valid[0] == 0)
    {
        $json[0] = "error";
        $json[1] = "ajax";
        $json[2] = "These details are incorrect.";
    }
    elseif($valid[0] > 0)
    {
        $_SESSION['login']['username'] = $users->GrabUserVar($users->Name2id($username),"username");
        $_SESSION['login']['hash'] = $valid[1];
        $_SESSION['login']['social'] = false;
        $json[0] = "success";
    }
}
else {
    $json[0] = "error";
    $json[1] = "ajax";
    $json[2] = "You are already signed in.";
}
echo json_encode($json);
exit;
?>

EDIT2: Code that is run on each page to check whether the session username and password hash match that of the database:

session_start();
if(isset($_SESSION['login']['username']) && isset($_SESSION['login']['hash']))
{
    $userN = $_SESSION['login']['username'];
    $userH = $_SESSION['login']['hash'];
    if($users->CheckUser($userN, $userH) > 0)
    {
        define('LOGGED_IN',true);
        define('USER_ID',$users->Name2id($userN));
        $cUser = $users->createIndividual(USER_ID);
        define('USER_NAME',$cUser->getUsername());
        define('USER_HASH',$userH);
    }
    else {
        define('LOGGED_IN',false);
        define('USER_ID',0);
        define('USER_NAME','Guest');
        define('USER_HASH',0);
        session_destroy();
    }
}
else {
    define('LOGGED_IN',false);
    define('USER_ID',0);
    define('USER_NAME','Guest');
    define('USER_HASH',0);
}


texts:
Please help me optimize this bubble sort code. It's working fine otherwise.

int[] randomIntegers = {2,3,1,1,4,5,8,-2,0};

for(int i=0;i<randomIntegers.length;i++){
  for(int j=i;j<(randomIntegers.length-1);j++){
    if(randomIntegers[i]>randomIntegers[j+1]){
      randomIntegers[i] += randomIntegers[j+1];
      randomIntegers[j+1] = randomIntegers[i] - randomIntegers[j+1];
      randomIntegers[i] = randomIntegers[i] - randomIntegers[j+1];
    }
  }
}
for(int i:randomIntegers){
  System.out.print(i+",");
}


texts: Counting unordered factorizations with distinct parts

texts:
Trying to solve this combinatorics problem, I wrote some functions to count the number of unordered distinct factorizations of an integer n into k distinct parts.

The following function builds up a list of unordered distinct factorizations of n with largest part at most m.

duf' :: Integer -> Integer -> [[Integer]]
duf' m 1 = [[]]
duf' 1 n = []
duf' 0 n = []
duf' m n | isPrime n = if m < n then [] else [[n]]
         | otherwise = concatMap (\x -> map (\y -> x : y) $
             duf' (x-1) (n `div` x) ) $ tail $
             takeWhile (<= m) $ toList $ divisors n

It is then used below to generate the list of all unordered distinct factorizations of n.

duf :: Integer -> [[Integer]]
duf n = duf' n n

To count the number of factorizations of k parts only I use a simple (and inefficient ?) filter.

pd n k = length . filter (\x -> k == length x) $ duf n

As a beginner, I have the feeling this is not really Haskell-ish. Any help to improve the syntax is welcome !

My concern is that I would like to avoid filtering and (if possible) to count without generating an enormous list. Is there a way to "merge" pd and duf' ? Or at least optimizing the thing ?

I use this two external functions : Math.NumberTheory.Primes.Factorisation.divisors and Data.Numbers.Primes.isPrime. Are there better choices ?


texts: What is the best to select a javascript object property at any depth?

texts:
I'm looking for suggestions on how to select properties on the child level or deeper dynamically.

For example, here is the method that I am currently using. The method parameters is the object and either a string or array for the property name. If a string is passed used, it will just will get the property.  The array is iterated through in order to select the property value.

getMappedDataProperty: function(obj, map) {
  var m, result, _i, _len;
  if (typeof map === 'string') {
    return obj[map];
  }
  result = obj;
  for (_i = 0, _len = map.length; _i < _len; _i++) {
    m = map[_i];
    result = result[m];
  }
  return result;
}

Even though this works, I keep thinking to myself that there has to be a better way of accomplishing this.  Suggestions?


texts:
I present to you... my battleship location picker! This will be part of a larger battleship program. The coordinates that are important are finalcoords.

from operator import itemgetter
import getch
import skilstak.colors as c #colors
BOARDLENGTH = 10
BOARDHEIGHT = 10
board = [['_'] * BOARDLENGTH for _ in range(BOARDHEIGHT)]
class Ship():
    def __init__(self, size, symbol):
        self.size = size
        self.symbol = symbol
        self.coords = [(x,0) for x in range(size)]
        self.previous_coords = [(None,None) for _ in range(size)]
    def shift(self,direction):

        x_values = list(map(itemgetter(0), self.coords))
        y_values = list(map(itemgetter(1), self.coords))
        if direction == 'R' and 0 not in x_values:
            change = (-1,0)
        elif direction == 'D' and BOARDHEIGHT-1 not in y_values:
            change = (0,1)
        elif direction == 'U' and 0 not in y_values:
            change = (0,-1)
        elif direction == 'L' and BOARDLENGTH-1 not in x_values:
            change = (1,0)
        else:
            change = (0,0)
        for i, coord in enumerate(self.coords):
            self.previous_coords[i] = self.coords[i]
            self.coords[i] = (coord[0] + change[0], coord[1] + change[1])

    def rotate(self):
        a, b = self.coords[0][0], self.coords[0][1]
        x, y = self.coords[-1][0], self.coords[-1][1]
        newx, newy = -(y-b)+a, (x-a)+b
        if newy >= 0 and newx >= 0 and newy <= BOARDHEIGHT-1 and newx <= BOARDLENGTH-1:
            for i, coord in enumerate(self.coords):
                self.previous_coords[i] = self.coords[i]
                self.coords[i] = (-(self.coords[i][1]-b)+a, (self.coords[i][0]-a)+b)

    def show(self, board, hasprevious=True):
        if hasprevious:
            for pcoord in self.previous_coords:
                board[pcoord[1]][pcoord[0]] = '_'
        for coord in self.coords:
            board[coord[1]][coord[0]] = self.symbol
        display_board = '\n'.join(' '.join(line) for line in board)
        print(c.clear + display_board) #c.clear clears the screen
        return board
def hide(board,coords):
    for coord in coords:
        board[coord[1]][coord[0]] = '_'
    return board

def choose_locations(board):
    ships = [Ship(5,'A'),Ship(4,'B'),Ship(3,'c'),Ship(3,'C'),Ship(2,'D')]
    finalcoords = []
    for ship in ships:
        board = ship.show(board,hasprevious=False)
        while True:
            key = getch.getch()
            if key == 'w':
                ship.shift('U')
                board = ship.show(board)
            elif key == 's':
                ship.shift('D')
                board = ship.show(board)
            elif key == 'a':
                ship.shift('R')
                board = ship.show(board)
            elif key == 'd':
                ship.shift('L')
                board = ship.show(board)
            elif key == 'r':
                ship.rotate()
                board = ship.show(board)
            elif key == 'q':
                exit()
            elif key == '\r':
                intersection = list(set(ship.coords).intersection(finalcoords))
                if intersection == []:
                    finalcoords += ship.coords
                    board = hide(board,ship.coords)
                    break
                else:
                    print('''You already have a ship or part of a ship there.Your current coordinates are {}
You have placed a ship on these coords, {}.
You overlapped on these coords: {}'''.format(ship.coords,finalcoords,intersection))
            else:
                print('press w,a,s or d to move, and r to rotate. Press q to quit.')
    return finalcoords
if __name__ == '__main__':
    coords = choose_locations(board)


texts:
RetrieveData is a 3rd party API that takes 3 parameters: a buffer, number of bytes to retrieve, and actual bytes required for the buffer.

The buffer returned is a non-null terminated unicode string
99% of the time, the buffer is less than 256 bytes, but may be larger and needs to handle this scenario
RetrieveData(data) is guaranteed to return
The reason for using std::map is the ID must later be retrieved based on a string

std:map<std::wstring, unsigned int> map_columns;
unsigned int id;
unsigned long pcbActual;
char* data;

do
{
    RetrieveID(&id);
    // find out how large buffer we need to retrieve data
    RetrieveData(NULL, 0, &pcbActual);
    data = new char[pcbActual + 2];
    // actually retrieve data
    RetrieveData(data, pcbActual, &pcbActual);
    data[pcbActual] = '\0';
    data[pcbActual + 1] = '\0';
    std::wstring str((wchar_t*)data);
    map_columns[str] = id;
} while (MoveNext());


texts: Converting a List of arcs into Adjacency list representation for graph using dictionary

texts:
I was reading up on implementing Graphs in Python and I came across this Essay at python.org about graphs, so I decided to implement it, but with weighted edges.

I start with arcs and their cost using list of lists and then iterate through it building a dictionary (Adjacency list format) that represents the Undirected Weighted Graph. I am looking for suggestions on how to improve the following code. Here I need to check every time if a vertex already exists in the dictionary using an if x in dict.keys() statement, which takes linear time for each node.

data=[['A','B',5],
  ['A','C',4],
  ['B','C',2],
  ['B','D',3],
  ['C','D',10],
  ['E','F',1],['F','C',6]]

graph={}

for row in data:
    if row[0] in graph.keys():
        graph[row[0]][row[1]]=row[2]
        if row[1] not in graph.keys():
            graph[row[1]]={}
            graph[row[1]][row[0]]=row[2]
        else:
            graph[row[1]][row[0]]=row[2]

    else:
        graph[row[0]]={}
        graph[row[0]][row[1]]=row[2]
        if row[1] not in graph.keys():
            graph[row[1]]={}
            graph[row[1]][row[0]]=row[2]
        else:
            graph[row[1]][row[0]]=row[2]

print graph

The output of the above code is:

>>{'A': {'C': 4, 'B': 5},
   'C': {'A': 4, 'B': 2, 'D': 10, 'F': 6},
   'B': {'A': 5, 'C': 2, 'D': 3},
   'E': {'F': 1},
   'D': {'C': 10, 'B': 3},
   'F': {'C': 6, 'E': 1}}


texts: Lists' intersection keeping elements' order

texts:
I could use the function Intersection, but it returns a sorted list. That's why I have to do my own, but it looks too big. I hope it could be done shorter.

lists = {{1, 2, 3, 4, 5}, {1, 2, 3, 4}, {2, 3, 4, 5}};
Fold[ Function[ {a, b},
  Select[b, MemberQ[a, #] &]
  ], lists // First, lists // Rest]


texts:
Information about my code:

I am following this MIT OCW algorithms course. The first lecture described insertion sort and merge sort. I implemented merge sort in C.

The algorithm is structured as a function called from the main function. The array to be sorted is allocated dynamically in the main function but can also be statically allocated.

What I am looking for:

I am looking whether the 2 functions can be optimized without changing the algorithm(merge sort), whether it follows the best-practices of programming in C and does it have proper readability factor?

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

#define SORTING_ALGO_CALL merge_sort

void merge_parts(int arr[], int length)
{
    /*
    Sorts into increasing order
    For decreasing order change the comparison in for-loop
    */
    int ans[length];
    //This for and next if-else puts the merged array into temporary array ans
    //in a sorted manner
    int i, k;
    int temp, j = temp = length/2;
    for (i = k = 0; (i < temp && j < length); k++){
        ans[k] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];
    }

    if(i >= temp){
        while(j < length){
            ans[k++] = arr[j++];
        }
    }
    else{
        while(i < temp){
            ans[k++] = arr[i++];
        }
    }

    //This for-loop puts array ans into original array arr
    for(i = 0; i < length; i++){
        arr[i] = ans[i];
    }
}

void merge_sort(int arr[], int length)
{
    if(length > 1)
    {
        merge_sort(&arr[0], (length/2));
        merge_sort(&arr[length/2], (length - length/2));
        merge_parts(arr, length);
    }
}

int main()
{
    int length;
    scanf("%d", &length);
    while (length < 1)
    {
        printf("\nYou entered length = %d\n", length);
        printf("\nEnter a positive length: ");
        scanf("%d", &length);
    }

    int *arr;
    if ((arr = malloc(sizeof(int) * length)) == NULL)
    {
        perror("The following error occurred");
        exit(-1);
    }

    for (int i = 0; i < length; i++){
        scanf("%d", &arr[i]);
    }

    SORTING_ALGO_CALL(arr, length);

    for (int i = 0; i < length; i++){
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}

The book I am reading is Introduction to Algorithms 3rd Edition by Cormen. It mentions a sentinel value be placed at the end of two subarrays. That, if implemented, it can result in better efficiency. But I am not sure what to use as a sentinel value.


texts:
So i am developing an Android application as a side project/hobby and I have come across the situation that I have to pass an Activity into a method for use a context (Don't question it)

The problem here is that I have to pass it into a PreferenceOnClickListener and so I am unable to use this. I have come up with the following code snippet, that you all might just wanna stab me for writing... Sorry, I feel bad for creating this as well:

Preference rebuildDB = pf.findPreference(getString(R.string.preference_rebuildDatabase));
    Activity thisContext = this;
    rebuildDB.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            SongLoader.generateXml(thisContext);
            return true;
        }
    });

The thing I don't like is setting thisContext to the value of this, so my question is the following:

Is this really as bad as I think it is, and is there any better way to achive it?


texts:
I am creating an application that will move specific data from one Oracle database and moving it to a MySQL database. I created this class to help keep myself organized and this class holds all of the operations/communication that will happen with this database. I have learned C# on my own with no formal training I was just wanting some pointers that could help me make my code to be acceptable if I was working as a developer for a company.

class Oracle
{
    //private properties
    private OracleConnection oConnection;
    private XmlDocument oXML;
    private string oUID;
    private string oPassword;
    private string oSecurity;
    private string oDb;
    private string oConString;
    private OracleDataAdapter oCommand;
    private string oScript;
    private DataSet oData;
    private DataTable oTable;
    public Oracle()
    {
        oConnection = new OracleConnection();
        oXML = new XmlDocument();
        try
        {

            oXML.Load(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\Test.xml");
            oSecurity = oXML.SelectSingleNode("/Connections/Oracle/Security").InnerText;
            oDb = oXML.SelectSingleNode("/Connections/Oracle/Database").InnerText;
            oUID = oXML.SelectSingleNode("/Connections/Oracle/UId").InnerText;
            oPassword = Encrypt.DecryptString(oXML.SelectSingleNode("/Connections/Oracle/Pwd").InnerText,oUID);
            oConString = "Data Source=" + oDb + ";User Id=" + oUID + ";Password=" + oPassword + ";";
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles opening the connection to the  database
    public void Open()
    {
        try
        {
            oConnection.ConnectionString = oConString;
            oConnection.Open();
            Console.WriteLine("Oracle DB Connection Established");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles closing the connection to the database
    public void Close()
    {
        try
        {
            oConnection.Close();
            Console.WriteLine("Oracle DB Connection Closed");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles pulling the data from a table
    public DataTable Pull()
    {
        oCommand = new OracleDataAdapter();
        oData = new DataSet();
        oTable = new DataTable();
        try
        {
            oScript = System.IO.File.ReadAllText(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\CASE_SELECT.sql");
            oCommand.SelectCommand = new OracleCommand(oScript, oConnection);
            oCommand.Fill(oData, "uds9");
            oTable = oData.Tables["uds9"];
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
        return oTable;
    }
}


texts:
I am using Dr.Racket, Intermediate Student with Lambda. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.

 ; DRAWING FUNCTIONS

 ; draw-rocket: rocket scene --> scene
 ; Purpose: To draw the given rocket in the given scene
 (define (draw-rocket a-rocket a-scene)
 (place-image rocket-img a-rocket ROCKET-Y a-scene))

 ; draw-alien: alien scene --> scene
 ; Purpose: To draw the given alien in the given scene
 (define (draw-alien an-alien a-scene)
 (place-image alien-img
   (posn-x an-alien)
   (posn-y an-alien)
   a-scene))

    ; draw-aliens: loa scn --> scene
    ; Purpose: To draw the aliens in the given scene
    (define (draw-aliens a-loa scn)
    (cond [(empty? a-loa) scn]
    [else (draw-alien (first a-loa) (draw-aliens (rest a-loa) scn)
                  )]))
;

; draw-shot: shot scene --> scene
; Purpose: To draw the given shot in the given scene
(define (draw-shot a-shot scn)
(place-image SHOT-IMG (posn-x a-shot) (posn-y a-shot) scn))

; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-shots a-los scn)
(cond [(empty? a-los) scn]
[else (draw-shot (first a-los) (draw-shots (rest a-los) scn)
             )]))

; draw-world: world --> scene
; Purpose: Draw the world in the empty scene
(define (draw-world a-world)
(draw-rocket (world-rocket a-world)
(draw-aliens (world-aliens a-world)


texts:
The application uses NCalc to execute diverse calculations.

The 'natural' way to write powers using a computer is using the ^ symbol. However, NCalc already uses it as bitwise or.

I use the following function to parse calculations and convert it to the Pow(a,b) format.

    Private Function _replacePower(Str As String) As String
        Const PowerString As String = "Pow({0},{1})"

        Dim i, j As Integer
        Dim c As String
        Dim before, after, all As String

        Dim other_p As Integer 'Keep track of other opening/closing parenthesis, to avoid breaking for a nested one.

        other_p = -1
        i = 1
        While i <= Len(Str)
            c = Mid(Str, i, 1)
            If c = "^" Then
                If Mid(Str, i - 1, 1) = ")" Then
                    j = i - 1
                    Do While Mid(Str, j, 1) <> "(" Or other_p > 0
                        If Mid(Str, j, 1) = ")" Then other_p = other_p + 1
                        If Mid(Str, j, 1) = "(" Then other_p = other_p - 1
                        j = j - 1
                    Loop
                    before = Mid(Str, j, i - j)
                Else
                    j = i - 1
                    'The expression to be raised is everything between the power and + - * / , ( <- Opening parenthesis is not ok if there is no closing one, and this case is handled above.
                    Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> "(")
                        j = j - 1
                        If j = 0 Then Exit Do
                    Loop
                    before = Mid(Str, j + 1, i - j - 1)
                End If

                other_p = -1

                If Mid(Str, i + 1, 1) = "(" Or other_p > 0 Then
                    j = i + 1
                    Do While Mid(Str, j, 1) <> ")"
                        If Mid(Str, j, 1) = ")" Then other_p = other_p - 1
                        If Mid(Str, j, 1) = "(" Then other_p = other_p + 1
                        j = j + 1
                    Loop
                    after = Mid(Str, i + 1, j - i)
                Else
                    j = i + 1
                    Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> ")")
                        j = j + 1
                        If j = Len(Str) + 1 Then Exit Do
                    Loop
                    after = Mid(Str, i + 1, j - i - 1)
                End If

                all = before & "^" & after
                Str = Replace(Str, all, String.Format(PowerString, before, after))
                i = 1
            End If
            i = i + 1
        End While
        Return Str
    End Function

My issues lies with performance, as it appears that this function is the bottleneck of the entire application. How could I improve?


texts: Bash script that checks for package dependencies and installs them if necessary

texts:
I'm new to writing bash scripts and was wondering if I could get someone's advice on a part of the script I'm working on.

Intended purpose of code

Check if a package exists using dpkg, and if it doesn't, offer to install it for the user. This snippet is part of a larger script that installs a particular Conky configuration along with all of its dependencies with minimal effort from the user.

Concerns

I feel as though there is a more elegant way to check if a package is installed using dpkg (code was found on Stack Overflow).
Is there a better way of handling the (y/n) response?

Here is the code that I am using:

declare -a packages=("conky-all" "lm-sensors");

for i in "${packages[@]}"; do
    if [ $(dpkg-query -W -f='${Status}' $i 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
        echo "$i is not installed, would you like to install it now? (Y/N)";
        read response
        if [ "$response" == "y" ] || [ "$response" == "Y" ]; then
            sudo apt-get install "$i";
        else
            echo "Skipping the installation of $i...";
            echo "Please note that this Conky configuration will not work without the $i package.";
        fi
    else
        echo "The $i package has already been installed.";
    fi
done


texts:
From my C university book 'The C Programming Language' by Brain W.Kernighan and Dennis M.Ritchie. Excercise 1 - 20.

  Write a program detab that replaces tabs in the input with the proper number of
      blanks to space to the next tab stop.
  Assume a fixed set of tab stops, say every
      n columns. Should n be a variable or a symbolic parameter?

#include <stdio.h>

#define TABSTOP 8
#define MAXLINE 1000

int getline(char s[], int len);

int main()
{
    char line[MAXLINE];

    while ((getline(line, MAXLINE) > 0))
    {
        int i, j, count;

        count = 0;
        for (i = 0; line[i] != '\0'; ++i)
        {
            if (line[i] == '\t')
            {
                for (j = 0; j < TABSTOP - count; ++j)
                {
                    putchar(' ');
                }

                count = 0;
            }
            else
            {
                ++count;

                if (count >= TABSTOP)
                    count = 0;

                putchar(line[i]);
            }
        }
    }

    system("pause");

    return 0;
}

int getline(char line[], int len)
{
    int c, i;

    for (i = 0; i < len - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        line[i] = c;

    if (c == '\n')
    {
        line[i] = c;
        ++i;
    }

    line[i] = '\0';

    return i;
}

My concerns are that I didn't get the question right, did they mean that every time I see a tab in the input I need to put the corresponding amount of spaces instead of tabs?

Are there any flaws or bugs in the code?

I didn't understood what is a 'symbolic parameter', did they mean symbolic constant?

By 'n' did they mean what I did with the 'TABSTOP' symbolic constant?


texts:
I'm working on the problem of print a linked list reversely without destruction. I'm wondering if any other better ideas, in terms of both time complexity improvement and space complexity improvement. I also welcome for code bugs and code style advice.

class LinkedListNode:
    def __init__(self, value, nextNode):
        self.value = value
        self.nextNode = nextNode
    def print_reverse(self):
        if not self.nextNode:
            print self.value
            return
        else:
            self.nextNode.print_reverse()
            print self.value
if __name__ == "__main__":
    head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
    head.print_reverse()


texts: How can I refactor to avoid repetition finding the index of strings in a list?

texts:
I have a list of strings where I want to find the index of a first- and second-choice video compressor.

Logic: If the first choice is available, return its index. If not, and the second choice is available, return its index. If not, return zero.

Here is what I have now:

List<string> availableVideoCompressors = GetAvailableVideoCompressors();
int compressorIndexToUse = 0;
if (availableVideoCompressors.Any(c => c.StartsWith("ffdshow", StringComparison.OrdinalIgnoreCase)))
    compressorIndexToUse = availableVideoCompressors.Select((c, i) => new { c, i }).First(c => c.c.Equals("ffdshow", StringComparison.OrdinalIgnoreCase)).i;
else if (availableVideoCompressors.Any(c => c.StartsWith("Microsoft Video 1", StringComparison.OrdinalIgnoreCase)))
    compressorIndexToUse = availableVideoCompressors.Select((c, i) => new {c, i}).First(c => c.c.StartsWith("Microsoft Video 1", StringComparison.OrdinalIgnoreCase)).i;
return compressorIndexToUse;

The problem is that I am iterating the list several times. Once to determine if the desired compressor is available, then again to obtain its index, for each candidate compressor.

I am not sure how to refactor to avoid this repetition. What can I do instead?


texts:
I have some questions on how I can improve this "add action" (method) in "controller":

I'm using the add action only if post request. Is it correct?
This action doesn't have views ($this->autoRender = false;). Is it correct?
I set a response .json file to this action but I didn't change on routes to routing .json files (the file will be return when access localhost:8765/users/add). Is it correct?
I'm using Enums(handmade) to store messages that will returned to user. Is it correct?
I'm using an object to store the fields of message (that will returned to user), that object will be serialized and returned like this:

$this->response->body(json_encode($response));

Is it correct?

Controller code:

public function login()
{
    $this->autoRender = false;
    $this->response->type('json');
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            $response = new ResponseMessage();
            $response->code = CodeEnum::LOGIN_GRANTED;
            $response->name = NameEnum::LOGIN_GRANTED;
            $response->type = TypeMessageEnum::SUCCESS;
            $this->response->body(json_encode($response));
        }else {
            $response = new ResponseMessage();
            $response->code = CodeEnum::LOGIN_DENIED;
            $response->name = NameEnum::LOGIN_DENIED;
            $response->message = MessageEnum::USER_PASS_INCORRECT;
            $response->type = TypeMessageEnum::ERROR;
            $this->response->body(json_encode($response));
        }
    }
}


texts: Making multiple calls to API and processing data in Node.JS

texts:
I have written a chunk of Node that is acting as a web hook for a GitHub repository I have.  Basically when a commit is made to that repo, a request gets made to my function which then looks for potentially sensitive data that has been checked in.  I'm making multiple calls to the GitHub API to pull down data.  I tried to handle all of these calls by using the async package's waterfall and each functions.

There are two sections to the waterfall call: getting the commit data and then getting the file data.  Within the "file data" section I have the async each that is getting the actual file contents for each file.

I'm wondering if anyone can see any obvious best practices that I am not following for JavaScript programming.  Am I handling the asynchronous calls the correct way?  I created two helper functions to try and keep things clean/readable - should I break any other pieces out into their own functions?

var https = require('https')
var async = require('async')

module.exports = function (ctx,cb) {
  console.log("**********************************************")
  var danger = ['password','pass','pw','pwd','passwd','key','user','username','secret']
  var re = new RegExp(danger.join('|'))
  async.waterfall([
      function(callback){
        var options = {
          host: 'api.github.com',
          path: getApiPath(ctx.data.head_commit.url),
          headers: {
            'User-Agent': 'Broham'
          }
        }
        getData(options, function(commitData){
          // console.log("commit data", commitData)
          callback(null,commitData.files)
        })
      },
      //for each file, get the file content and look for potentially sensitive information that has been commited
      function(files, callback){
        // console.log("files", files)
        var review = []
        async.each(files, function(file, fileCallback){
          var fileOptions = {
            host: 'api.github.com',
            path: file.contents_url.replace('https://api.github.com', ''),
            headers: {
              'User-Agent': 'Broham'
            }
          }
          // get the JSON that will have the URL for the raw file content
          getData(fileOptions, function(fileData){
            // get the raw file content
            https.get(fileData.download_url, function(contentData){
                contentData.setEncoding('utf-8')
                var contents = ''
                contentData.on('data', function (data) {
                  contents += data
                })
                contentData.on('end', function(){
                  console.log('contents', contents)
                  // check to see if there are any matches for the terms we want to review.
                  matches = contents.match(re)
                  if(matches.length > 0){
                    // console.log("matches", matches)
                    review = review.concat(contents.match(re))
                  }
                  fileCallback()
                })
              })
          })
        }, function(err){
          callback(null, review)
        })

      }
    ], function(err, results){
        if(results.length > 0){
          console.log("For review:", results)
        }
        cb(null, 'GitEye complete!')
        console.log("**********************************************")
  })
}

function getData(options, callback){
  https.get(options, function(res){
    res.setEncoding('utf-8')
    var body = ''
    res.on('data', function (data) {
      body += data
    })

    res.on('end', function(){
      // console.log('body', body)
      var data = JSON.parse(body);
      callback(data)
    })
  })
}

function getApiPath(url){
  var pieces = url.split('/')
  var user = pieces[3]
  var repo = pieces[4]
  var commit = pieces[6]
  // return "https://api.github.com/repos/" + user + "/" + repo + "/commits/" + commit
  return "/repos/" + user + "/" + repo + "/commits/" + commit
}


texts:
I implemented the lightweight cipher Twine described
here but it seems to me that this is not sufficiently optimized.
For example, below I have the key expansion for 80 bits:

    private void expand80Key(byte[] key)
{

    short len_x = 20;
    short key_size = 10;
    short iterator = 0,iterator2=0;;
    byte temp_val=-1;
    byte temp_val2=-1,temp_val3=-1,temp_val4=-1;
    short sh=0;
    // reset the array
    Util.arrayFillNonAtomic(temp, (short)0, (short)20, UNTOUCHED_VALUE);

    for (iterator = 0 ; iterator < key_size; iterator++)
    {
        //key[iterator] = (byte)(key[iterator] & 0xff);
        temp[(short)(2*iterator)] = (byte)((short) (key[iterator] & 0x00FF) >> 4);
        temp[(short)(2*iterator+1)] = (byte)((short) (key[iterator] & 0x00FF) & 0x0F);
    }

    for ( iterator = 0 ; iterator < 35;iterator ++)
    {
        rk[(short)(iterator * 8 + 0)] = temp[1];
        rk[(short)(iterator * 8 + 1)] = temp[3];
        rk[(short)(iterator * 8 + 2)] = temp[4];
        rk[(short)(iterator * 8 + 3)] = temp[6];
        rk[(short)(iterator * 8 + 4)] = temp[13];
        rk[(short)(iterator * 8 + 5)] = temp[14];
        rk[(short)(iterator * 8 + 6)] = temp[15];
        rk[(short)(iterator * 8 + 7)] = temp[16];

        temp[1] ^= sbox[temp[0]];
        temp[4] ^= sbox[temp[16]];
        temp_val = roundconst[iterator];
        temp[7] ^= temp_val >> 3;
        temp[19] ^= temp_val & 7;

        temp_val = temp[0];
        temp_val2 = temp[1];
        temp_val3= temp[2];
        temp_val4 = temp[3];

        for (iterator2 = 0 ; iterator2 < 4;iterator2++)
        {
            sh = (short)(iterator2*4);
            temp[sh]   = temp[(short)(sh+4)];
            temp[(short)(sh+1)] = temp[(short)(sh+5)];
            temp[(short)(sh+2)] = temp[(short)(sh+6)];
            temp[(short)(sh+3)] = temp[(short)(sh+7)];
        }
        temp[16]   = temp_val2;
        temp[17]   = temp_val3;
        temp[18]   = temp_val4;
        temp[19]   = temp_val;
    }
    rk[(short)(35 * 8 + 0)] = temp[1];
    rk[(short)(35 * 8 + 1)] = temp[3];
    rk[(short)(35 * 8 + 2)] = temp[4];
    rk[(short)(35 * 8 + 3)] = temp[6];
    rk[(short)(35 * 8 + 4)] = temp[13];
    rk[(short)(35 * 8 + 5)] = temp[14];
    rk[(short)(35 * 8 + 6)] = temp[15];
    rk[(short)(35 * 8 + 7)] = temp[16];

}

I wanna know if there is a way to optimize this kind of loops. Also I don't know when to allocate the memory in RAM instead of EEPROM. Until now I allocated the memory this way:

public static byte[] temp   = new byte[MAX_MEMORY_TEMPORARY];  // TODO consider allocating tmp in RAM
public static byte[] rk     = new byte[36*8];
private static byte  [] roundconst =
    {
            0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x03, 0x06, 0x0c, 0x18, 0x30, 0x23, 0x05, 0x0a, 0x14, 0x28, 0x13, 0x26,
            0x0f, 0x1e, 0x3c, 0x3b, 0x35, 0x29, 0x11, 0x22, 0x07, 0x0e, 0x1c, 0x38, 0x33, 0x25, 0x09, 0x12, 0x24, 0x0b,
    };
private static short [] shufinv = {1, 2, 11, 6, 3, 0, 9, 4, 7, 10, 13, 14, 5, 8, 15, 12};
private static short [] shuf = { 5, 0, 1, 4, 7, 12, 3, 8, 13, 6, 9, 2, 15, 10, 11, 14};
private static byte  [] sbox = {0x0C, 0x00, 0x0F, 0x0A, 0x02, 0x0B, 0x09, 0x05, 0x08, 0x03, 0x0D, 0x07, 0x01, 0x0E, 0x06, 0x04};


texts:
This is a program about finding all the permutations of an string. I want to be able to make it faster and more efficient like eliminating the recursion maybe. Please advise.

What is intended is to also find the permutations of the sub-strings of the main string while repetitions should be omitted.

public class StrPerm {
    static int count = 0;

    public static void main(String[] args) {
        String str = "ABCD";
        permutation("", str);
        System.out.println("Total permutations of given string are : " + count);
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) {
            if (prefix != "")
                System.out.println(prefix);
            count++;
        } else {
            for (int i = 0; i < n; i++) {
                if (prefix != "") {
                    System.out.println(prefix);
                    count++;
                }
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1));
            }
        }
    }
}

The results are as follows:

  A
  AB
  ABC
  ABCD
  AB
  ABD
  ABDC
  A
  AC
  ACB
  ACBD
  AC
  ACD
  ACDB
  A
  AD
  ADB
  ADBC
  AD
  ADC
  ADCB
  B
  BA
  BAC
  BACD
  BA
  BAD
  BADC
  B
  BC
  BCA
  BCAD
  BC
  BCD
  BCDA
  B
  BD
  BDA
  BDAC
  BD
  BDC
  BDCA
  C
  CA
  CAB
  CABD
  CA
  CAD
  CADB
  C
  CB
  CBA
  CBAD
  CB
  CBD
  CBDA
  C
  CD
  CDA
  CDAB
  CD
  CDB
  CDBA
  D
  DA
  DAB
  DABC
  DA
  DAC
  DACB
  D
  DB
  DBA
  DBAC
  DB
  DBC
  DBCA
  D
  DC
  DCA
  DCAB
  DC
  DCB
  DCBA

  Total permutations of given strings are : 84


texts:
import java.util.*;

public class BFS {
    static LinkedList<Node> tracker = new LinkedList<>();
    static Node[] nodes = new Node[]{
            new Node(1),
            new Node(2),
            new Node(3),
            new Node(4),
            new Node(5),
            new Node(6),
    };

    public static void main(String[] args) {

        Map<Node, ArrayList<Edge>> graph = new TreeMap<>();
        graph.put(nodes[3], addEdges(2,3,5,6));
        graph.put(new Node(5), addEdges(3,4,6));
        graph.put(new Node(6), addEdges(4,5));
        graph.put(new Node(1), addEdges(2,3));
        graph.put(new Node(2), addEdges(1,4));
        graph.put(new Node(3), addEdges(1,4,5));

        traverse(graph, nodes[0]);

    }

    private static ArrayList<Edge> addEdges(int... edges) {
        ArrayList<Edge> edgeList = new ArrayList<>(edges.length);
        for(int edge : edges)
            edgeList.add(new Edge(nodes[edge-1]));
        return edgeList;
    }

    static class Node implements Comparable<Node>{
        final int vertex;
        boolean isExplored;

        Node(int vertex) {
            this.vertex = vertex;
        }

        @Override
        public int compareTo(Node node) {
            return this.vertex - node.vertex;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Node)) return false;
            Node node = (Node) o;
            return vertex == node.vertex;
        }

        @Override
        public int hashCode() {
            return Objects.hash(vertex, isExplored);
        }
    }

    static class Edge {
        Node endNode;
        boolean isExplored;
        Edge(Node endPoint) {
            this.endNode = endPoint;
        }
    }

    private static void traverse(Map<Node, ArrayList<Edge>> graph, Node startNode) {
        startNode.isExplored = true;
        tracker.add(startNode);
        System.out.println("Start Node -> " + startNode.vertex + " (" + startNode.hashCode() + ")");
        while(!tracker.isEmpty()) {
            Node top = tracker.pop();
            System.out.println("Top Node ->" + top.vertex + " (" + top.hashCode() + ")");
            for(Edge edge : graph.get(top)) {
                System.out.println("About to check Node ->" + edge.endNode.vertex);
                if(!edge.isExplored && !edge.endNode.isExplored) {
                    edge.endNode.isExplored = true;
                    edge.isExplored = true;
                    tracker.add(edge.endNode);
                    System.out.println("Marked Node ->" + edge.endNode.vertex);
                }
            }
        }
    }
}

I have implemented BFS can someone please review it and give recommendations. My main concern(but not limitted to) is the way I defined Graph i.e. Node and Edge class isn't a standard way of dealing with graphs.