texts:
I wrote a small sitemap-checker.aspx, the goal of this code is to find the pages, that respond with the codes other than 200. I've only put the C# part here for the review:
    void Start_Click(object sender, EventArgs e)
    {
        CheckUrls(UrlTextBox.Text);
    }

    private void CheckUrls(string url)
    {
        try
        {
            var xmlDoc = LoadXml(url);
            var urlNodes = xmlDoc.GetElementsByTagName("url");
            var numberOfNodes = urlNodes.Count;
            var index = 0;

            Log("### Total nodes: " + numberOfNodes+ "
");
            Log("Here is the list of URLs, with the status code other than 200:
");
            foreach (XmlNode urlNode in urlNodes)
            {
                CheckUrlNode(urlNode, xmlDoc);
                index++;

                if(index % 10 == 0)
                {
                    Log("" + index + " nodes of " + numberOfNodes + " are finished, please wait...");
                }
            };
            Log("### Sitemap check finished. Please analyze the reported urls

");
        }
        catch (Exception e)
        {
            Log("Some problems were encountered while checking the sitemap
");
            Log(e.Message + "
");
            Log(e.StackTrace + "
");
        }
    }

    private XmlDocument LoadXml(string url)
    {
        var m_strFilePath = url;
        string xmlStr;
        using (var wc = new WebClient())
        {
            xmlStr = wc.DownloadString(m_strFilePath);
        }
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlStr);
        return xmlDoc;
    }

    private void CheckUrlNode(XmlNode xmlNode, XmlDocument xmlDoc)
    {
        var urlList = new List<string>() { xmlNode["loc"].InnerText };

        var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
        nsmgr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

        var hrefLangUrls = xmlNode
            .SelectNodes("xhtml:link", nsmgr)
            .Cast<XmlNode>()
            .Select(x => x.Attributes["href"].Value);

        urlList.AddRange(hrefLangUrls);

        foreach (var url in urlList)
        {
            string logMessage;
            if (!CheckUrl(url, out logMessage))
            {
                Log(logMessage);
            }
        }
    }

    private bool CheckUrl(string url, out string logMessage)
    {
        logMessage = null;
        try
        {
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
            request.Method = "HEAD"; //Get only the header information -- no need to download any content

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                int statusCode = (int)response.StatusCode;
                if (statusCode == 200) //Good requests
                {
                    return true;
                }
                else
                {
                    logMessage = String.Format("{0}, status code: {1}", url, statusCode);
                    return false;
                }
            }
        }
        catch (WebException ex)
        {
            logMessage = String.Format("{0}, status: {1}", url, ex.Status);
        }
        catch (Exception ex)
        {
            logMessage = String.Format("Could not test url {0}, exeption message: {1}", url, ex.Message);
        }

        return false;
    }


texts: Find the second-largest number in an array of elements

texts:
I have written this code to find second largest element in an array of random integers.  If it needs to be optimized, then do comment on it.  First of all I'm populating all the elements into the list which does not have any repeating value, then sorting, then in  list.size()-2 I have second largest element.

This is one way of doing this:

int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
int max = Integer.MIN_VALUE;
int secMax = Integer.MIN_VALUE;
List<Integer> list = new ArrayList<>();
for(int i:randomIntegers) {
    if(!(list.contains(i))){
        list.add(i);
    }
}
Collections.sort(list);
System.out.println(list.get(list.size()-2));

If you are not allowed to sort that list then you can do the following to find the second-largest element:

int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
int max = Integer.MIN_VALUE;
int secMax = Integer.MIN_VALUE;
List<Integer> list = new ArrayList<>();
for(int i:randomIntegers) {
    if(!(list.contains(i))){
        list.add(i);
    }
}
for(int i:list) {
    if(max < i) {
        secMax = max;
        max = i;
    }
    else if(secMax < i){
        secMax = i;
    }
}
System.out.println("Second Largest Number is :" + secMax);


texts:
I have a utility class, called Bills, that extracts some information from a billId and a paymentId. I'm pasting the whole class here for completeness, you don't need to understand the algorithm behind all functions to be able to answer my question.

<?php

class Bills {
    private $typeAndServicePaymentIdMap = [
        0 => 13,
        1 => 4, // water
        2 => 1, // electricity
        3 => 5, // gas
        4 => 2, // landline
        5 => 3, // cellphone
        6 => 6, // municipality due
        7 => 6, // municipality due type 7
        9 => [
            'default' => 24, // traffic due
            '001' => 38, // traffic fine
            '002' => 38, // traffic fine
        ],
    ];

    private $logger;

    public function __construct(File_Logger $logger)
    {
        $this->logger = $logger;
    }

    public function getType($billId)
    {
        return substr($billId, -2, 1);
    }

    public function getAmount($paymentId)
    {
        $paymentId = str_pad($paymentId, 13, '0', STR_PAD_LEFT);
        $amount = ltrim(substr($paymentId, 0, 8), '0') . '000';

        return $amount;
    }

    public function getCompanyCode($billId)
    {
        return substr($billId, -5, 3);
    }

    public function getPaymentServiceId($billId)
    {
        $type = $this->getType($billId);

        if (key_exists($type, $this->typeAndPaymentServiceIdMap)) {
            return $this->calculatePaymentServiceId($type);
        } else {
            $this->logger->errorLog('Type ' . $type . ' is not defined in the $typeAndPaymentServiceIdMap.');
        }
    }

    private function calculatePaymentServiceId($type)
    {
        $paymentServiceId = $this->typeAndPaymentServiceIdMap[$type];

        if (is_array($paymentServiceId)) {
            return $this->createPaymentServiceIdFromCompanyCode($paymentServiceId);
        } else {
            return $paymentServiceId;
        }
    }

    private function createPaymentServiceIdFromCompanyCode($paymentServiceId)
    {
        $companyCode = $this->getCompanyCode($billId); // TODO: fix this, we don't have $billId here

        if (key_exists($companyCode, $paymentServiceId)) {
            return $paymentServiceId[$companyCode];
        } else {
            return $paymentServiceId['default'];
        }
    }
}

The problem I have is in getPaymentServiceId(). Here is what this function does:

If the type is found in the type -> paymentServiceId map, it checks the value defined for $type in the map. For example, if $type is 1, it gets the value for 1, which in this case is 4.
If the paymentServiceId (the value that was retrieved in the previous step) is not an array, it just returns it. For example, if type is 1, the value is 4, and it is returned as-is.
However, if the paymentServiceId is an array, we need to calculate the company code (calculated using $this->getCompanyCode()) to be able to get a paymentServiceId, and as you can see, to do that, we need billId. In the current mapping, only a type of 9 would result in this calculation. All other types would not require this.

In other words, if createPaymentServiceIdFromCompanyCode() is called, it needs billId. If not, billId is not needed. My problem is that I don't want to pass billId as an argument down the chain when it is only needed for one $type.

Is there a better way of structuring this class to achieve what I want, or do I have to just pass billId down the chain every time?


texts:
I was reading this article about StringBuilder vs string.concat and couldn't figure out which one would be better in the following situation:

StringBuilder address = new StringBuilder();

address.Append(retailer.Street.Replace(",", "
").Replace("\n", "
"));
address.Append("
");

if (!string.IsNullOrWhiteSpace(retailer.City))
{
  address.Append(retailer.City);
  address.Append("
");
}

if (!string.IsNullOrWhiteSpace(retailer.County))
{
  address.Append(retailer.County);
  address.Append("
");
}

address.Append(retailer.Postcode);

return MvcHtmlString.Create(address.ToString());

According to the article, as it is not in a loop, I should be using string.Concat. But as there are if statements while building the string, I was wondering if that still applied.

Or would I be better off doing the following:

string address = string.Concat(retailer.Street.Replace(",", "
").Replace("\n", "
"), "
");

if (!string.IsNullOrWhiteSpace(retailer.City))
{
    address += string.Concat(retailer.City, "
");
}

if (!string.IsNullOrWhiteSpace(retailer.County))
{
    address += string.Concat(retailer.County, "
");
}

address += retailer.Postcode;

return MvcHtmlString.Create(address);


texts:
I am concerned about creating too many objects in my code.
Am I using duplicate code? Can I cut down on the number of lines of code?

Note: I only want to use recursion to solve this. Any suggestions on the design of the program and naming convention used here are appreciated.

import java.util.ArrayList;

class Subsets {
    public static void main(String[] args) {
        ArrayList<Integer> superSet = new ArrayList<Integer>();
        superSet.add(1);
        superSet.add(2);
        superSet.add(3);
        superSet.add(4);
        ArrayList<ArrayList<Integer>> lists = Subsets.getSubsets(superSet);
        System.out.println("final set ==> " + lists);
    }

    static ArrayList<ArrayList<Integer>> getSubsets(ArrayList<Integer> SubList) {
        if (SubList.size() > 0) {
            ArrayList<ArrayList<Integer>> list = addToList(SubList.remove(0),
                    SubList);
            return list;
        } else {
            ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
            list.add(SubList);
            return list;
        }
    }

    private static ArrayList<ArrayList<Integer>> addToList(
            Integer firstElement, ArrayList<Integer> SubList) {
        ArrayList<ArrayList<Integer>> listOfLists = getSubsets(SubList);
        ArrayList<ArrayList<Integer>> superList = new ArrayList<ArrayList<Integer>>();
        for (ArrayList<Integer> iList : listOfLists) {
            superList.add(new ArrayList<Integer>(iList));
            iList.add(firstElement);
            superList.add(new ArrayList<Integer>(iList));
        }
        return superList;
    }
}


texts: Hash table for Coursera's algorithms course

texts:
I implemented a hash table for Coursera's Algorithms and Design class. I am looking for feedback on coding style and other improvements. I want to practice C++ coding but I see myself drifting to C and functional programming a lot. Any advice on switching would be very helpful.

The problem is as follows:

  Given a list of 1 million numbers, find all the values of t in
  [-10000, 10000] such that if you pick 2 distinct numbers from the
  given list, they sum to t.

Solution (from one of the posts in the discussion forums):

  Store all the numbers in a hash table (map of (key, value) where
  key=int and value=vector). The hash function makes the key by dividing
  the number by 20000. Then, go to that key in the hash table and do a
  push_back on the vector for the value of that key.

Here are the 2 files:

#include<iostream>
#include <vector>
#include <fstream>
#include <set>
#include <map>
#include <cmath>
#include <sys/time.h>

using namespace std;

typedef set<long int> inner;
typedef map<int, inner> hashTable_T;

#include "ht2.h"

using namespace std;

void readfile(hashTable_T &H){
    ifstream ipstream;
    ipstream.open("algo1-programming_prob-2sum.txt");
    long int output; int index; hashTable_T::iterator it;
    while (ipstream >> output){
        index = output/(2*t);
        it = H.find(index);
        if (it==H.end()){
            inner innerVec;
            innerVec.insert(output);
            H.insert(make_pair(index,innerVec));
        }
        else{
            (it->second).insert(output);
        }
    }
    ipstream.close();
}

int findinTable(hashTable_T &H,const  long int &value, const int &binL,const int &binH, set<int> &setofTs){
    hashTable_T :: iterator it, itL, itH;
    inner :: iterator itIn;
    long int sum;

    itL = H.upper_bound(binL);
    if (itL!=H.begin()) itL--;
    itH = H.upper_bound(binH);

    bool done = false;
    while( itL!= H.end()){
        for (itIn = (itL->second).begin() ; itIn != (itL->second).end() ; itIn++){
            sum = *itIn + value;
            if (sum <= t && sum >= -t && *itIn!=value) setofTs.insert(sum) ;
        }
        itL++;
        if (done) break;
        if (itL == itH) done = true;
    }
}

void printHashTable(hashTable_T &H){
    hashTable_T::iterator it;
    inner::iterator vecIt;
    for (it=H.begin(); it!=H.end() ; it++){
        cout << it->first << " :";
        for (vecIt = (it->second).begin() ; vecIt != (it->second).end() ; vecIt++){
            cout << *vecIt << " ";
        }
        cout << endl;
    }
}

int main(){
    int t = 10000;
    hashTable_T HashTable;
    readfile(HashTable);

    set<int> setofTs;
    hashTable_T::iterator it = HashTable.begin();
    inner::iterator it2;
    int binL, binH;
    for (it;it!=HashTable.end();it++){
        for (it2 = (it->second).begin();it2 != (it->second).end(); it2++){
            binL = (-t-(*it2))/(2*t);
            binH = (t- (*it2))/(2*t);
            findinTable(HashTable, *it2, binL, binH, setofTs);
        }
    }
    cout << setofTs.size() << endl;
    return 0;
}


texts: Argument-parsing class in Python to handle a --force flag

texts:
I am relatively new to Python. I've so far mostly worked with PHP and C#, so most of it is relatively familiar.

I'm making a simple console application that will store a few API calls in a local database through a cronjob. It will have a timeout, so if the program is run too often it won't spam the API and use up all of my free access tokens.

Of course this begs for my favourite flag in any console application: --force. If something doesn't work, try forcing it, right?

Now, my first attempt at adding this was using sys.argv[n] like I would in PHP, though I read that's a rather insecure solution, which could also produce nasty bugs.

So, wanting to better my Python OOP knowledge as well as add a better implementation of CLI arguments, I've now written this:

import argparse

class Arguments:

    def __init__(self):
        self.argument_parser = argparse.ArgumentParser()
        self.argument_parser.add_argument(
            '--force',
            default=False,
            help="Force the program to run, even if the timer returns False.",
            action="store_true"
        )
        self.parsed = self.argument_parser.parse_args()

    @property
    def force_run(self):
        return self.parsed.force

Is this the right way to use classes in Python, and this is a "better" implementation of CLI arguments?

Sidenote: This was written with the assumption I'll be adding more flags in the future, all of which are accessed through the Arguments class.


texts: Correct way to center logo and navigation

texts:
I'm new to CSS and HTML and while I've achieved a centering of the logo and navigation links, it feels wrong.  I'm developing a site for a small non-profit for a side project.  I have a logo next to a few navigation links.  I put the logo and navigation links in a list.

Could someone take a look at this and tell me if my CSS is correct?  I just think that there's something off.  Or that I'm duplicating CSS code.

Here's my JSFiddle to show what I've done.

HTML:

WHO WE ARE

WHAT WE DO

EXPLORE

DONATE

CSS:

#top_nav {
    text-align: center;
    width: 100%;
}

#nav_logo {
    /*display: inline-block;*/
    width: 142px;
    height: 159px;
    padding-right: 20px;
    text-decoration: none;
}

#nav_links li a {
    padding: 15px 20px;
    text-decoration: none;
    font-family: Arial;
    font-size: 24px;
    color: #000;
}

/* When window is resized, doesn't wrap menu*/
#nav_links {
    display: inline-block;
    padding: 0 0 30px 0;
    list-style:none;
    text-align:left;
    white-space: nowrap;
}

#nav_links li {
    vertical-align: text-top;
    display: inline-block;
    float: none;
    margin: 0 -3px 0 0;

}
/* ------------------------------------*/

a.nav_links_border {
    border-right: 1px solid #f37f43;
}

#nav_links li a:hover {
    text-decoration: underline;
}

#nav_links > img:hover {
    text-decoration: none;
}

#bottom_nav {
    clear: both;
}


texts: Sorting an List of tiles based on size and row limitation

texts:
We are using the below code to optimally display our menu items (metro style).  We are looping through an array of menu items and automatically shifting them based on size.

Our tiles could be a size of 1, 2, 3.  The row length is 6

Could you help me optimize the code?

private void SortTiles(ref List<MenuItems> t)
    {
        int rowSize = 0;
        var n = new List<MenuItems>();

        while (t.Count > 0)
        {
            if (6 - rowSize < t[0].Size) //Too Big
            {
                bool suitableTileFound = false;

                for (int j = 1; j < t.Count; j++) //Go find smaller tile
                {
                    if (6 - rowSize >= t[j].Size) //Use this one
                    {
                        suitableTileFound = true;
                        n.Add(t[j]);
                        rowSize += t[j].Size;
                        t.RemoveAt(j);
                        break;
                    }
                }
                if (!suitableTileFound)
                    rowSize = 0;
            }
            else
            {
                //Add normally
                n.Add(t[0]);
                rowSize += t[0].Size;
                t.RemoveAt(0);
            }

        }
        t = n;
    }

MenuItem class

public class MenuItems
{
    public int MenuId { get; set; }

    public string MenuTitle { get; set; }

    public string MenuUrl { get; set; }

    public int SuiteId { get; set; }

    public string Target { get; set; }

    public int? Count { get; set; }

    public List<MenuItems> SubMenuItems { get; set; }

    public int Size { get; set; }
}


texts:
I've made a prime number generator (for Project Euler).  It uses Euler's Sieve (a modified Sieve of Eratosthenes), with a mod 30 step.  I'd like to reduce the memory consumption to 4/15 what it currently is by keeping a boolean array only for the possibly prime remainders of 30.  I can't get it to work and also fear that this will slow down the program.

I've used

n[f/30*8+[zeroes, except 1,2,3,4,5,6,7 at 7,11,13,17,19,23,29][f%30]]

which seemed to not filter out any composite numbers.  How can I make this work and what other optimizations (aside from increasing the mod) can you suggest?  I need the primes up to about two billion.

#include <vector>
#include <algorithm>
#ifndef _pes30_cxx_
#define _pes30_cxx_
typedef unsigned long long big;
const int ofs[]={6,4,2,4,2,4,6,2};
void sievePrimes(big m,std::vector<big> &p){
  big f;
  bool n[m];
  p={2,3,5};
  for(big i=0;i<m;++i)n[i]=true;
  for(big i=7,s=1;i<=m;i+=ofs[s],++s==8?s=0:0){
    if(!n[i])continue;
    p.push_back(i);
    for(big j=i,t=s;j<=m/i;j+=ofs[t],++t==8?t=0:0){
      if(!n[j])continue;
      f=j*i;
      do{
        n[f]=false;
      }while((f*=j)<=m);
    }
  }
}
inline bool isPrime(big n,std::vector<big> p){
  return std::binary_search(p.begin(),p.end(),n);
}
#endif


texts: "Stardust" 2D Gravity Simulator - Follow Up 1: The Planets

texts:
This is a follow up for the 2D Gravity Simulator-like Game question.

Since then I have developed my javascript skills further, and now I'm using ES6 mainly. Note that even through this code uses the EaselJS library, the question is principally about its design so no EaselJS skill needed.

Also I wanna avoid posting a bigger version of the bible here, so this question is only about the game's Planet class and its properties.

The code is more well divided, but I don't know if this organization is effective, and how can changes in a planet's .physicsBody affect its graphical .skin – colors specially. Any tips and ratings on how I'm using class inheritance are really appreciated.

Also, is there any part that could use a more ES6-ish approach?

Planet class:

class Planet {
    constructor (x, y, radius, color) {
        this.physicsBody = new CircleBody(x, y, radius);
        this.skin = new CircleSkin(x, y, radius, color);
    }
    update (scene) {
        // This part is responsible for changing a planet's radius and animating the transition. I have no idea if this should in fact be made here or elsewhere.
        if (this.physicsBody.radius !== this.skin.radius) {
            this.skin.scaleX = this.skin.scaleY = this.skin.radius / this.physicsBody.radius;
            this.skin.radius = this.physicsBody.radius;
            this.skin.redraw();
            createjs.Tween.get(this.skin, {override: true}).to({scaleX: 1, scaleY: 1}, 1000, createjs.Ease.elasticOut);
        }
        if (!this.physicsBody.destroyed) {
            this.skin.x = this.physicsBody.x;
            this.skin.y = this.physicsBody.y;
        } else scene.removeChild(this);
    }
}

CircleBody class:

class CircleBody extends PhysicsBody {
    constructor (x, y, radius) {
        super(x, y);
        this.radius = radius;
    }
    get area () {
        return this._area;
    }
    set area (newValue) {
        this._area = newValue;
        this._radius = Math.sqrt(newValue / Math.PI / 4);
    }
    get radius () {
        return this._radius;
    }
    set radius (newValue) {
        this._radius = newValue;
        this._area = 4 * Math.PI * newValue * newValue;
    }
    get mass () {
        return this.area * this.density;
    }
}

PhysicsBody class:

class PhysicsBody {
    constructor (x, y) {
        this.x = x;
        this.y = y;

        this.px = x;
        this.py = y;

        this.vx = 0;
        this.vy = 0;

        this.density = 1;

        this.affectedByGravity = true;
        this.static = false;
        this.collision = null;
        this.destroyed = false;
    }
    get dynamic () {
        return !this.static;
    }
    set dynamic (newValue) {
        this.static = !newValue;
    }
    get velocity () {
        return new Vector(this.vx, this.vy);
    }
    clearCollisions () {
        this.collision = null;
    }
}

CircleSkin class:

class CircleSkin extends Skin {
    constructor (x, y, radius, color) {
        super(x, y, color);
        this.radius = radius;
        this.redraw();
    }
    redraw (resolution) {
        var r = this.radius;
        this.graphics.clear();
        this.graphics.f(this.color).dc(0, 0, r);
        //this.cache(-r, -r, r * 2, r * 2, resolution || 1);
    }
}

Skin class:

class Skin extends createjs.Shape {
    constructor (x, y, color) {
        super();
        this.x = x;
        this.y = y;
        this.color = color;
    }
}

And finally, this is the class usage in engine:

for (var i = 0; i < 1024; ++i) {
    var x = Utils.getRandomInt(0, innerWidth),
        y = Utils.getRandomInt(0, innerHeight);
    var myPlanet = new Planet(x, y, 2, Utils.getRandomItem(colors));
    myPlanet.physicsBody.n = i;
    myScene.addChild(myPlanet);
}

Utils and Vector dependencies are out of scope and I think their method names are pretty clear so no declaration needed here.


texts: Find differences between two spreadsheets

texts:
I have this code that is supposed to compare two Excel sheets. The code is working fine for small comparisons. I did a test run with 7 rows and 2 columns.

The code itself works as follows: it compares the two sheets and copies the differences into a new workbook.

However, the code should be applied to files that have around 16 columns and a lot of rows (around 206700).  It doesn't seem to scale very well to these larger sheets - the process is shown “Not Responding”, for more than ten minutes when I gave up.

This is how my excel file columns looks likem, keeping in mind that most of them contain text and only few times numbers are used.

I'd like to improve the performance with these larger files; any other suggestions for improvement are also welcome.

Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)

  Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer
  Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
  Dim report As Workbook, difference As Long
  Dim row As Long, col As Integer

  Set report = Workbooks.Add

  With ws1.UsedRange
    ws1row = .Rows.Count
    ws1col = .Columns.Count
  End With

  With ws2.UsedRange
    ws2row = .Rows.Count
    ws2col = .Columns.Count
  End With

  maxrow = ws1row
  maxcol = ws1col
  If maxrow < ws2row Then maxrow = ws2row
  If maxcol < ws2col Then maxcol = ws2col

  difference = 0

  For col = 1 To maxcol
    For row = 1 To maxrow
      colval1 = ""
      colval2 = ""
      colval1 = ws1.Cells(row, col).Formula
      colval2 = ws2.Cells(row, col).Formula
      If colval1 <> colval2 Then
        difference = difference + 1
        Cells(row, col).Formula = colval1 & "<> " & colval2
        Cells(row, col).Interior.Color = 255
        Cells(row, col).Font.ColorIndex = 2
        Cells(row, col).Font.Bold = True
      End If
    Next row
  Next col

  Columns("A:B").ColumnWidth = 25
  report.Saved = True

  If difference = 0 Then
    report.Close False
  End If
  Set report = Nothing
  MsgBox difference & " cells contain different data! ", vbInformation, _
         "Comparing Two       Worksheets"
End Sub


texts: Generate a CSV file from a multidimensional array in php

texts:
I can tell by looking at this code that I've gone about this in the wrong way.  Provided the string is correctly formatted (each index ofCSVData[][], would the following generate a CSV file?

There must be a more elegant way of taking my queries and building a CSV.  Looking at this code kinda makes me sick in the stomach.

class ShippingCSVGenerator
{
    public function generateShippingCSV($invoiceArray)
    {
        $invoiceArray = $this->filterInvoices($invoiceArray);
        if(empty($invoiceArray))
        {
            // no parcels to fetch
            return;
        }
        $dispatchDataRes = \DispatchDataQuery::create()
            ->where('DispatchData.printed = ?', $invoiceArray)
            ->find();

        $index = 0;
        $CSVData = [];
        foreach($dispatchDataRes as $orders)
        {
            $parcelsRes = \ItemsInDispatchQuery::create()
                ->where('ItemsInDispatch.orderNumber = ?', $orders->orderNumber)
                ->find();

            $parcelIndex = 0;
            foreach($parclesRes as $parcel)
            {
                $CSVData[$index][$parcelIndex] =
                    $orders->orderNumber() . ',' .
                    $orders->date() . ',' .
                    $orders->toName() . ',' .
                    $orders->destinationBuilding() . ',' .
                    $orders->destinationStreet() . ',' .
                    $orders->suburb() . ',' .
                    $orders->unused_7() . ',' .
                    $orders->postcode() . ',' .
                    $orders->state() . ',' .
                    $orders->country() . ',' .
                    $orders->email() . ',' .
                    $orders->phone() . ',' .
                    $orders->itemName() . ',' .
                    $orders->itemPrice() . ',' .
                    $orders->instructions() . ',' .
                    $parcel->weight() . ',' .
                    $orders->shippingMethod() . ',' .
                    $parcelIndex . ',' .
                    $orders->SKU() . ',' .
                    $orders->quantity() . ',' .
                    $orders->unused_21() . ',' .
                    $orders->unused_22() . ',' .
                    $orders->unused_23() . ',' .
                    $orders->unused_24() . ',' .
                    $parcel->height() . ',' .
                    $parcel->width() . ',' .
                    $parcel->length() . ',' .
                    $orders->courier() . ',' .
                    $orders->unused_29() . ',' .
                    $orders->unused_30();
                $parcelIndex++;
            }
            $index++;
        }

        header("Content-Type: text/csv");
        header('Content-disposition: attachment;filename=shipping.csv');
        $fp = fopen("php://output", "w");
        fputcsv ($fp, $header, "\t");
        foreach($CSVData as $order)
        {
            foreach($csvOrder as $csvParcel)
            {
                fputcsv($fp, $csvParcel, "\n");
            }
        }
        fclose($fp);
    }

    private function filterInvoices($invoiceArray)
    {
        if(empty($invoiceArray))
        {
            // no parcels to fetch
            return;
        }
        $filteredInvoices = [];
        $dispatchDataRes = \DispatchDataQuery::create()
            ->where('DispatchData.printed = ?', $invoiceArray)
            ->find();
        if($dispatchDataRes->isEmpty())
        {
            // no parcels to fetch
            return;
        }
        else
        {
            foreach($dispatchDataRes as $invoicesToFetch)
            {
                $filteredInvoices = $invoicesToFetch->getInvoiceNumber();
            }
        }
        return $filteredInvoices;
    }
}


texts: Project Euler - Problem 1 Multiples of 3 and 5 (Java)

texts:
I consider myself a beginner at Java but this question was an easy one.  My only concern is if there is a more efficient way to write this program. I'm very open minded.  I don't care how advanced your answer is, I'm willing to learn.

public static void main(String[] args) {

    long limit = 1000;

    long sum = sumOfMultiples(3,limit) + sumOfMultiples(5,limit) - sumOfMultiples(15,limit);

}

public static long sumOfMultiples(long number, long limit){
    long sum = 0;
    long add = number;

    for(; add < limit; add+=number){
        sum += add;
    }

    return sum;
}


texts: How to handle JSON's undefined value in a better way?

texts:
I'm working on Google Book API to post a book's basic information. I notice that some of the books will always miss a value or two under volumeInfo, like this book (Fiddle) that has no publisher value. Do I need to repeat if [object] undefined statement several times for the missing values (e.g Publisher,Average Rating,Rating Count)? Can I do it in a more concise way?

 $.ajax({

    url: 'http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22https%3A%2F%2Fwww.googleapis.com%2Fbooks%2Fv1%2Fvolumes%3Fq%3Disbn%3A1879505215%22&format=json&diagnostics=true&callback=?',
    dataType: 'json',
    success: function (data) {

 $(data.query.results.json.items).each(function (index, item) {

    var isbn10;

 $.each(item.volumeInfo.industryIdentifiers, function(index, item) {

    if (item.type === "ISBN_10") {
    isbn10 = item.identifier;
    return false;
    }

    });
    var Rating = item.volumeInfo.averageRating;
    var RatingCount = item.volumeInfo.ratingsCount;
    var item_html = '';

    item_html += '

<img src="' +item.volumeInfo.imageLinks.thumbnail+'

Author: ' + item.volumeInfo.authors + '

Publisher ' + item.volumeInfo.publisher + '

PublishDate: '+item.volumeInfo.publishedDate+'

Category: ' + item.volumeInfo.categories + '

Page Count: ' + item.volumeInfo.pageCount +'

ISBN: ISBN10_' + isbn10 +'

Description:  ' + item.volumeInfo.description +'
';

    if (Rating != undefined) {
    item_html += '
Average Rating:' + Rating +'
';
    }

    if (RatingCount != undefined) {
    item_html += '
Rating Count:' + RatingCount +'
';
    }

    var title_html ='' +item.volumeInfo.title + '';

    $('#bookhead').append(title_html);

    $('#bookdetail ul').append(item_html);

    });

    },
    error: function () {}

    });


texts:
I made a class that connects to my DB and inserts some values. Is it secure or how can I protect this further from injections? The object declaration will come from variables with POST from a form, after being validated, ofc. Just want to know if this is secure.

That, and also, should I make a method for every query I need? Or is there a better and secure way?

<?php
include "db/db_info.php";
/*$DBServer
$DBUser
$DBPass
$DBName*/
class WorkDB {
    private $server;
    private $user;
    private $pass;
    private $name;
    private $conn;

    public function __construct( $server, $user, $pass, $name ) {
        $this->server=$server;
        $this->user=$user;
        $this->pass=$pass;
        $this->name=$name;
    }

    public function tryconn() {
        $this->conn = new mysqli(  $this->server, $this->user, $this->pass, $this->name );

    if ( mysqli_connect_error()) {
        die( '*************Connection Error (' . mysqli_connect_errno()  . '):'
                .mysqli_connect_error() );
    }

    else echo 'ok';

}

public function query_register( $user, $pass, $email ) {
    $stmt = $this->conn->prepare( "INSERT INTO `users` (`username`, `password`, `email`) VALUES (?, ?,?)" );
    $stmt->bind_param( "sss", $user, $pass, $email );
    $stmt->execute();
    $stmt->close();
}

}//end of class

$a=new WorkDB( $DBServer, $DBUser, $DBPass, $DBName );
$a->tryconn();
$a->query_register( 'a', 'b', 'c' );

?>


texts: Submitting forms on pages linked from a main page

texts:
In this scenario, the main page contains a list of links to the subpages. The requirement is to navigate to each page (if a condition passes) and perform some actions.

I have written the loop using Geb:

at MainPage
    ListItem.each {
        if(Button.present){
            Button.click()
            at SubPage
                SelectAddressButton.click()
                termsCheckBox.value(true)
                EnterButton.click()
                to MainPage
    }
}

I feel that the code can be improved so that the toMainPage need not be specified again inside the loop. I have alternatively used driver.navigate().back()  which doesn't seem clean either.


texts:
I'm currently writing a mesh generator class, and I'm making a method that generates vertices, normals and texcoords for a cube. But, as you can see, it's incredibly complicated and hard to follow. Is anyone willing to help me making this shorter?

public static void GenerateCube(float size, out Vector3[] vertices, out Vector2[] texCoords, out Vector3[] normals)
{
    List<Vector3> vertexList = new List<Vector3>();
    List<Vector2> texCoordList = new List<Vector2>();
    List<Vector3> normalList = new List<Vector3>();

    for (int i = 0; i <= 2; i++)
    {
        Vector3 normal = i == 0 ? Vector3.UnitZ : (i == 1 ? -Vector3.UnitY : Vector3.UnitX);

        float ninety = (float)(Math.PI / 2);
        Matrix4 matrix = i == 0 ? Matrix4.Identity : (i == 1 ? Matrix4.CreateRotationX(ninety) : Matrix4.CreateRotationY(ninety));

        Vector3 vertex1a = new Vector3(-1, -1, 1);
        Vector3 vertex2a = new Vector3(-1, 1, 1);
        Vector3 vertex3a = new Vector3(1, 1, 1);
        Vector3 vertex4a = new Vector3(1, -1, 1);

        Vector3 vertex1b = new Vector3(-1, -1, 1);
        Vector3 vertex2b = new Vector3(1, -1, 1);
        Vector3 vertex3b = new Vector3(1, 1, 1);
        Vector3 vertex4b = new Vector3(-1, 1, 1);

        vertex1a = Vector3.Transform(vertex1a, matrix);
        vertex2a = Vector3.Transform(vertex2a, matrix);
        vertex3a = Vector3.Transform(vertex3a, matrix);
        vertex4a = Vector3.Transform(vertex4a, matrix);

        vertex1b = Vector3.Transform(vertex1b, matrix);
        vertex2b = Vector3.Transform(vertex2b, matrix);
        vertex3b = Vector3.Transform(vertex3b, matrix);
        vertex4b = Vector3.Transform(vertex4b, matrix);

        for (int j = -1; j <= 1; j += 2)
        {
            Vector3 vertex1, vertex2, vertex3, vertex4;
            if (j == -1)
            {
                vertex1 = vertex1a;
                vertex2 = vertex2a;
                vertex3 = vertex3a;
                vertex4 = vertex4a;
            }
            else
            {
                vertex1 = vertex1b;
                vertex2 = vertex2b;
                vertex3 = vertex3b;
                vertex4 = vertex4b;
            }

            //Triangle 1
            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(0, 0));
            vertexList.Add(vertex1 * j);

            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(0, 1));
            vertexList.Add(vertex2 * j);

            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(1, 1));
            vertexList.Add(vertex3 * j);

            //Triangle 2
            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(0, 0));
            vertexList.Add(vertex1 * j);

            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(1, 1));
            vertexList.Add(vertex3 * j);

            normalList.Add(normal * j);
            texCoordList.Add(new Vector2(1, 0));
            vertexList.Add(vertex4 * j);
        }
    }

    vertices = vertexList.ToArray();
    texCoords = texCoordList.ToArray();
    normals = normalList.ToArray();

    for (int i = 0; i < vertices.Length; i++)
        vertices[i] *= size;
}


texts: Optimal way to Compare two arrays that are widely different

texts:
I have two different arrays that are widely different in length, arrayA, arrayB

for example:arrayA.Length=1000  and arrayB.Length=100,000

Create a boolean function that returns true if each item in arrayA are also  present in arrayB, at least the same number of times as in arrayA.

Please review my code below and help me with siuggestions to improve this code below

    private static bool IsMinRequiredFrequencyMatch(int[] arrA,int[] arrB)
    {
    bool result = false;
    Array.Sort(arrA);

    //create dictionary from shorter array
    var dict = new Dictionary<int, int>();
    for (int i = 0; i < arrA.Length; i++)
    {
        var ch = arrA[i];
        if (!dict.ContainsKey(ch))
        {
            dict[ch] = 1; //add char count
        }
        else
        {
            dict[ch]++; //increase count
        }
    }

    //loop through Dictionary
    foreach (var kvp in dict)
    {
        var chr = kvp.Key; //target item to find
        var expectedcount = kvp.Value; //expected count of item in arrB
        int actualCount = 0; //actual count of item in arrB

        //loop through arrayB
        for (int i = 0; i < arrB.Length; i++)
        {
            if (arrB[i] == chr)
            {
                actualCount++;
            }

            if (actualCount >= expectedcount)
            {
                result = true;
                break;
            }
        }

        if (actualCount < expectedcount)
        {
            result = false;
            break;
        }
    }

    return result;

}


texts:
I have been learning programming for better half of a year now and recently started learning Rust. This is my attempt at implementing selection sort and insertion sort. Since I tried to implement both without mutating the argument, I am not sure if my implementation agrees with the definitions.

Selection sort:

fn selection_sort<T>(arr: &[T]) -> VecDeque<T>
where T: PartialOrd + Clone {
    if arr.len() == 1 {
        return VecDeque::from(arr.to_vec())
    }
    let mut sorted = selection_sort(&arr[1..]);
    let el = arr[0].clone();
    if el >= *sorted.back().unwrap(){
        sorted.push_back(el);
    } else if el <= *sorted.front().unwrap() {
        sorted.push_front(el);
    } else {
        let mut max = sorted.len() - 1;
        for i in 1..max {
            if sorted[i]>el && sorted[i] <= sorted[max] {
                max = i;
            }
        }
        sorted.insert(max, el)
    }
    sorted
}

Insertion sort:

fn insertion_sort <T>(arr: &[T]) -> Vec<T>
where T: PartialOrd + Clone {
    let mut sorted = vec![arr[0].clone()];
    for i in 1..arr.len() {
        sorted.push(arr[i].clone());
        let mut j = i;
        while j > 0 && sorted[j] < sorted[j - 1 ] {
            sorted.swap(j, j -1);
            j = j - 1;
        }
    }
    sorted
}


texts:
I'm trying to improve my coding practices and I was just wondering if (I'm definitely sure there are) there are better ways of doing the following task.

I'm rewriting the rent system of the building I live in, which currently (still) uses an Access '97 database. This is the schema that I've constructed and the following code fetches the data to be used in the section just below the nav.

I just have a few questions.

Am I doing too many queries? I'm pretty sure I cannot get all the information needed in just a single query (I've tried).
Naming conventions, should I be using $query1, $result1 etc or $person_query, $result_query. My logic is that, I don't need the resource variable again, why not reuse it? It's not like I create a new $conn each time.
Is there a simpler way of getting data, without using any framework?  I'm trying to solidify my own practices first before learning CakePHP. But perhaps CakePHP will force me to do that anyway.

<?php header('content-type: application/json; charset=utf-8');

//$_POST = json_decode(file_get_contents('php://input'));

$host = "127.0.0.1:3306";
$db = "bettenhaus";
$user = "root";
$pass = "";

$rent_types[0] = "Mieter";
$rent_types[1] = "Untermieter";
$rent_types[2] = "Zwischenmieter";

$json_id = $_GET['id'];

$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

// get basic info
$query = "SELECT people.id, people.surname, people.firstname, people.email, leases.room_id, DATE_FORMAT(leases.in_date, '%e %M %Y') as in_date, DATE_FORMAT(leases.out_date, '%e %M %Y') as out_date, leases.rent_type FROM people, leases WHERE people.id = :json_id AND leases.person_id = :json_id";
$result = $conn->prepare($query);
$result->bindValue(":json_id", $json_id);
$result->execute();

// prepare to merge
$person_info = $result->fetch(PDO::FETCH_ASSOC);

// get lease info
$query = "SELECT num as room_num, wg, rent FROM rooms WHERE id = :room_id";
$result = $conn->prepare($query);
$result->bindValue(":room_id", $person_info['room_id']);
$result->execute();

$room_info = $result->fetch(PDO::FETCH_ASSOC);

// merge two results
$all_info = array_merge($person_info, $room_info);
$all_info['rent_type'] = $rent_types[$all_info['rent_type']];

// get all bills charged to this tenant
$query = "SELECT SUM(amount) as debt FROM money_due WHERE person_id = :json_id";
$result = $conn->prepare($query);
$result->bindValue(":json_id", $json_id);
$result->execute();

$debt_info =  $result->fetch(PDO::FETCH_ASSOC);

// get total amount of money paid into the system by tenant
$query = "SELECT sum(money_paid.amount) as sum FROM money_paid, money_due WHERE money_paid.money_for = money_due.id AND money_due.person_id = :json_id";
$result = $conn->prepare($query);
$result->bindValue(":json_id", $json_id);
$result->execute();

$paid_info = $result->fetch(PDO::FETCH_ASSOC);

// calculate money owed to the house
$all_info['balance'] = $paid_info['sum'] - $debt_info['debt'];

$conn = null;

echo json_encode($all_info);

?>


texts:
I am unit testing this role provider. I have a few asserts in the code for my test. I am sure there are more test I could preform. Does anyone have any suggestions for more test for this role of the membership provider?

[TestMethod]
    public void TestDeleteUserAccess()
    {
        try
        {
            string sRoleName = "TestRole";
            string sUsername = "test.user";

            // Use a known user for relationships
            AsaMembershipProvider prov = this.GetMembershipProvider();
            MembershipUser user = prov.GetUser(sUsername, false);

            // Create a new role
            AsaRoleProvider roleProv = this.GetRoleProvider();
            roleProv.CreateRole(sRoleName);

            // Verify that role exists
            bool bRoleExists = roleProv.RoleExists(sRoleName);
            Assert.IsTrue(bRoleExists);

            // Add users to that role
            string[] usernames = new string[] { sUsername };
            string[] roleNames = new string[] { sRoleName };
            roleProv.AddUsersToRoles(usernames, roleNames);

            // Verify that user is in role
            bool bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
            Assert.IsTrue(bRelationExists);

            // Check various methods for finding role information
            string[] matchUsernames = roleProv.FindUsersInRole(sRoleName, "userx");// find constant
            foreach (string matchUsername in matchUsernames)//if match.length = 0 then roles were returned
            {
                Trace.WriteLine("Found in role " + sRoleName + ", user " + matchUsername + ". ");//check something instead of trace
            }

            string[] matchRoleNames = roleProv.GetRolesForUser(sUsername);
            foreach (string matchRoleName in matchRoleNames)
            {
                Trace.WriteLine("Found for user " + sUsername + ", role " + matchRoleName + ". ");
            }

            // Remove user from the role
            roleProv.RemoveUsersFromRoles(usernames, roleNames);

            // Verify that user is no longer in the role
            bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
            Assert.IsFalse(bRelationExists);

            // Delete the role
            roleProv.DeleteRole(sRoleName, true);

            // Verify that no longer exists
            bRoleExists = roleProv.RoleExists(sRoleName);
            Assert.IsFalse(bRoleExists);
        }
        catch (Exception ex)
        {
            LogMessage(ex);
            Assert.Fail(ex.Message);
        }
    }


texts:
I use a lot T4 templates and want to avoid extra code writing when it could be generated. Currently I have following class:

class Recursion
{
    private readonly string _function;
    private readonly Func<int, string> _appFunc;

    public Recursion(string function, Func<int, string> appFunc)
    {
        _function = function;
        _appFunc = appFunc;
    }

    public string Apply(int n)
    {
        return Apply(0, n);
    }

    private string Apply(int k, int n)
    {
        var diff = n - k;
        if (diff == 0)
            return "0";
        if (diff == 1)
            return _appFunc(k);
        if (diff == 2)
            return string.Format("{0}({1}, {2})", _function, _appFunc(k), _appFunc(k + 1));
        int half = (n + k) / 2;
        return string.Format("{0}({1}, {2})", _function, Apply(k, half), Apply(half, n));
    }
}

Example of usage:

var rec = new Recursion("Math.Max", i => string.Format("source[{0}]", i));
Console.WriteLine(rec.Apply(8));

output:

  Math.Max(Math.Max(Math.Max(source[0], source[1]), Math.Max(source[2],
  source[3])), Math.Max(Math.Max(source[4], source[5]),
  Math.Max(source[6], source[7])))

It works fine but for large files generation takes a lot of time (even when N is small). I can't use it for larger N (now I'm using N = 4 and generation takes 5+ seconds, i expect that for 8 and more it would take hours).

I want to get this output, but with smaller cost, if possible, possibly with a different algorithm.


texts:
I have recently started learning Clojure, and decided to write a number-guessing-game as an exercise.

The game works as follows:

User enters minimum and maximum values
Computer generates a number between those two values (inclusive)
User has to guess the number (the computer always tells him, whether his guess is bigger or smaller then the secret number)

(ns numguess.core)

(defn parse-int [v]
   (try
     (Integer/parseInt (re-find #"^-?\d+$" (.toString v)))
     (catch NumberFormatException e nil)
     (catch NullPointerException e nil)))

(defn get-input
  ([] (get-input nil))
  ([default]
     (let [input (clojure.string/trim (read-line))]
       (if (empty? input)
         default
         (clojure.string/lower-case input)))))

(defn get-number-input
  []
  (let [n (parse-int (get-input))]
      (if (nil? n) (recur) n)))

(defn get-input-prompt
  ([prompt default] (println (str prompt " ")) (get-input default))
  ([prompt] (get-input-prompt prompt nil)))

(defn get-number-input-prompt
  [prompt]
  (println (str prompt " ")) (get-number-input))

(defn gameplay
  [my-num]
  (let [n (get-number-input-prompt "What is your guess?")]
    (if (< n my-num)
        (do (println "My Number is bigger")
              (recur my-num))
        (if (> n my-num)
            (do (println "My Number is smaller")
                 (recur my-num))
            (println "You have guessed it: congratulations :)")))))

(defn is-yes
  [prompt]
  (let [answer (get-input-prompt prompt "y")]
       (not= "n" answer)))

(defn generate-my-number
  [min-val max-val]
  (let [my-max (max min-val max-val) my-min (min min-val max-val)]
  (+ (rand-int (- (inc my-max) my-min)) my-min)))

(defn mainloop []
  (let [n (generate-my-number
            (get-number-input-prompt "Please enter minimal value")
            (get-number-input-prompt "Please enter maximal value"))]
    (gameplay n)
    (if (is-yes "Would you like to play again?") (recur))))

(mainloop)

I am interested in any kind of improvement suggestion, no matter whether it is something as important as a key concept, or just indentation.


texts: Helper method to find VisualChildren of multiple Types

texts:
I created an helper method to return a List of UIElements where the returned  elements have to match with one of the Types which I pass to the method.

First I used this method to get all the children of one type:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject dependencyObj) where T : DependencyObject
{
    if (dependencyObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

I called this method like:

var textBoxes = UIHelper.FindVisualChildren<TextBox>(currentView);

But I need to find find elements of multiple types, so I rewrote the helper method to accept a List of Types.

public static IEnumerable<UIElement> FindVisualChildrenOfMultipleTypes(List<Type> types, DependencyObject dependencyObj)
{
    if (dependencyObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObj, i);
            if (child != null && types.Contains(child.GetType()))
            {
                yield return child as UIElement;
            }

            foreach (var childOfChild in FindVisualChildrenOfMultipleTypes(types, child))
            {
                yield return childOfChild;
            }
        }
    }
}

Called like:

List<Type> types= new List<Type>()
{
    typeof(CheckBox),
    typeof(RadioButton),
    typeof(TextBox)
};
var children = UIHelper.FindVisualChildrenOfMultipleTypes(types, currentView);

This works, but I think there a some improvements possible. For example the signature of my method, I think Generics can be used in the method signature, but I'm not very experienced with Generics, so advice on this would be nice. I'm also wondering if the performance of the method can be improved.


texts: Algorithm to determine if a string is all unique characters

texts:
This my solution to one of the practice problems from Cracking the Coding Interview: 150 Programming Interview Questions and Solutions [Book]

  implement an algorithm to determine of a string has all unique characters. What if you cannot use additional data structures ?

public class PracticeProblems {

    public void questionOne(String input) {
        /*-- implement an algorithm to determine if a string has all unique characters.
         * What if you cannot use additional data structures?   --*/

        boolean[] chars = new boolean[26];
        int x = 0;

        for(int i = 0; i < input.length(); i++) {

            if(!chars[(int)input.toUpperCase().charAt(i) - 64]) {
                chars[(int)input.toUpperCase().charAt(i) - 64] = true;
            }
            else {
                System.out.println("not unique");
                x = -1;
                break;
            }
        }

        if(x == 0)
            System.out.println("unique");
    }

    public static void main(String[] args) {
        PracticeProblems test = new PracticeProblems();
        test.questionOne("dsfdddft");
    }
}

I was wondering if there was a better solution to this, or if there is a better way of handling the last part, where I am initializing an x variable to be able to determine if I all the characters are not unique, not to print "it is unique". If don't have the condition for the x value it always prints "it is unique".


texts:
The goal of this function is to an invert an income tax function. That is, given the tax paid and the financial year, the function should return the taxable income for that year. I would prefer to invert the income tax function rather than create a new function (so that changes to the income tax function will not require changes to the inverse function).

Taxable income (i.e. the function's output) may be assumed to be nonnegative integer.

The function requires the use of the grattan package (as well as data.table)

require(grattan) || devtools::install_github("HughParsonage/grattan")
require(data.table)

My initial attempt was a basic while loop:

inverse_income_while <- function(tax, fy.year = "2012-13"){
  income <- 0L
  while(grattan::income_tax(income, fy.year = fy.year) <= tax){
    income <- income + 1000L
  }

  income <- income - 999L

  while(grattan::income_tax(income, fy.year = fy.year) <= tax){
    income <- income + 1L
  }

  return(income)
}

This function only works on a length-one input. To extend this to a vector, I used a lookup table and a rolling join. I also account for the one-to-many property of the income_tax function below the tax-free threshold (e.g. for 2012-13, $18,200 although technically above due to offsets) through an option zero.tax.income.

My concerns are

speed
the use of the 3.79 magic number
the use of the ifelse function (which lineprof suggests is a bottleneck) in order to ensure temporary invertibility.

inverse_income_lookup3 <- function(tax, fy.year = "2012-13", zero.tax.income = "maximum"){
  # This function creates a lookup table of incomes taxes
  zeroes <- tax == 0
  # We now designate the range of incomes to search over.
  # Always check up to $100,000. There, the ratio of income to
  # tax is at most 3.79 and decreases thereafter (2012-13).
  income.range <- seq(0L, max(ceiling(max(tax) * 3.79), 100000L), by = 1L)
  input <- data.table::data.table(taxes = ifelse(zeroes, 1, tax))  # ensure a one-to-one relationship
  temp <- data.table::data.table(incomes = income.range)
  temp$taxes <- grattan::income_tax(temp$incomes, fy.year = fy.year)
  data.table::setkey(temp, taxes)
  # tbl <- temp[input, roll=-Inf]  # LOOCF, all taxes are invertible
  tbl <- data.table:::`[.data.table`(temp, input, roll=-Inf)

  out <- tbl$incomes
  # Take care of zeroes
  if(any(zeroes)){
    if (zero.tax.income == "zero"){
      out[zeroes] <- 0L
    } else {
      if(is.numeric(zero.tax.income)){
        out[zeroes] <- zero.tax.income
      } else {
        max.zero.tax.income <- inverse_income_while(0, fy.year = fy.year) - 1
        if (zero.tax.income == "maximum"){
          out[zeroes] <- max.zero.tax.income
        } else {
          if(zero.tax.income == "uniform")
            out[zeroes] <- sample(0:max.zero.tax.income, size = sum(zeroes))
        }
      }
    }
  }
  return(out)
}


texts:
I have the following program and it's working as I had hoped but now I would like to tidy up the code, putting bits into new methods, so I'm not left with loads of code in the main method. I'm new to Java, so don't know how to go about this.

I have the following methods:

    public String getInventoryCode()
{
    return inventoryCode;
}

  public int getQuantityInStock()
{
    return quantityInStock;
}

public int getDailyDemand()
{
    return dailyDemand;
}

  public int getReOrder()
{
    return reOrder;
}

public int getLeadTime()
{
    return leadTime;
}

*/ Would like to use these */

*/ Would like to use instead of quantityIn -= item_1.getDailyDemand() in main method */

public void removeDailyDemand(){

    quantityInStock -= dailyDemand;
}

*/ Would like to use instead of quantityIn < reOrderThreshold  */

public void newDeliveryIn(){
    ;
}

*/ Would like to use instead of quantityIn += item_1.getReOrder() in main method */

public void isReOrderPoint(){
    ;
}

The bottom three methods I have made as I want to use them but I'm not exactly sure how, so they aren't currently doing anything, I have got all the rest to function as I had hoped.

Here is the main code:

/* Create new item - Inventory Code, Starting Quantity In Stock, Daily Demand, Re-order Amount, Time in Transit (Lead-time) */

    StockItem item_1 = new StockItem("A654Y", 1000, 50, 500, 5);

    /* Column titles */

            System.out.println("Day" + "\t" + "Stock" + "\t" + "Order Status");
            System.out.println("");

            /*Variables */

    int reOrderThreshold = 600;
    int orderTravelTime = 0;
    boolean orderInTravel = false;
    int quantityIn = item_1.getQuantityInStock();

    /* For loop to count 50 days */

    for (int n = 1; n <= 50; n++) {
        String out = "";

        /* Remove daily demand from current stock */
        quantityIn -= item_1.getDailyDemand();

        out += n;
        out += " " + "\t" + quantityIn + "\t";

        /* If order has been ordered and has not arrived */

        if (orderInTravel && orderTravelTime < item_1.getLeadTime()) {

            orderTravelTime++;

                            out += "In Transit -" + "\t";

        /* If ordered and has arrived */

        } else if (orderInTravel && orderTravelTime >= item_1.getLeadTime()) {
            orderTravelTime = 0;
            orderInTravel = false;

                            quantityIn += item_1.getReOrder();
                            out += "New Stock Delivered (" + item_1.getReOrder()")   and Will be Added to Quantity in Stock the Next Day";

        }
                    /* If stock gets too low, order */

        if (quantityIn < reOrderThreshold) {
            orderInTravel = true;

            out += "Ordered";
        }

                    /* Print out results */

        System.out.println(out);
    }

Here is part of the output:

Day   Stock   Order Status

1     950
2     900
3     850
4     800
5     750
6     700
7     650
8     600
9     550 Ordered
10    500 In Transit -    Ordered
11    450 In Transit -    Ordered
12    400 In Transit -    Ordered
13    350 In Transit -    Ordered
14    300 In Transit -    Ordered
15    250 New Stock Delivered (500) and Will be Added to Quantity in Stock the Next Day
16    700
17    650
18    600
19    550 Ordered
20    500 In Transit -    Ordered
21    450 In Transit -    Ordered
...


texts: If statement, is the shortened version readable enough?

texts:
I have to perform an IF statement in my Javascript code. I utilised the first method shown below:

(someVar1 !== "someString") && (someVar2[i].disabled = (someVar3.find("." + someVar4).length == 0));

Is the shortening of an if like this ok to do if my code is to be viewed by other members of my team? I have been told that it is a bit unclear and should instead use something like the following instead:

if (someVar1 !== "someString") {
  var bool = someVar3.find("." + someVar4).length == 0;
  someVar2[i].disabled = bool;
}

What are people's thoughts on this? Was it reasonable for me to implement the first method? Was it fair for me to be told I should change it and not use the (someVar) && doThis version of an if?


texts: Responsive search bar implementation using OOCSS

texts:
I am implementing a search bar here. I have finished basic UI. I have been recently developed a taste for scalable and robust HTML/CSS. Therefore I am closely following things like BEM and OOCSS

Am I on the right path? Also, how can I make the UI responsive?

index.html

  <form class="search-box">

    <input class="search-box-input" type="text" placeholder="Search"/>

      Foo Bar

  </form>

app.css

* {
  margin: 0;
  box-sizing: border-box;
  font-family: 'Roboto', sans-serif;
}

body {
  background: #343d46;
}

#container {
  width: 500px;
  margin: auto;
  margin-top: 30px;
  background: gray;
  color: black;
}

.search-box {
  width: 100%;
  position: relative;
  background: inherit;
  color: inherit;
  height: auto;
}

.search-box:hover .icon-search {
  opacity: 1;
}

.search-box-input {
  background: inherit;
  color: inherit;
  height: 50px;
  font-size: 18px;
  width: 100%;
  padding: 10px;
  padding-left: 40px;
  display: inline-block;
  border: none;
}

.search-box-input:focus {
  outline: none;
}

.search-box-icons {
  position: absolute;
  display: inline-block;
  margin: auto;
  top: 16px;
  left: 10px;
  width: auto;
}

.icon-search {
  color: inherit;
  font-size: 16px;
  display: inline;
  cursor: pointer;
  opacity: 0.4;
}

.search-box-autocomplete {
  position: absolute;
  background: #fff;
  width: 100%;
  margin: 0;
  border-top: 1px solid gray;
}


texts:
This is my first game and I'm really proud of it, but I think it's horribly messy. Is there any way to improve it?

#HANGMAN

# Valid Word Checker

def valid_word(word):

    ill_chars = ["!","@","#","$","%","^","&","*","(",")",",",".", " ","1","2","3","4","5","6","7","8","9","0"]
    for i in word:
        if i in ill_chars:
            print(f"\nError: It must be a letter. No symbols, numbers or spaces allowed. \n\n '{i}' is not allowed\n")
            return False
    if len(word) > 12:
        print("\n\nError: Word is too long. Use a word with eight characters or less.")
        return False
    return True

word_list = []
spaces = []
guessed_letters = []

ill_chars = ["!","@","#","$","%","^","&","*","(",")",",",".", " ","1","2","3","4","5","6","7","8","9","0"]

head ="    O"
armL = "   /"
torso = "|"
armR = "\\"
legL = "/"
legR = " \\"

hangman_parts = [head, armL, torso, armR, legL, legR]
hangman_progress = ["",
                    "|",
                  "\n|",
                  "\n|"]

hangman_final = ["|~~~~|\n"]

# Check if word is valid

wordisValid = False
while True:
    word = input("\n\n\nChoose any word\n\n\n").lower()
    if valid_word(word) == True:
        wordisValid = True
        break
    else:
        continue

# Add to list
for i in word:

    word_list.append(i)
    spaces.append("_ ")

# Main Game Loop
bad_letter = 0

while wordisValid == True:

    print("".join(hangman_final))
    print("\n\n\n\n")
    print("".join(spaces))
    print("\n\nThe word has: " + str(len(word)) + " letters.")
    print("\nYou've tried the following letters: " + "\n\n" + "".join(guessed_letters) + "\n\n")

    # Winning Loop

    if "".join(spaces) == word:
        print(f"YOU WIN! The word was: {word}")
        break
    # Choose Letters

    player_guess = input("\n\nPlease choose a letter: \n\n\n\n").lower()
    guessed_letters.append(" " + player_guess)

    if player_guess in ill_chars:
        print(f"\nError: It must be a letter. No symbols, numbers or spaces allowed. \n\n '{player_guess}' is not allowed\n")
    elif len(player_guess) > 1:
        print("\nError: You must use one letter.\n")
    elif player_guess == "":
        print("\nError: No input provided.\n")

    # Wrong Letter
    elif player_guess not in word_list:

        bad_letter += 1

        if bad_letter == 1:
            hangman_final.append(hangman_progress[1] + head)

        elif bad_letter == 2:
            hangman_final.append(hangman_progress[2] + "    " + torso)

        elif bad_letter == 3:
            hangman_final.pop(2)
            hangman_final.append(hangman_progress[2] + armL + torso)

        elif bad_letter == 4:
            hangman_final.pop(2)
            hangman_final.append(hangman_progress[2] + armL + torso + armR)

        elif bad_letter == 5:
            hangman_final.append(hangman_progress[3] + "   " + legL)

        elif bad_letter == 6:
            hangman_final.pop(3)
            hangman_final.append(hangman_progress[3] + "   " + legL + legR)
            print("\n\nThe word was: " + word)
            print("\n\n\n\n\n\n\n" + "".join(hangman_final))
            print(" YOU GOT HUNG ")
            break

        print("".join(hangman_final))
        print("\n\n\n\n")
        print("".join(spaces))
        print("\n\nThe word has: " + str(len(word)) + " letters.")
        print("\nYou've tried the following letters: " + "\n\n" + "".join(guessed_letters) + "\n\n")
        print(f"\n\n\n{player_guess} is not in the word. Try again.\n\n")

    # END GAME
    if bad_letter == 6:
        break

    # Add letters guessed to a list
    counter = 0
    for i in word:

        if player_guess == i:
            spaces[counter] = player_guess
        counter += 1

Even though it's working, I'm not sure that I have the right idea when it comes to making this type of project.


texts: Redirect incoming traffic based on referrer or random number

texts:
This working script directs incoming traffic to different locations depending on the value present in the session for referring URI. If there is a present value, it sends the user back to their original location. If not, then a random number is generated, checked against and used to direct the visitor to one of two possible locations, each with a likelihood of 50%.

It satisfies the basic requirement but I'm wondering if there might not be a better approach.

We have two sub directories, each one with a file within it, and one file at the root. Traffic generally hits the files in the sub dirs, but I wanted to create a root file to handle an event where a user might strip out everything in the URL but the domain.

Each of the files in the sub dirs use this logic to set the referrer:

function strleft($s1, $s2) {
    return substr($s1, 0, strpos($s1, $s2));
}
function selfURL() {
    if(!isset($_SERVER['REQUEST_URI'])) {
       $serverrequri = $_SERVER['PHP_SELF'];
    } else {
       $serverrequri = $_SERVER['REQUEST_URI'];
    }
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
    $_SESSION['ref'] = $protocol."://".$_SERVER['SERVER_NAME'].$port.$serverrequri;
}
selfURL();

The file at the root uses this logic to direct traffic:

$refurl = $_SESSION['ref'];
if (isset($refurl)) {
    header("Location: " . $refurl);
} else {
    $loc1 = "dir1/file.php";
    $loc2 = "dir2/file.php";
    $num = mt_rand(1, 100);
    if ($num > 50) {
        header("Location: " . $loc1);
    } else {
        header("Location: " . $loc2);
    }
}


texts:
I create blog posts as blog1.php...blog20.php...blog500.php etc and redirect users from blog.php (code below) to the most recent blog post as determined by the blog post with the highest number in the filename.

Here's how I'm doing it, but I have the sense this could be much cleaner and more elegant:

$directory = "/var/www/html";
$scanned_directory = array_diff(scandir($directory), array('..', '.'));

$blogNumbers = Array();
foreach($scanned_directory as $file){
        if(preg_match("/blog(?<digit>[0-9]+)/", $file, $matches)){
                foreach($matches as $match){
                                 if(is_numeric($match["digit"])) array_push($blogNumbers, $match["digit"]);
                                     //had to put this numeric check in because otherwise
                                     //script was pushing some 'b's onto array
                                 }
        }

}

$currentBlog = max($blogNumbers);
header('Location: http://www.sunnysideworks.nyc/Simply-Run/blog'.$currentBlog);
die();

People are always complaining that bad programming is too easy in PHP, and I suspect what I've posted is just that easy bad programming that makes people mad. Can someone tell me how to make this more PHP-like and more elegant? I've worked much more in Python, but I'd like to be less of a hack in PHP.


texts: Computing divisibility and multiplication

texts:
Please check my Java program to see if I use the global variables, nested loops and two functions with parameters correctly. I would also like any suggestions to improve my program.

import java.util.*;
public class javaProgram {

    public static int loopCount = 0;
    static Scanner scanner = new Scanner(System.in);

    public static void div(int n) {
        for (int i = 1; i <= n; i++) {
                System.out.print("The number " + i + " is divisible by:");
                for (int j = 1; j <= i; j++) {
                    if ((i % j) == 0)
                        System.out.print(" " + j);
                    loopCount++;
                }
                System.out.println();
            }
       }

     private static void mul(int n) {
                System.out.println();
                System.out.println("Multiplication table for "+n);
                System.out.println("---------------------------");
                for(int i = 1; i<=10;i++) {
                    System.out.format("%2d x %d = %3d\n", i,n,i*n);
                    loopCount++;
                }
     }

     public static void main(String[] args) {
            System.out.println("Let's compute for divisible and multiplication!");
            System.out.print("Enter number of integers: ");
            int number = scanner.nextInt();
            div(number);
            mul(number);
            System.out.println();
            System.out.println("Loop count " + loopCount);
        }

}


texts:
I want to get table names and column names from queries in a dataframe. The dataframe is like this:

Date         Query
29-03-2019   SELECT * FROM table WHERE ..
30-03-2019   SELECT * FROM ... JOIN ... ON ...WHERE ..
....         ....
20-05-2019   SELECT ...

and I run function to that dataframe to get tablename from the queries.

import sqlparse
from sqlparse.tokens import Keyword, DML

def getTableKey(parsed):
    findFrom = False
    wordKey = set(
        [
            "FROM",
            "JOIN",
            "LEFT JOIN",
            "INNER JOIN",
            "RIGHT JOIN",
            "OUTER JOIN",
            "FULL JOIN",
        ]
    )
    for word in parsed.tokens:
        if word.is_group:
            yield from getTableKey(word)
        if findFrom:
            if isSelect(word):
                yield from getTableKey(word)
            elif word.ttype is Keyword:
                findFrom = False
                StopIteration
            else:
                yield word
        if word.ttype is Keyword and word.value.upper() in wordKey:
            findFrom = True

def getTableName(sql):
    tableReg = re.compile(r"^.+?(?<=[.])")
    tableName = []
    query = sqlparse.parse(sql)
    for word in query:
        if word.get_type() != "UNKNOWN":
            stream = getTableKey(word)
            table = set(getWord(stream))
            for item in table:
                tabl = tableReg.sub("", item)
                tableName.append(tabl)
    return tableName

Also, I run function to get columnname from queries.

def getKeyword(parsed):
    kataKeyword = set(["WHERE", "ORDER BY", "ON", "GROUP BY", "HAVING", "AND", "OR"])
    from_seen = False
    for item in parsed.tokens:
        if item.is_group:
            yield from getKeyword(item)
        if from_seen:
            if isSelect(item):
                yield from getKeyword(item)
            elif item.ttype is Keyword:
                from_seen = False
                StopIteration
            else:
                yield item
        if item.ttype is Keyword and item.value.upper() in kataKeyword:
            from_seen = True

def getAttribute(sql):
    attReg = re.compile(r"asc|desc", re.IGNORECASE)
    namaAtt = []
    kueri = sqlparse.parse(sql)
    for kata in kueri:
        if kata.get_type() != "UNKNOWN":
            stream = getKeyword(kata)
            table = set(getWord(stream))
            for item in table:
                tabl = attReg.sub("", item)
                namaAtt.append(tabl)
    return namaAtt

But as this is my first try, I need an opinion about what I've tried, because my code runs slowly with a large file.


texts: Extracting the src attribute and content of  tags in HTML files in a directory

texts:
I have a program which parse HTML content to get a script src attribute and script attribute. A function have directory (contain HTML files) as input and extract to other directory as output.

However, I think my code is not clean. The following is my code.

def extract_int_js(src, dst):

    for file in os.listdir(src):
        filepath = os.path.join(src, file)
        with open(filepath) as f:
            html = f.read()
        parser = HtmlParser(html)

        for text in parser.script_text:
            yield text

def extract_src_js(src, dst):
    for file in os.listdir(src):
        filepath = os.path.join(src, file)
        with open(filepath) as f:
            html = f.read()
        parser = HtmlParser(html)

        for src in parser.src:
            yield src

Do you have any solution to improve this code since there are duplicated line in 2 functions.


texts:
To practice around with C++11 smart pointers I was trying to implement a simple Queue to go beyond a simple Linked List. The fact that the _first and _last nodes are pointed to twice at runtime made me decide to implement them as shared_ptr.
I was wondering if this was the correct way to implement the data structure.

#include <iostream>
#include <memory>

template <class T>
class Queue
{
private:
    class Node
    {
    public:
        const T _data;
        std::shared_ptr<Node> _next;
        Node(const T& t) : _data{ t } {}
    };

    std::shared_ptr<Node> _first;
    std::shared_ptr<Node> _last;
    unsigned _size;
public:
    Queue() : _size{ 0 }, _first { nullptr }, _last{ nullptr } {}
    ~Queue() {}
    void add(const T& item);
    const T remove();
    const unsigned size();
    const T peek();
    bool isEmpty();
};

template <class T>
bool Queue<T>::isEmpty()
{
    return _first == nullptr;
}

template <class T>
void Queue<T>::add(const T& item)
{
    std::shared_ptr<Node> new_end = std::make_shared<Node>(item);
    if (_last)
    {
        _last->_next = new_end;
    }
    _last = new_end;
    if (!_first)
    {
        _first = _last;
    }
    ++_size;
}

template <class T>
const T Queue<T>::remove()
{
    if (_first == nullptr) return NULL;
    auto ptr = std::move(_first);
    _first = ptr->_next;
    if (!_first)
    {
        _last.reset();
    }
    T val = ptr->_data;
    ptr.reset();
    --_size;
    return val;
}

template <class T>
const unsigned Queue<T>::size()
{
    return _size;
}

template <class T>
const T Queue<T>::peek()
{
    if (_first) return _first->_data;

    return NULL;
}


texts:
I'm having a ListView which contains some users. This ListView is used to select users which should be added to a new group chat.

When I tap on an element in the list, it feels not good because it doesn't instantly visually update the CheckBox of this element to be checked/unchecked.

Additionally, I have a "Select All" element at the top of the list. If tapped, all users will be selected (or deselected if every user is already selected). This also needs 1-2 seconds until all checkboxes are visually updated.

Can I achieve a better UX here?

ViewModel code:

public void OnUserTapped(UserDto userDto)
{
    if (userDto != null)
    {
        if (userDto.status == "alleListElement")
        {
            OnAlleToggled();
        }
        else
        {
            PageItem.Users.FirstOrDefault(u => u.openId == userDto.openId).isSelected = !userDto.isSelected;
            PageItem.Users = new ObservableCollection<UserDto>(PageItem.Users); // Needed so that the CheckBoxes visually updates
        }
    }
}

public void OnAlleToggled()
{
    bool isToggled = true;
    if (PageItem.Users.FirstOrDefault(u => u.isSelected == false) == null)
    {
        isToggled = false;
    }
    foreach (UserDto user in PageItem.Users)
    {
        user.isSelected = isToggled;
    }

    PageItem.Users = new ObservableCollection<UserDto> (PageItem.Users);
}

I tried to access the ViewCells of the ListView directly. This is very fast and offers a good UX:

private void Handle_OnUserTapped(object sender, EventArgs e)
{
    var grid = sender as Grid;
    var userDto = grid.BindingContext as UserDto;
    //_addParticipantsPageViewModel.OnUserTapped(userDto);

    if (userDto.status == "alleListElement")
    {
        // TODO... Can't access all ViewCells of the ListView because ListView.TemplatedItems is internal
    }
    else
    {
        OneCheckbox checkbox = GetCheckBoxFromGrid(grid.Children) as OneCheckbox;
        checkbox.IsChecked = !checkbox.IsChecked;
    }
}

But I know that it's bad code to access a ViewCell directly and I usually handle stuff like this in the ViewModel. Is this acceptable for the sake of performance? Also, I don't know if it's possible to get access to all ViewCells of the ListView. ListView.TemplatedItems is internal...


texts: Simple exchange calculator in Java - structure and tests

texts:
I am trying to learn how to correctly structure my projects and write a good, clean code. I would also like to learn how to write good tests. Can you please review it and give me some tips and tricks how to make that better?

The application is calculating the exchange from the bill for lemonade. Lemonade costs 5$ and client may pay with 5$, 10$ or 20$. At the beginning there is no change available.

Project structure

My project structure is as follows:

LemonadeChange (project) with src package and 4 packages inside:

app (contains Main)
calculatorImp (contains CalculatorLongImp and CalculatorShortImp)
calculatorInterface (contains CalculatorInterface)
test (contains CalculatorTest)

Classes

Main

public class Main {

    public static void main(int[] args) {
        CalculatorInterface calc = new CalculatorLongImp();
        calc.lemonadeChange(args);
    }
}

CalculatorInterface

public interface CalculatorInterface {

    public boolean lemonadeChange(int[] bills);
}

CalculatorLongImp

public class CalculatorLongImp implements CalculatorInterface {
    private int five = 0;
    private int ten = 0;
    int acc = 0;

    public boolean lemonadeChange(int[] bills) {
        for (int bill : bills) {
            if(bill == 5) {
                five++;
            }
            else if(bill == 10) {
                five--;
                ten++;
            }
            else {
                if(ten >= 1 && five >= 1) {
                    ten--;
                    five--;
                }
                else if (five >= 3) {
                    five -= 3;
                }
                else {
                    acc++;
                }
            }
        }

        if(acc == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}

CalculatorTest

public class CalculatorTest {

    @Test
    public void testAllChangeShouldBePossibleToGive() {
        int[] bills = {5,5,5,10,20};
        CalculatorInterface calc = new CalculatorLongImp();
        assertTrue(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertTrue(calc.lemonadeChange(bills));
    }

    @Test
    public void testAllChangeShouldNotBePossibleToGive() {
        int[] bills = {20};
        CalculatorInterface calc = new CalculatorLongImp();
        assertFalse(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertFalse(calc.lemonadeChange(bills));
    }

    @Test
    public void testAllChangeShouldNotBePossibleToGiveSecond() {
        int[] bills = {10, 20};
        CalculatorInterface calc = new CalculatorLongImp();
        assertFalse(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertFalse(calc.lemonadeChange(bills));
    }

    @Test
    public void testAllChangeShouldBePossibleToGiveSecond() {
        int[] bills = {5, 5, 10, 20};
        CalculatorInterface calc = new CalculatorLongImp();
        assertTrue(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertTrue(calc.lemonadeChange(bills));
    }

    @Test
    public void testAllChangeShouldNotBePossibleToGiveThird() {
        int[] bills = {10, 20, 5, 5};
        CalculatorInterface calc = new CalculatorLongImp();
        assertFalse(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertFalse(calc.lemonadeChange(bills));
    }

    @Test
    public void testAllChangeShouldBePossibleToGiveThird() {
        int[] bills = {5,5,5,5,20};
        CalculatorInterface calc = new CalculatorLongImp();
        assertTrue(calc.lemonadeChange(bills));
        calc = new CalculatorShortImp();
        assertTrue(calc.lemonadeChange(bills));
    }
}

How would you improve that? Any tips and tricks welcomed!

Please let me know if you want to see the task that it solves - that is one of the tasks on LeetCode, so I can post it if that makes review easier.


texts: looking for review of code organization for jQuery/javascript code

texts:
The first block of code is my main app.js that is included on every request. It is essentially a library of functions and objects that include related functions (ie: app.utils) that I can use on other pages like page1.js:

./app.js

var app = window.app || {};

(function($){
    app.req = app.req || {};
    app.utils = app.utils || {};
    app.utils.form = app.utils.form || {};
    app.page = app.page || {};
    app.log = function(msg){
        ( window.console && console.log(msg) );
    };
})(jQuery);

This is a page-level script that is included only on the one page:

./page1.js

(function($){
    $(function(){
        app.log('page1 stuff');
    });
}(jQuery);

I'm wondering what other methods are used for organizing larger codebases, or if there are any inheritly flawed ways using this method.


texts:
This is a Python document (PDF) downloader I made to download some question papers automatically. However, it is very slow. Any better way to do this?

try:
    import urllib2
    from bs4 import BeautifulSoup
    from time import sleep
    import os
    import sys
    from time import sleep
except ImportError:
    print "ImportError !"

url = raw_input('enter the url :')
c = 0

while True:
    path = raw_input("\nGive the directory Name where to save the files with full path :")
    if c == 3:
        if raw_input("you have tried 3 times do you want to create the folder ? (y/n)").lower().startswith('y'):
            os.mkdir(path)
            c = 0
            break
    else:
        if os.path.isdir(path):
            break
        else:
            print "\nEnter Path Carefully !\n"
            c+=1
            continue

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'}

request = urllib2.Request(url,None,headers)
html = urllib2.urlopen(request)
soup = BeautifulSoup(html.read(), "html.parser")
soup.prettify()

#modifying the url for concatonation with
url =  url.split('/')
del url[-1]
url.append('')
url = '/'.join(url)
urls = []
names = []

for anchor in soup.findAll('a', href=True): #Going inside links
    req = urllib2.Request(anchor['href'],None,headers)
    pag = urllib2.urlopen(req)
    pgf = pag.read()
    soup1 = BeautifulSoup(pgf, "html.parser")

    for i, link in enumerate(soup1.findAll('a')): # Download all pdf inside each link
        fullurl = url + str(link.get('href'))
        #print fullurl

        if fullurl.endswith('.pdf'):
            #print fullurl
            urls.append(fullurl)
            names.append(soup1.select('a')[i].attrs['href'])

names_urls = zip(names, urls)
os.chdir(path)

for name, url1 in names_urls:
    try:
        if os.path.isfile(name):
            print name, "Already exists skipping..."
            pass
        else:
            rq = urllib2.Request(url1)
            res = urllib2.urlopen(rq)
            with open(name, 'wb') as pdf:
                pdf.write(res.read())
            print name, "Downloaded"
    except:
        print name, "Failed to download"
        pass
    sleep(1)


texts:
I am new to using Python and the following is the first script that I have written. I will execute a test complete project and will be started via team city. Once test execute has been called - the log file needs to be processed for consumption through TeamCity.

import sys
import argparse
import subprocess
import os.path

parser = argparse.ArgumentParser()
parser.add_argument("-s", "--projectSuite", help=".pjs that you want to execute", type=str)
parser.add_argument("-p", "--project", help=".pj that you want to execute", type=str, default="ExploratoryTests")
parser.add_argument("-l", "--logDirectory", help="The directory to log the mht's too", type=str, default="C:\TestLogs")
parser.add_argument("-lf", "--logFile", help="The name of the log", type=str, default="TextExecuteLog.mht")
parser.add_argument("-ps", "--psexec", help="Absolute path to psexec", type=str, default="c:\Program Files (x86)\PsTools\PsExec.exe")
parser.add_argument("-te", "--testExecute", help="Absolute path to testExecute", type=str, default="c:\Program Files (x86)\SmartBear\TestExecute 9\Bin\TestExecute.exe")
parser.add_argument("-m", "--mhtExtractor", help="Absolute path to an mht extractor", type=str, default="C:\extract2htm\extractMHT.exe")

#Get the args that are passed in
args = parser.parse_args()

#Make sure we have an absolute path
suite = os.path.abspath(args.projectSuite)

#Prepare the project for consumption by TestExecute
project = "/p:" + args.project

#Get a path for the currenct mht
logFile = os.path.abspath(os.path.join(args.logDirectory, args.logFile))

#Tell TestExecute where to put the log
log = "/exportlog:" + logFile

#prepare TE Executables
psexec = os.path.abspath(args.psexec);
testExecute = os.path.abspath(args.testExecute)

#Execute testExecute through psexec
testExecuteCommand = [psexec,"-i" ,"-accepteula", testExecute, suite, project, "/exit", log, "/r", "/DoNotShowLog", "/SilentMode"]

#Blank array to hold the TE outcome
testExecuteError = [];

try:
    result = subprocess.run(args = testExecuteCommand, stderr=subprocess.STDOUT, shell=True)
    result.check_returncode()
    testExecuteError.append(result)
except subprocess.CalledProcessError as e:
    result = e.returncode
    testExecuteError.append(e)
    print("Error code: {0}".format(result))

extractor = os.path.abspath(args.mhtExtractor)
outputDir = os.path.join(args.logDirectory)

extractorExecuteCommand = [extractor, logFile, outputDir]

try:
    result = subprocess.run(args = extractorExecuteCommand, stderr=subprocess.STDOUT, shell=True)
    result.check_returncode()
except subprocess.CalledProcessError as err:
    result = err.returncode
    print("Error code: {0}".format(result))

#exit the script with the exit code from testexetute
sys.exit(testExecuteError[0])

The way in which I handle my exceptions from testExecute are the part that I'm not happy about but it is working as intended. Any suggestions are welcome.


texts: Optimizations for Knapsack with 3 dimensions

texts:
Problem Statement:

I am given a set of prices for \$n\$ items I have to find out what is the maximum value I can get with \$M\$ money by selecting exactly \$C\$ items without exceeding the amount of money I have. Obviously \$C \leq N\$.

Solution:

The code for the above problem is developed using the suggestions taken from here. The code in java is given below:

public class KnpMD {

    public static void main(String[] args) {

        int items[] = {4,6,9,10};
        int M = 12;
        int C = 2;

        int dp[][][] = new int[items.length+1][M+1][C+1];

        for(int i = 0; i < items.length+1; i++) {
            for(int j = 0; j < M+1; j++) {
                for(int k = 1; k <= C; k++) {
                    dp[i][j][k] = -1;
                }
            }
        }

        for(int i = 0; i < items.length; i++) {
            for(int j = 1 ; j < M + 1; j++) {

                for(int k = 1; k <= C; k++) {

                    dp[i+1][j][k] = dp[i][j][k];// to Copy all previous optimal states found.

                    if(items[i] > j)
                        continue;

                    if(dp[i][j-items[i]][k-1] != -1)
                        dp[i+1][j][k] = Math.max(dp[i+1][j][k],
                                dp[i][j-items[i]][k-1] + items[i]);
                }
            }

        }

        System.out.println(dp[items.length][M][C]);
    }
}

What are some of the improvments I can add to this code?  I am unable to follow the optimzations suggested in the answer linked above.

Can someone tell me what is the meaning of the statement(linked in the above answer)

  In the preceding formulae, we retrieved the optimal solution which
  consisted of no more than (k−1)(k−1) items among the first (j−1)(j−1)
  as Ti,j−1,k−1Ti,j−1,k−1. However, it should be clear that this is
  precisely equal to maxp=0,j−1{Ti,p}maxp=0,j−1{Ti,p} just by using the
  original table!! ie., the optimal solution with no more than kk items
  can be also retrieved by considering the optimal solutions with 1
  item, 2 items, 3 items, ... (j−1)(j−1) items ...

Any other improvments would be greatly appreciated.


texts: Correct Way to Retrieve Header Records With Filtered Detail Records

texts:
I wrote this in LinqPad. It works. The whole point was to retrieve header records, and only include some detail records. I'm looking for possible improvements to this, specifically around the anonymous type part. The only way I was able to get this to work as to use an anonymous type, then create the ToEntitySet() extension method to convert the detail rows. I just feel like I'm making this harder than it is. But maybe not? Any comments are welcome.

void Main()
{
    var query =
        from header in AccountHeader
        join detail in AccountDetail
            on header.AccountHeaderId equals detail.AccountHeaderId
            into groupedDetails
        where groupedDetails.Any(x => x.Status == "status2")
        select new
        {
            Account = header,
            AccountDetail = groupedDetails.Where(x => x.Status == "status2")
        };

    foreach (var item in query)
    {
        var account = item.Account;
        account.AccountDetail = item.AccountDetail.ToEntitySet();
        account.Dump();
    }
}

public static class Extensions
{
    public static EntitySet<T> ToEntitySet<T> (this IEnumerable<T> source) where T : class
    {
        var entitySet = new EntitySet<T> ();
        entitySet.AddRange (source);
        return entitySet;
    }
}


texts:
This is the code I came up with.It seems correct.

I am interested in:
1) Improvements on code
2) How can it be better than this? i.e. this is O(N^2) Could I have done better in complexity? What should I have read to do it?

Thanks

 public int lengthOfLongestSubstringNoRepetitions(String s) {

            if(s == null || s.trim().equals(""))
                return 0;

            Map<Character,Boolean> seen = new HashMap<Character,Boolean>();

            int max = Integer.MIN_VALUE;

            for(int i = 0; i < s.length(); i++){
                for(int j = i; j < s.length(); j++){
                    char c = s.charAt(j);
                    if(seen.containsKey(new Character(c))){
                        //duplicate in substring
                        int tmp = j - i;
                        if(max < tmp) max = tmp;
                        break;
                    }
                    else{
                        seen.put(new Character(c),true);
                        if(j == s.length() -1){
                            //Reached the end of string.Add one to get the range
                            if(max < (j - i + 1)) max = (j - i + 1);
                        }
                    }
                }
                seen.clear();
            }

            return (max == Integer.MIN_VALUE)?s.length():max;

        }


texts: Refactoring asynchronous JS pre-rendering code

texts:
A few months ago I wrote this module but, coming back to it, I find it a bit hard to read and reason about. I want to ask community's opinion on whether this needs to be refactored, and how I could approach this.

(function (q) {

  'use strict';

  var DELAY_BEFORE_RENDERING_NEXT_PAGE_VIEW = 3 * 1000;

  window.st.viewer.Helper.PageViewFactory = (function () {
    function promiseRenderView(page, token) {
      return page.fetchUnlessReady()
        .then(token.throwIfCanceled)
        .then(function () {
          var view = new window.st.viewer.View.PageView({
            model: page
          });

          view.render();
          return view;
        });
    }

    var scheduledPage,
        scheduledPromise;

    function scheduleRenderNextView(page, token) {

      // After some time passes, prefetch and prerender next page view
      // so if it is requested (very likely), we can re-use an existing promise.

      scheduledPage = null;
      scheduledPromise = null;

      q.delay(DELAY_BEFORE_RENDERING_NEXT_PAGE_VIEW)
        .then(token.throwIfCanceled)
        .then(function () {
          return page.promiseNext();
        })
        .then(token.throwIfCanceled)
        .then(function (nextPage) {
          if (nextPage) {
            scheduledPage = nextPage;
            scheduledPromise = promiseRenderView(nextPage, window.st.Helper.CancellationToken.getNone());
          } else {
            scheduledPage = null;
            scheduledPromise = null;
          }
        })
        .catch(token.catchItself)
        .done();
    }

    function scheduleRenderView(page, token) {
      var promise = (page !== scheduledPage) ?
        promiseRenderView(page, token) :
        scheduledPromise;

      scheduleRenderNextView(page, token);

      return promise;
    }

    return {
      scheduleRenderView: scheduleRenderView
    };
  })();
})(Q);

This module exports a single function called scheduleRenderView. Its purpose is, given a page model and a cancellation token, do the following steps asynchronously:

Fully fetch page model (it may be loaded partially);
Create and render (in memory) a PageView for it;
Return this view to the caller;
Additionally, after a 3 second delay:

Request next page by calling promiseNext;
Pre-render next page by repeating steps 1-3 for it and store the pre-rendered view in case it gets requested the next time scheduleRenderView is called (very likely)

The user views pages one by one, and I wanted to anticipate the most likely scenario where she will request the next page.

I also wanted to make this optimization invisible to the calling code.

Is this code hard to comprehend? Are the simpler ways to achieve the same?