texts:
I have made a basic stack class utilizing a linked list for data storage and \$O(1)\$ push and pop and just want some basic feedback on the class to see if there is anything basic I missed. It seems to be working perfectly and I know there are no memory leaks. I'm just being cautious and wondering if there is one or two big things I am missing or doing wrong.

template <typename T>
class Stack {
public:
  struct Node {
    T data;
    Node *next = nullptr;
    Node(T data) : data(data) {}
    Node(T data, Node *next) : data(data), next(next) {}
  };
  Node *top;
  int size_;

  Stack() : size_(0), top(nullptr) {}

  bool empty() {
    return top == 0;
  }

  void push(T data) {
    if(empty()) {
      top = new Node(data);
      size_++;
    } else {
      top = new Node(data, top);
      size_++;
    }
  }

  T pop() {
    if(!empty()) {
      T ret = top->data;
      Node *tmp = top->next;
      delete top;
      top = tmp;
      size_--;
      return ret;
    }

    return -1;
  }

  int size() {
    return size_;
  }

  ~Stack() {
    if(empty()) return;

    if(size_ == 1) {
      delete top;
      return;
    }

    Node *current = top;
    Node *next;
    while( current != 0 ) {
        next = current->next;
        delete current;
        current = next;
    }
    top = nullptr;

  }

};


texts: Simple JavaScript precondition checking implementation

texts:
I am writing a JavaScript application and would like to validate function arguments in many places.  Most of these checks will be for correct argument types, or numeric values within specific ranges.

Here is a simple function I came up with to check any number of preconditions:

function requires(conditions)
{
    for (var cond in arguments)
    {
        if (typeof cond !== "boolean") throw "Preconditions must be boolean expressions {" + cond + "}";
        if (cond !== true) throw "Precondition failed {" + cond + "}";
    }
}

It would be used like this:

function alertChar(message, index)
{
    requires(
        typeof message === "string",
        typeof index === "number",
        index >= 0,
        index < message.length);

    alert(message.charAt(index));
}

Is there anything conceptually wrong with this simple implementation?  Is there a way I can make it lazily evaluate each precondition expression?  Is accessing the arguments array inefficient?


texts: Polling an SFTP server to list files in a directory

texts:
When is it better to instantiate the sftp client globally vs inside a function as shown below? What considerations favor one method over the other?

For a long running service that polls indefinitely, would it better to instantiate globally so I don't need to instantiate a new client on each run?

Also, is there any difference between using Bluebird's Promise.delay(10000) as opposed to wrapping setTimeout like so:

const timeout = async (ms) => new Promise(resolve => setTimeout(resolve, ms));

Finally, my polling function sleeps at the beginning of the function instead of at the end so my finally block frees up the sftp connection without having to wait 10000ms. Seems okay with the current recursive setup but I'm curious if there are "better" ways to write a recurring task.

Instantiate globally

const Client = require('ssh2-sftp-client');
const Promise = require('bluebird');

const sftp = new Client();

const listFiles = async (directory) => sftp.list(`/${directory}`);

const pollSftpServer = async () => {
  try {
    await Promise.delay(10000);
    await sftp.connect({
      host: '127.0.0.1',
      port: '2222',
      username: 'foo',
      password: 'pass',
    });
    const files = await listFiles('upload');
    console.log(files);
    return pollSftpServer();
  } catch (e) {
    console.error('caught error', e);
    return pollSftpServer();
  } finally {
    sftp.end();
  }
};

(() => {
  pollSftpServer();
})();

Instantiating inside a function

const Client = require('ssh2-sftp-client');
const Promise = require('bluebird');

const listFiles = async (sftp, directory) => sftp.list(`/${directory}`);

const pollSftpServer = async () => {
  // Instantiate here?
  const sftp = new Client();
  try {
    await Promise.delay(10000);
    await sftp.connect({
      host: '127.0.0.1',
      port: '2222',
      username: 'foo',
      password: 'pass',
    });
    const files = await listFiles(sftp, 'upload');
    console.log(files);
    return pollSftpServer();
  } catch (e) {
    console.error('caught error', e);
    return pollSftpServer();
  } finally {
    sftp.end();
  }
};

(() => {
  pollSftpServer();
})();


texts:
I wrote a solution to this question. The task is to take an input of n increasing positive integers (1 ≤  n ≤ 2∙105), each entry as large as 109, and find the length of the longest subsequence where each element is no more than double the previous element.

Example input

10
1 2 5 6 7 10 21 23 24 49

Example output

4

… because the longest subsequence is [5, 6, 7, 10].

My solution works for small numbers, but exceeds the time limit for big inputs.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{

 int n,a,c=1,max_count=1;
 cin>>n;
 vector<int>v;
 for(int i=0;i<n;i++)
 {
     cin>>a;
    v.push_back(a);
}
for(int i=0;i<n;i++)
{
    int l=i+1;
    while((l<n)&&(v[l]<=2*v[i]))
    {
        c++;
        l++;
        max_count=max(max_count,c);
    }

    c=1;
}
cout<<""<<max_count;
return 0;
}


texts:
I've written a script in python to parse the name, tweets, following and follower of those people available in view all section in my profile page of twitter. My scraper is able to parse those aforesaid fields flawlessly. Any input on the improvement of my parser will be highly appreciated. Here is what I've written:

from selenium import webdriver
import time

def browsing_pages():

    driver = webdriver.Chrome()
    driver.get('https://twitter.com/?lang=en')

    driver.find_element_by_xpath('//input[@id="signin-email"]').send_keys('username')
    driver.find_element_by_xpath('//input[@id="signin-password"]').send_keys('password')
    driver.find_element_by_xpath('//button[@type="submit"]').click()
    time.sleep(5)

    #Clicking the viewall link
    driver.find_element_by_xpath("//small[@class='view-all']//a[contains(@class,'js-view-all-link')]").click()
    time.sleep(5)

    for links in driver.find_elements_by_xpath("//div[@class='stream-item-header']//a[contains(@class,'js-user-profile-link')]"):
        scraping_docs(links.get_attribute("href"))
        #tracking down each profile links under viewall section

def scraping_docs(item_link):

    driver = webdriver.Chrome()
    driver.get(item_link)

    # gleaning information of each profile holder
    for prof in driver.find_elements_by_xpath("//div[@class='route-profile']"):
        name = prof.find_elements_by_xpath(".//h1[@class='ProfileHeaderCard-name']//a[contains(@class,'ProfileHeaderCard-nameLink')]")[0]
        tweet = prof.find_elements_by_xpath(".//span[@class='ProfileNav-value']")[0]
        following = prof.find_elements_by_xpath(".//span[@class='ProfileNav-value']")[1]
        follower = prof.find_elements_by_xpath(".//span[@class='ProfileNav-value']")[2]
        print(name.text, tweet.text, following.text, follower.text)

        driver.quit()

browsing_pages()


texts: Insert 271 million records from text file to mongodb

texts:
I have 271 million records, line by line in a text file that I need to add to MongoDB, and I'm using Python and Pymongo in order to do this.

I first split the single file containing the 271 million records into multiple files containing each 1 million lines, and have written the current code to add it to the database:

import os
import threading
from pymongo import MongoClient

class UserDb:
    def __init__(self):
        self.client = MongoClient('localhost', 27017)
        self.data = self.client.large_data.data

threadlist = []

def start_add(listname):
    db = UserDb()
    with open(listname, "r") as r:
        for line in r:
            if line is None:
                return
            a = dict()
            a['no'] = line.strip()
            db.data.insert_one(a)
    print(listname, "Done!")

for x in os.listdir(os.getcwd()):
    if x.startswith('li'):
        t = threading.Thread(target=start_add, args=(x,))
        t.start()
        threadlist.append(t)

print("All threads started!")

for thread in threadlist:
    thread.join()

This starts as many threads as there are files, and adds every line to the db as it goes through it. The bad thing is that after 3 hours it had only added 8.630.623.

What can I do to add the records faster?

There are 261 threads currently running.

Example of one row of data: 12345678 (8 digits)


texts: I created a "enum string" container in c++

texts:
The reason I created this is because I wanted my string values to be type safe and I wanted to decrease the amount of bad data that has crept into my system due to hard coded values in the past.  There are different ways to solve this issue, like a lookup table with a key value pair but this is not a direction I can move into at the time.  So here is my design and I would love some feedback.

Here is my working sample: https://onlinegdb.com/rympFKEaf

#include <iostream>

class EnumStringContainer
{
protected:
  EnumStringContainer(const std::string &_str);

public:
  bool operator==(const EnumStringContainer&rhs) const;

public:
  std::string ToString() const;
  const char* ToCharArray() const;

private:
  std::string str;
};

EnumStringContainer::EnumStringContainer(const std::string &_str)
{
   this->str = _str;
}

bool EnumStringContainer::operator==(const EnumStringContainer &rhs) const
{
   return this->ToString() == rhs.ToString();
}

std::string EnumStringContainer::ToString() const
{
   return this->str;
}

const char* EnumStringContainer::ToCharArray() const
{
   return this->str.c_str();
}

// Usage
class Color : public EnumStringContainer
{
private:
    Color(const std::string &color);

public:
    static const Color Red;
    static const Color Blue;
    static const Color Green;
};

// Constructor is private because I don't want new "random" values being created.
Color::Color(const std::string &color) : EnumStringContainer(color)
{
}

const Color Color::Red("Red");
const Color Color::Blue("Blue");
const Color Color::Green("Green");

int main()
{
    Color color = Color::Red;
    return 0;
}


texts:
I am working on my first HTML5/CSS web site and, like all of my first-time projects, they end up cumbersome, crude, and hard to work with when changes need to be made later in the life cycle. I am attaching some code with a small amount of HTML and CSS. I have read up on CSS and HTML and, after quite alot of effort, have ended up with this. Please look at the code and fill me in on any inefficiencies that I may have introduced due to lack of experience. I do feel like I am doing a little bit too much manually right now and this is just a basic web site. Any opinion will be appreciated. FYI: I have left the colors a bit funny in order to easily see changes to the web site.

/*
 Created on : Mar 24, 2014, 9:05:35 AM
 Author     : meggleston
*/
#listheader
{
 position:absolute;
 top:90px;
 width:100%;
 background:cadetblue;
 height: 80px;
 text-align: center;
}

#header
{
 top: 0;
 position: absolute;
 height: 90px;
 width: 100%;
 background: #007400;
 margin: 0px;
 padding: 0px;
}

#logo
{
 position:absolute;
 background-image:url(../assets/pics/logomain.png);
 background-repeat: no-repeat;
 background-re:no-repeat;
 background-position: left top;
 background-size:100px 90px;
 height: 100;
 width: 100;
}

body
{
 margin: 0px;
 padding: 0px;
}

#site1Container
{
 position:absolute;
 background-color: #cd0a0a;
 top:170px;
 width: 100%;
 height: 180px;
}

#site2Container
{
 position:absolute;
 background-color: bisque;
 top:350px;
 width: 100%;
 height: 180px;
}

#site3Container
{
 position:absolute;
 background-color: darkgoldenrod;
 top:530px;
 width: 100%;
 height: 180px;
}

#site1logo
{
 position:absolute;
 top:20%;
 background-image:url(../assets/pics/logo1.png);
 background-repeat: no-repeat;
 background-re:no-repeat;
 background-position: left top;
 background-size:100px 100px;
 height: 100%;
 width: 100;
}

#site2logo
{
 position:absolute;
 top:20%;
 background-image:url(../assets/pics/logo2.png);
 background-repeat: no-repeat;
 background-re:no-repeat;
 background-position: left top;
 background-size:100px 100px;
 height: 100;
 width: 100;
}

#site3logo
{
 position:absolute;
 top:20%;
 background-image:url(../assets/pics/logo3.png);
 background-repeat: no-repeat;
 background-re:no-repeat;
 background-position: left top;
 background-size:100px 100px;
 height: 100;
 width: 100;
}

#site1desc
{
 position: absolute;
 left:150px;
 top: 20%;
}

#site2desc
{
 position: absolute;
 left:150px;
 top: 20%;
}

#site3desc
{
 position: absolute;
 left:150px;
 top: 20%;
}

  <title>Site Title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/basecss.css"/>

List of Web Sites Header

Site description goes here.

Site description goes here.

Site description goes here.


texts:
Do two circles in a 2D plane disjoint?

$$(r_1 + r_2) \cdot (r_1 + r_2) \gt \Delta{X} \cdot \Delta{X} + \Delta{Y} \cdot \Delta{Y}$$

Any comments / corrections on this code?

internal struct HoleInfo
{
    public float Diameter { get; internal set; }
    public float X { get; internal set; }
    public float Y { get; internal set; }
    public HoleInfo(float x, float y, float diameter)
    {
        X = x;
        Y = y;
        Diameter = diameter;
    }
}
static bool HoleOverlap(HoleInfo hole1, HoleInfo hole2)
{
    float holeSize = (hole1.Diameter + hole2.Diameter) / 2;
    float deltaX = hole1.X - hole2.X;
    float deltaY = hole1.Y - hole2.Y;
    return (holeSize * holeSize > deltaX * deltaX + deltaY * deltaY);
}

It is called HoleInfo because the app is concerned if holes drilled in a board will overlap.


texts:
I'm fairly new to programming and this is the 2nd thing I've done in python.

This code creates a /Tiles directory in the folder where the script is ran, then it makes an X (8) number of folders inside of /Tiles.

Inside of those 8 folders it makes a Y number of subfolders and downloads Z number of images per Y folder.

Y and Z are the same number but change depending on the X folder.

X folder 0 contains 2^0 Y folders and 2^0 Z images per Y folder.

Next X folder 2^1, etc until 8 folders or 2^7.

Any general or python specific advice for a newbie?

Also, any design advice?

I was thinking of having a loading bar of some sorts because it's ~20k images and was looking into this https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console

But in the end decided I just want to finish this up since I was done with the main functionality.

[..] means the code is on the same line but I made a new one for the purposes of reading here without scrolling.

Thanks.

import os
import urllib.request
import ctypes

print ("This script will download map tiles from [Redacted link]")
print ("The further it gets the more time it will take to fill the current folder.")
print ("Because the number of images increases exponentially.")
print ("You can check the progress by going into the latest folder.")
print ("When it is done the taskbar icon will flash and prompt you to close the window.")

# stores current directory
path = os.getcwd()
print ("The current working directory is {}.".format(path) + "\n")

# adds the names of the new directory to be created
path += "/Tiles/"

# defines the access rights
access_rights = 0o755

# creates the tiles directory
try:
    os.mkdir(path, access_rights)
except OSError:
    print ("Creation of the tiles directory {} failed.".format(path))
else:
    print ("All files will be downloaded to {}.".format(path))
    # for testing:
    # print ("Successfully created the tiles directory {}".format(path))

# number of x subfolders
x_folders = 8
# number of y subfolders and z images - different folders have a
[..] # different number of subfolders amd images
yz_array = [2**0, 2**1, 2**2, 2**3, 2**4, 2**5, 2**6, 2**7]

# main loop
# creates the x directories
for x in range(x_folders):
    try:
        os.mkdir("{}/{}".format(path,x), access_rights)
    except OSError:
        print ("Failed to create the X directory - {}.".format(x))
        break
    except:
        print("Something went wrong creating X folders.")
        break
    else:
        print("Downloading images to {}{}.".format(path,x))

        # creates the y directories
        for y in range(yz_array[x]):
            try:
                os.mkdir("{}/{}/{}".format(path,x,y), access_rights)
            except OSError:
                print ("Failed to create the Y directory - {}.".format(y))
                break
            except:
                print("Something went wrong creating Y folders.")
                break
            else:
                pass

            # downloads z images
            for z in range(yz_array[x]):
                try:
                    urllib.request.urlretrieve("[Redacted link]
[..]/{}/{}/{}.png" \
                    .format(x,y,z), "{}/{}/{}/{}.png".format(path,x,y,z))
                except:
                   print("Something went wrong downloading Z images.")
                   break
                else:
                    pass

    print("Successfully filled folder {}{}.".format(path,x) + "\n")

print("Finished running.")
ctypes.windll.user32.FlashWindow(ctypes.windll.kernel32.
[..]GetConsoleWindow(),True) # flashes the taskbar icon
print("Press Enter to close")
input("\n")


texts: Shortening list of arguments to some kind of a variadic function

texts:
If you look at ImportAndPreload method, it looks bad because:
MovingAverageConvergenceDivergence, StochasticRSI, RelativeStrengthIndex and ExponentialMovingAverage. They are all indicators, they all inherit from IndicatorBase. What would happen if I wanted to pass a few more indicators? There would be 10 indicators passed by arguments, which is annoying and it's against S.O.L.I.D. Is there a way to make that method like a variadic function in C++ and pass infinite amount of indicators. By the way, as you can see below, IndicatorBase is generic, which prevents params IndicatorBase<???>[] args.
For example: ImportAndPreload(symbol, interval, macd, stoch, rsi, ema, ...)
I'm also open for other ideas.
MovingAverageConvergenceDivergence macd = new MovingAverageConvergenceDivergence(12, 26, 100);
StochasticRSI stoch = new StochasticRSI(14, 9, 3, 3);
RelativeStrengthIndex rsi = new RelativeStrengthIndex(20);
ExponentialMovingAverage ema = new ExponentialMovingAverage(20);

ImportAndPreload(symbol, interval, macd, stoch, rsi, ema);

// Abstract base class for all indicators:
public abstract class IndicatorBase<TInput, TOutput>
    where TInput: struct
    where TOutput : struct
{
    public abstract TOutput ComputeNextValue(TInput input);
    public abstract void Reset();
}

private void ImportAndPreload(string symbol, KlineInterval interval, MovingAverageConvergenceDivergence macd, StochasticRSI stoch, RelativeStrengthIndex rsi, ExponentialMovingAverage ema)
{
    // Import candles
    List<BinanceKline> candles = Client.GetKlines(symbol, interval, limit: 1000).Data.SkipLast(1).ToList();

    for (int i = 0; i < 3; i++)
    {
        List<BinanceKline> moreCandles2 = Client.GetKlines(symbol, interval, startTime: null, endTime: candles.First().OpenTime, limit: 1000).Data.SkipLast(1).ToList();
        candles.InsertRange(0, moreCandles2);
    }

    // Workaround in case it gets more bigger time to import candles
    List<BinanceKline> moreCandles = Client.GetKlines(symbol, interval, limit: 2).Data.SkipLast(1).ToList();
    candles.AddRange(moreCandles.ExceptUsingJsonCompare(candles));

    // Preload indicators
    for (int i = 0; i < candles.Count; i++)
    {
        macd.ComputeNextValue(candles[i].Close);
        stoch.ComputeNextValue(candles[i].Close);
        rsi.ComputeNextValue(candles[i].Close);
        ema.ComputeNextValue(candles[i].Close);
    }
}
```


texts: Using Cache::remember for banners and stores

texts:
I'm using Cache::remember to cache 3 results in my action, 2 in the same call to Cache::remember. It works, but I have 2 questions about how I can join this Cache::remember call:

Could I use two Cache::remembers in the same method?
Could I join these two Cache::remembers (I need change the first param)?
Is it possible load model outer Cache::remember?

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    list($stores, $favoriteStores) = Cache::remember(
        'stores', function(){
        $stores = $this->Stores->myStores($this->Auth->user('id'));
        $favoriteStores = $this->Stores->favoriteStores();
        return [$stores, $favoriteStores];
    });

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}


texts: Filtering a Vec of structs and creating new vector of Strings or strs in Rust

texts:
I'm working through the Rust book, and it has the following example of how to use the filter method on Iterators (source):
struct Shoe {
    size: u32,
    style: String,
}

fn shoes_in_my_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

I started thinking of how I could improve this function with the following objectives:

Do not consume/take ownership the shoes vector, so the caller can still use it.
Return a vector of just the styles, rather than of the whole Shoe struct.

I came up with the following two possible solutions:
fn shoe_styles_in_my_size(shoes: &[Shoe], shoe_size: u32) -> Vec<&String> {
    shoes
        .iter()
        .filter(|s| s.size == shoe_size)
        .map(|s| &s.style)
        .collect()
}

and:
fn shoe_styles_in_my_size(shoes: &[Shoe], shoe_size: u32) -> Vec<&str> {
    shoes
        .iter()
        .filter(|s| s.size == shoe_size)
        .map(|s| &s.style[..])
        .collect()
}

The difference being that the first example returns Vec<&String> and the second returns Vec<&str>.
What criteria would I use to determine which of these two is "better?"  I've been under the impression that using str is preferable to using String when possible, since it is more flexible (hopefully this is accurate?) Is there any overhead associated with the [..] operation?  My understanding says no, but I'm not sure.


texts: How to refactor below nodejs code to unblock event-loop?

texts:
I produced below code and soon it became outdated due to the blocking nature of it's loops which I can't see how to avoid that.

Work-flow summery

Client send a request to "/" to get a list of JS objects via JSON format. Few hundred thousand records of them. Array A
First script should retrieve translation documents for above records, translations are also obviously in few hundred thousand set. In this stage it does a network call and retrieves those. Array B
Then needed Array A should be retrieved via Mysql DB.
Then sorts Array A and Array B and bind those together in a very long loop. (Blocks code)
Then submits the reformatted result to client.

router.get("/", async function (req, res) {
  CustomModel.count({}) // this is database call via sequelize-hierarchy library
    .then(async (count) => {
      await common
        .getLanguages(config.urls.languages_cat_endpoint) // this is a outside API call which retreives few hundred thousand records of JSON objects
        .then((langs) => {
          common.afterFindHook(CustomModel, langs.data); // This code registers a hook and it will get triggers when line findAll calls, and it pass above set of JSON objects as an arguments
        })
        .catch((e) => {
          console.log(e);
          common.sendResponse(res, 500, "Internal Server Error");
          return;
        });

      CustomModel.findAll({
        // BLOCKING code due to above 4th step. Another call via sequelize-hierarchy library, it will trigger above afterFindHook and sort->find->bind each language JSON object to each row. Few hundred thousand records here
        where: { status: true },
        hierarchy: true,
        order: [["position", "DESC"]],
      })
        .then(function (result) {
          res.send(result); // This is where the real result submitted to client.
          res.end();
        })
        .catch((error) => {
          common.sendResponse(res, 500, error);
        });
    })
    .catch((e) => {
      console.log(e);
      common.sendResponse(res, 500, "Internal Server Error");
      return;
    });
});

I'm aware there are lot of optimizations can be done to speed up the request, or reduce the time to prepare the request however I'm not interested on that.

My question here is how to remove and refactor only event-loop blocking code.


texts: Sieve of Eratosthenes performance; Scala very slow compared to Node.js

texts:
I am new to Scala so it might show. I am learning it for one of my classes and have to write a performance benchmark. I have written the Sieve of Eratosthenes in both Node.js and Scala, and my Node.js version runs much much quicker for n larger than 100,000. At n = 100,000 the Scala version runs in around a minute where as the Node.js one runs in milliseconds.

As far as I know the Scala version is implemented correctly as it finds the first few primes correctly.

The big disparity in time leads me to believe it's an algorithmic issue and the two pieces of code likely have different time complexities, but looking at the two pieces of code I don't see any stark differences other than iterating the list a couple extra times in the scala version (with the zipIndex and mapping).

Any help would be appreciated.

This is my Scala method

// Sieve of Eratosthenes
// pseudo code from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def sieve (n: Integer) = {
    // Let A be an array of Boolean values, indexed by integers 2 to n,
    // initially all set to true.
    var A = new ListBuffer[Boolean]()
    var i = 2
    for (i <- 2 to n) {
        A += true
    }

    // for i = 2, 3, 4, ..., not exceeding √n:
    // if A[i] is true:
    //    for j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n:
    //      A[j] := false.
    i = 2
    for ( i <- 2 to Math.sqrt(n.toDouble).toInt ) {
        if(A(i - 2)) {
            var j = 0
            for ( j <- i * i to n by i ) {
                A(j - 2) = false
            }
        }
    }

    // Output: all i such that A[i] is true.
    A.zipWithIndex.filter{case (b, i) => b }.map{ case (b, i) => i + 2 };
}

This is my Node.js code:

let _ = require('lodash');

// Sieve of Eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

function int (str, base=10) {
    return parseInt(str, base);
}

// Input: an integer n > 1.
let n = int(process.argv[2]);

//  Let A be an array of Boolean values, indexed by integers 2 to n,
//  initially all set to true.
 let A = _.range(n+1)
 A[0] = false
 A[1] = false

// for i = 2, 3, 4, ..., not exceeding √n:
//    if A[i] is true:
//      for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
//        A[j] := false.
for(let i = 2; i <= Math.sqrt(n); ++i) {
    if(A[i]) {
        for(let j = i*i; j <= n; j += i) {
            A[j] = false;
        }
    }
}

let primes = A.filter((el)=>el);


texts:
I am having difficulty understanding the runtime and space complexity while implementing the said question.

Following is the code:

import java.util.HashMap;
import java.util.Map;

public class AnagaramInBigString {

private static Map<Character, Integer> frequencyMap(String str)
{
    Map<Character, Integer> source = new HashMap<Character,Integer>();
    for(int i = 0; i < str.length(); i++)
    {

        if(str.charAt(i) == ' ')
        {
            continue;
        }
        else
        {

            if(source.containsKey(str.charAt(i)))

            {
                source.put(str.charAt(i), source.get(str.charAt(i) + 1));
            }
            else source.put(str.charAt(i), 1);
        }
    }

    return source;
}

public static void main(String []args)
{
    String check= "BACDGABCDA";
    String sample = "ABCD";
    System.out.println(sample.length());

    for(int i= 0; i <= check.length() - sample.length() ; i++)
    {
        String checkSub = check.substring(i, i + sample.length());
        System.out.println(checkSub);
        System.out.println(frequencyMap(checkSub).equals(frequencyMap(sample)));
    }
}

}

Is the time complexity O(check*sample)? Space complexity is O(sample)?
Also please suggest on how I can improve the efficiency of this code.

Like:

I can calculate the hashmap for sample string only once instead of doing it again and again with every iteration.


texts: Way to hide logic behind class for better readability of method and refactor class to follow SRP

texts:
I have an algorithm to create a version for an entity and then I save that version against below 2 entity:

1) Variant

2) Category

interface IEntityVersion
{
    string GetVersion();
}

public class EntityVersion : IEntityVersion
{
    public string GetVersion()
    {
        return null;
    }
}

public interface IVariant
{
    void Process(Variant model, string connectionString);
}

public abstract class BaseVariant : IVariant
{
    private readonly IEntityVersion _entityVersion = new EntityVersion();

    public void Process(Variant model, string connectionString)
    {
        try
        {
            Transform();
            string variantVersion = _entityVersion.GetVersion();
            using (var myConnection = new SqlConnection(connectionString))
            {
                myConnection.Open();
                using (var transaction = myConnection.BeginTransaction())
                {
                    try
                    {
                        VariantRepo.UpdateVariantVersion(
                          myConnection,
                          transaction, model.VariantId, variantVersion);

                        CategoryRepo.UpdateCategoryVariantMapping(
                                     myConnection,
                                     transaction, model.CategoryId, variantVersion);

                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        DeleteStep1Data();
                    }
                }
            }
        }
        catch (Exception)
        {
            //log error
        }
    }

    protected abstract void DeleteStep1Data();
    protected abstract void Transform();
}

public class Variant
{
    public int VariantId { get; set; }
    public int CategoryId { get; set; }
}

public class VariantRepo
{
    public static void UpdateVariantVersion(SqlConnection sqlConnection,
        SqlTransaction transaction, int variantId, string version)
    {
        //save logic here
    }
    public static void RemoveAggregateStatistics(int variantId)
    {
       //remove logic here from Aggregate statistics table
    }
    public static void RemoveAdditionStatistics(int variantId)
    {
       //remove logic here from Addition statistics table
    }
}

public class CategoryRepo
{
    public static void UpdateCategoryVariantMapping(SqlConnection sqlConnection,
        SqlTransaction transaction, int categoryId, string version)
    {
        //save logic here
    }
}

I have 2 derived types(AggregateCalculator and AdditionCalculator) each having their own implementation of Transform and DeleteStep1Data methods.

public class AggregateCalculator : BaseVariant
{
    protected override void DeleteStep1Data() // Is it violating SRP ?
    {
        VariantRepo.RemoveAggregateStatistics(int variantId);
    }

    protected override void Transform()
    {
        throw new NotImplementedException();
    }
}

public class AdditionCalculator : BaseVariant
{
    protected override void DeleteStep1Data()// Is it violating SRP ?
    {
        VariantRepo.RemoveAdditionStatistics(int variantId);
    }

    protected override void Transform()
    {
        throw new NotImplementedException();
    }
}

I feel like the Process method is doing too much work and if it would be possible to hide version saving related logic behind the EntityVersion class so that the Process method looks simple.

Step1 and Step2 are in sync so that if there is an error in Step2, I call the DeleteStep1Data method to delete all the data saved in Step1.

Also I feel like my 2 derived classes AggregateCalculator and AdditionCalculator are handling more than 1 responsibility, i.e. running a transformation and also deleting the data stored during the transformation process, although I am not sure if this is true or not.

Is there a possibility to refactor above code to improve readability and handle SRP ?


texts: Loop through products and return first product that matches criteria

texts:
I am writing a function which loops through an array of products.  The function needs to return:

the ID of the first product that has an image and is in stock
if no products have an image and are in stock, then return the first product id that has an image
if no products have an image, then return the first product id that is in stock
if no products have an image, and no products are in stock, return the first product id

This is what I have written, and it is working as expected:

function loopThroughProducts($products)
{
    $firstId = $products[0]->id;

    foreach ($products as $product) {
        if ($product->hasImage && $product->inStock) {
            $id = $product->id;
            return $id;
        }
        if ($product->hasImage && empty($firstIdWithImage)) {
            $firstIdWithImage = $product->id;
        }
        if ($product->inStock && empty($firstIdInStock)) {
            $firstIdInStock = $product->id;
        }
    }

    if (!empty($firstIdWithImage)) {
        return $firstIdWithImage;
    }
    if (!empty($firstIdInStock)) {
        return $firstIdInStock;
    }

    return $firstId;
}

Does anyone see a way that I can optimize this loop or simplify the logic?  I dislike using so many sequential if-statements in one function, and there are some minor violations to the DRY principle.


texts:
I have a problem were the time in minutes of N songs are given and I have to write the maximum number of time in K CDs.

Input description

  The first input line consists of two positive integers N e K (\$N \le 100\$, \$K \le 3\$), which represent respectively the number of songs and te number of cds. The second input line consists of N positive integers, which represent the duration in minutes of each song. The last input line consists of K positive integers, which represent the maximum number of minutes of music that it is possible to record to each cd. No song has more than 50 minutes, and no cd has available more than 50 minutes of space.

Output description

  Print a line containing singly the maximum total number of minutes of music that it is possible to record to the cartridges.

To solve this problem I've programmed a dynamic programming solution where the choices are put the \$i\$th song on each CD or none.

#include <iostream>
#include <algorithm>
#include <string.h>

int dpt[51][51][51][101]; //table for dp

int dp(int *song, int *cd, int n, int k, int element){
    if(element == n)
        return dpt[ cd[0] ][ cd[1] ][ cd[2] ][element] = 0;

    if(dpt[ cd[0] ][ cd[1] ][ cd[2] ][element] != -1)
        return dpt[ cd[0] ][ cd[1] ][ cd[2] ][element];

    int best = 0;

    for (int i = 0; i < k; ++i) {
        if(cd[i] >= song[element]){
            cd[i] -= song[element];
            best = std::max(best,song[element] + dp(song,cd,n,k,element + 1));
            cd[i] += song[element];
        }
    }

    best = std::max(best,dp(song,cd,n,k,element + 1));

    return dpt[ cd[0] ][ cd[1] ][ cd[2] ][element] = best;
}

int main(void){
    int n,k;
    std::cin >> n >> k;

    int song[n];
    for (int i = 0; i < n; ++i) {
        std::cin >> song[i];
    }

    int cd[3] = {0,0,0};
    for (int i = 0; i < k; ++i) {
        std::cin >> cd[i];
    }

    memset(dpt, -1 , sizeof(dpt));
    std::cout << dp(song, cd, n, k, 0) << "\n";
}

This solution takes approximately 1 second with a unknown testbase. But some people got 0 secs. What can I do better here?

Here are some samples:

Input

8 3
7 3 3 2 4 4 2 3
9 8 9

10 1
31 36 16 13 10 13 36 47 1 21
20

10 2
41 8 48 49 33 2 41 26 5 39
22 37

Output

26

17

48


texts:
I want to implement a function take_upto_n(A, n)
such that for e.g.
take_upto_n([1,2,3,4], 8) returns [1,2,3,2]
take_upto_n([1,2,4,3], 8) returns [1,2,4,1]
take_upto_n([1,2,3,4], 100) returns [1,2,3,4]
take_upto_n([1,2,3,4], 3) returns [1,2,0,0]

Assume A contains non-negative values only. n is also non-negative
This is straightforward with a loop
def take_upto_n(A, n):
    out = []
    for x in A:
        out += [min(n, x)]
        n -= min(n, x)
    return out

We can also do this with numpy, but this I.M.O. is fairly unreadable:
def take_upto_n(A, n):
    A = np.array(A)
    return np.clip(n + A - np.cumsum(A), 0, A)

Is there some standard function that does this - couldn't find it myself (or didn't know how to search)?
If there isn't any such function, any advice on how to make it not look like "what is this?" (the n + A - np.cumsum(A) is the real killer)?


texts: Excel 2016 VBA - Show/Hide multiple shape groups

texts:
I have the following code I'm using to show/hide multiple shape groups in Excel 2016 using VBA and macros:

   Sub Pic_1_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = True
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_1_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = True
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = True
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = True
   End Sub

Now the above is somewhat tedious if I plan to add more buttons. Is there any way to do this more efficiently?


texts: All combinations of two pairs of elements of an array

texts:
Suppose I have an array of objects. Without loss of generality, it could be an array of indices:
$$a = (0, 1, 2, ..., n)$$
Now suppose I want to choose two pairs of elements of this array. The order is not of the matter inside pairs so for pairs itself.

For example if
$$a = (1,2,3,4)$$
then all those combinations would be
$$(1,2), (3,4)\\(2,3), (1,4)\\...$$
But combinations like
$$(1,2), (3,4)\quad \text{and}\quad (4,3), (1,2)$$
should be considered as equivalent.

I am a little bit confused how to write compact and effective algorithm for my purpose. I feel that there is a way to do it for general case (not just for pairs) but I cannot find it. If you know, please share.

So far, here is my code.

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector< int > targetVector = { 1, 2, 3, 4, 5 };

    std::vector< int > index_pair = { 2, 2, 1, 1, 0 };

    int pair1, pair2;
    do
    {
        //reset pairs to 00000
        pair1 = pair2 = 0;

        for ( int i = 0; i < (int)index_pair.size(); i++ )
        {
            if( index_pair[i] == 1 ) { pair1 += ( 1 << (i+1) ); }
            if( index_pair[i] == 2 ) { pair2 += ( 1 << (i+1) ); }
        }

        if ( pair1 > pair2 )
        {
            for ( auto index : index_pair )
            {
                std::cout << index;
            }
            std::cout << "\n";
        }
    }while( prev_permutation( index_pair.begin(), index_pair.end() ) );

    return 0;
}

Here is the output that seems to be right.

22110
22101
22011
21210
21201
21021
20211
20121
12210
12201
12021
10221
02211
02121
01221


texts: Exotic bitmap renderer for core drawing functions

texts:
I am very interested in inventing the best way possible for rendering bitmaps on-screen using the base drawing functions (putpixel(x, y), lineto(x, y), moveto(x, y), setpen(r, g, b, transp, size) )

You don't need to use graphic library to have them. You can call BIOS interrupt or initialize registers manually to set the video mode to 13h (for example) for 320x200 canvas field and 256-color mode and write from offset segment A000h

I know there are ways to make the rendering faster.

If loop iterations are reduced
If loop body computations are reduced
If the function is smart enough to figure out where to use lineto or larger pen

  C89, no std libs, implementation of putpixel/setpen functions (from
  graphics.h, sdl, cairo etc)

#define OFFSET_OF_ID        (0x0)
#define OFFSET_OF_SIZE      (0x2)
#define OFFSET_OF_PIXELS    (0xA)
#define OFFSET_OF_NDIB      (0xE)
#define OFFSET_OF_WIDTH     (0x12)
#define OFFSET_OF_HEIGHT    (0x16)
#define OFFSET_OF_BPP       (0x1C)
#define OFFSET_OF_NRAW      (0x22)

#define loop(x, y, z) int x; for(; y; z)

typedef const volatile unsigned long data, *pdata;
typedef unsigned char pixel [0x3], (*byte_buffer);

void bmp_render (byte_buffer image)
{
    data image_width            = *(pdata)&image[OFFSET_OF_WIDTH];
    data image_height           = *(pdata)&image[OFFSET_OF_HEIGHT];
    data image_offset_pixels    = *(pdata)&image[OFFSET_OF_PIXELS];
    data image_raw_size         = *(pdata)&image[OFFSET_OF_NRAW];
    data image_row              = image_width * sizeof(pixel);

    unsigned h = 0, w = 0, pad = 0, padding = image_width % 4;

    loop(i = image_offset_pixels, i < image_raw_size, i += sizeof(pixel))
    {
        if(i == image_offset_pixels + (image_row * ((h + 1)) + (pad * h)))
        {
            pad = padding;
            i += pad;
            h += 1;
            w = !w;
        }

        setpen(image[i + 2], image[i + 1], image[i], 0, 1); // setpen(r, g, b, transp, size)
        putpixel(w++, image_height - h); // putpixel(x, y) of the canvas
    }
}


texts: SQL Group and Filter - Refining down a search including Dates

texts:
The below process is designed to pick out only AsbestosUPRNs and get the lowest OverallRiskCategory where they have the newest SurveyDate. I just wanted to ensure this is the best way, it seems neat now though as well as second code, which in reality is the same thing, based on two tables.

SELECT
AsbestosUPRN,
MIN(OverallRiskCategory) AS OverallRiskCategory,
MAX(SurveyDate) AS SurveyDate
FROM TblAsbestos
GROUP BY
AsbestosUPRN

Two Table version:

SELECT
p.UCARN,
MAX(a.OverallRiskCatNumberical) as OverallRiskCatNumberical,
MAX(a.SurveyDate) AS SurveyDate
FROM TblAsbestos AS a
INNER JOIN TblProperty AS p
ON p.UPRN = a.AsbestosUPRN
GROUP BY
p.UCARN


texts:
This question over on SO about how to call a function "later" using Rx led me to post the following ill-advised piece of code to solve the problem:

void Main() {
  getScheduleTimes()
    .Where(t => t >= DateTimeOffset.Now)
    .SelectMany(t => Observable.Timer(t).ToEnumerable())
    .ToObservable()
    .Subscribe(_ => {
      Console.WriteLine("Ding! It's now {0}", DateTimeOffset.Now);
    });
}

IEnumerable<DateTimeOffset> getScheduleTimes() {
  DateTimeOffset day = DateTimeOffset.Now.Date;
  while (true) {
    yield return day + new TimeSpan(09, 00, 00);
    yield return day + new TimeSpan(13, 00, 00);
    day = day.AddDays(1);
  }
}

This doesn't work. Or rather, it appears to work -- if you run this, you'll notice that the call to .Subscribe() never returns. I was lambasted (rightly or otherwise) for involving .ToEnumerable() and .ToObservable(), as using these can cause "subscription side effects, collapsed times and dead-locks", as well as the code being confusing overall. The accepted answer builds an Observable directly.

Have I learned my lesson? Hardly. I still like the idea of using an (infinite) IEnumerable for producing the schedule. My question to you is: is anything still wrong with this code (assuming we keep the same getScheduleTimes()):

getScheduleTimes()
  .Where(t => t >= DateTimeOffset.Now)
  .Select(t => Observable.Timer(t))
  .Concat()
  .Subscribe(_ => {
    Console.WriteLine("Ding! It's now {0}", DateTimeOffset.Now);
  });

I was originally fixated on .SelectMany(), but instead .Concat() seems to be what I'm looking for. The code works, in that the subscribe no longer blocks and, as far as I can tell, no unacceptable overhead or confusion is produced, but my experience with Rx is limited. Are there any problems with this I'm not seeing, perhaps when you take it out of the toy box (cancellation, multiple subscriptions, thread overhead, etc.)?

The accepted answer also mentions using .Generate():

Observable.Generate(
  getScheduleTimes().GetEnumerator(),
  e => e.MoveNext(),
  e => e,
  e => e.Current,
  e => e.Current);

Would you say this is better than .Select(...).Concat(), based on whatever people experienced in Rx use to judge such things?


texts: Python recursive function that receives list of strings, and returns a nested list of anagrams

texts:
I'm learning Python and would appreciate any (and all) feedback to improve myself.
input/output example:
>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]

Here is the code I wrote, it worked well for the above list. Looking for feedback on complexity, overall design, readability and any other thing that pops to mind when reviewing, thanks!
# process list of strings, construct nested list of anagrams.

list_of_strings = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

list_of_lists = []
temp_list = []

def sort_anagrams(list_of_strings):
    if len(list_of_strings) > 1:
        temp_list = [list_of_strings[0]] # create temp list to be eventually appended to main list
        popped_list = list_of_strings # list of anagrams to remove from source list after iteration, without deleting source list
        popped_list.pop(0) # remove the first item as it's already in the temp_list
        strings_to_pop = []

        for string in popped_list:
            if sorted(string) == sorted(temp_list[0]):
                temp_list.append(string) # passing anagram test so append to temp_list
                strings_to_pop.append(string) # create list of items to remove popped_list

        list_of_lists.append(temp_list) # append temp_list as a list element

        for string in strings_to_pop:
            popped_list.remove(string) # remove all strings that were deemed anagram to remove possible duplications

        sort_anagrams(popped_list)    # running the function again on list remainder

    elif len(list_of_strings) == 1:
        temp_list.append(list_of_strings[0])
        list_of_strings.pop(0)
        list_of_lists.append(temp_list) # append temp_list as a list element
        sort_anagrams(popped_list)

    else:
        print('you have reached the end and sorted all anagrams. here is the list of anagram lists: \n \n', list_of_lists)

sort_anagrams(list_of_strings)
```


texts:
I've came up with solution to the Piling Up! problem on HackerRank. It passes all tests on HackerRank. How could I improve this code? Are there any cases outside those provided on HR that I've missed?

for _ in (range(int(input()))):
    no_of_cubes = int(input())
    side_lengths = list(map(int, input().strip().split()))
    result = "Yes"
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        result = "No"
    print(result)


texts: Bash script, "flash cards" for Spanish vocabulary

texts:
I use this bash script to review over vocabulary with my dental Spanish class. The script works great for me. However, I am wondering what other ways the same thing could be done. How could it be more efficient? Perhaps the script could me made more readable? Maybe other areas could be made more proper or elegant? If I have done something well, then that feedback too is appreciated. I am not particularly interested in adding in checks/tests of the formatting of my vocabulary sheet or checking to make sure the file exists. The comments have my English translations of the Spanish in the script.

This script reads each line of the vocabulary file from the top to the bottom and tests whether the user knows how to say the equivalent in Spanish. It is formatted like this, English: SpanishOpt1, SpanishOpt2, SpanishOpt3. Any of the options between commas could count as correct.

This is a sample of what a vocab file looks like:

floor of the mouth: piso de la boca
cheek: mejilla, cachete
throat: garganta
change in color: cambio en color, cambio de color
taste buds: bulbos gustativos
growth: crecimiento
bruise: moretón, cardenal, magulladura, moradura, contusión

Here is the script:

#!/bin/bash

read -r -p "1 - evaluación oral
2 - radiografía
Elige uno: " opt
# Choose one.

clear

if ! [[ "$opt" =~ ^[1-2]$ ]]; then
    # That is not an option. Choose 1 or 2.
    echo "Eso no es una opción. Elige 1 o 2."
    exit 1
fi

fname=("" "evaluación-oral-vocabulario.txt" "radiografía-vocabulario.txt")
file="/home/brock/2-Work/Dental/${fname[$opt]}"
vocab_items=$(wc -l < "$file")
line_num=1
num_right=0

until (("$line_num" > "$vocab_items")); do
    vocab_item=$(head -n"$line_num" "$file" | tail -n1)
    english=$(echo "$vocab_item" | cut -d: -f1)
    spanish=$(echo "$vocab_item" | cut -d: -f2 | sed 's/ //')
    plural_options=$(echo "$spanish" | grep ,)
    plural_vocab_item=$(echo "$spanish" | cut -d, -f1 | wc -w)
    if [ -n "$plural_options" ] || (("$plural_vocab_item" > "1")); then
        # The "s" is to make the subject below "Las palabras" plural if needed. The "n" is for the plural verb conjugation.
        s="s"; n="n"
    else
        s=""; n=""
    fi
    # How do you say ... in Spanish?
    read -r -p "¿Cómo se dice \"$english\" en español? " r
    answer_check=$(echo "_${spanish}_" | sed 's/, /_/g' | grep "_${r}_")
    # The "y" means "and" which is added before the last item in a list with no serial comma.
    spanish_feedback=$(echo "$spanish" | sed 's/\(.*\),/\1 y/')
    if [ -n "$answer_check" ]; then
        # You are correct. The word(s) ... mean ...
        echo -e "\tTienes razón. La$s palabra$s \"$spanish_feedback\" quiere$n decir \"$english\".\n"
        ((num_right++))
    else
        # You are not correct. The word(s) ... mean ...
        echo -e "\tNo tienes razón. La$s palabra$s \"$spanish_feedback\" quiere$n decir \"$english\".\n"
        pair_wrong[$line_num]="$vocab_item\n"
    fi
    ((line_num++))
done

# You know ... out of ... terms overall.
echo "Tú sabes $num_right de $vocab_items términos en total."
if [ -z "${pair_wrong[*]}" ]; then
    # Incredible! One hundred percent!
    echo "¡Increíble! ¡Cien por ciento!"
else
    # You have to work more on:
    echo -e "Tienes que trabajar más en:\n ${pair_wrong[*]}"
fi


texts: Getting names/values of multiple properties

texts:
Lets say I have one method, which extracts property name and value:

public TModel Get (Expression<Func<object>> param)
{
        using (OracleConnection connection = new OracleConnection(GetConnectionString()))
        {
            connection.Open();

            var propertyName= ((MemberExpression)param.Body).Member.Name;

            var value = param.Compile()();

            // GetTableName() returns table name of TModel
            var query = $"SELECT * FROM {GetTableName()} WHERE {propertyName}='{value}'";

            var output = connection.Query<TModel>(query);
            connection.Dispose();
            return output.FirstOrDefault();

        }
}

and using it as:

var model = Get(() => foo.FirstProperty);

However, if I want to get name and value from the unknown number of properties, I do this:

public TModel Get(params Expression<Func<object>>[] param)
        using (OracleConnection connection = new OracleConnection(GetConnectionString()))
        {
            connection.Open();

            var query = new StringBuilder();

            query.Append($"SELECT * FROM {GetTableName()} WHERE ");
            for (int i = 0; i < param.Length; i++)
            {
                var propertyName = ((MemberExpression)param[i].Body).Member.Name;

                var value = param[i].Compile()();

                query.Append($"{propertyName} = '{value}'");
                if (i + 1 < param.Length) query.Append(" AND ");
            }

            var output = connection.Query<TModel>(query.ToString());
            connection.Dispose();
            return output.FirstOrDefault();
        }
    }

But, implementation looks a bit 'ugly' and verbose:

var model = Get(() => foo.FirstProperty, () => foo.SecondProperty); // and so on

I could send manualy name of the property + value, however, I would like to keep the implementation as simple as possible and less verbose.

Is there any way to simplify this?


texts: What should I do to improve this snippet

texts:
Though it works I wonder if there might be a better way to do this. I would like to reuse this loading and establishing of fields of another class(es) (the static TileMapper class mentioned at the end) in a C#/.net/XNA environment.

I noticed that when moving through the OpenFileDialog to find files it felt sluggish.
 Is that because I had to set [STAThreadAttribute] just to get it to open?

private void loadMapToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Title = "Select a File";
        openFile.InitialDirectory = Application.StartupPath + @"\Content\Map\";
        openFile.Filter = "MAP Files (.MAP)|*.MAP";
        openFile.FilterIndex = 1;
        openFile.Multiselect = false;

        if (openFile.ShowDialog() != DialogResult.Cancel)
        {
            try
            {
                // Example file - _W25_H25_SET_GL_test.Map
                TileMapper.LoadMap(new FileStream(openFile.FileName, FileMode.Open));
                // remove directory information
                string[] _mapname = openFile.FileName.Split('\\');
                string tempmap = _mapname.Last();
                // remove .map
                string[] removemap = tempmap.Split('.');
                MapName = removemap.First();
                //print file name
                txtMapName.Text = MapName;
                //get info stored in file name
                string[] nameParts = MapName.Split('_');
                string[] widthPart = nameParts[1].Split('W');
                string[] heightPart = nameParts[2].Split('H');

                TileMapper.MapWidth = int.Parse(widthPart[1]);
                TileMapper.MapHeight = int.Parse(heightPart[1]);
            }
            catch
            {
                System.Diagnostics.Debug.Print("Unable to load map file");
            }
        }
        else return;
     }


texts:
I searched for a notification script that shows inbox and rep change items on the browser tab in stackapps.com but either they didn't work or were outdated.

So, I've done this raw script myself and want to make it fool proof and robust:
This is my first ever user script. So want to make it better. (Even if it wasn't the first, I would have wanted to make it better)

// ==UserScript==
// @name         Tab Notifier
// @namespace    http://2200ce.wordpress.com/
// @version      0.1
// @description  A notification system that displays inbox and rep change notification on the tab
// @author       Amit Joki - http://stackoverflow.com/users/3001736/amit-joki
// @include      http://stackoverflow.com/*
// @grant        none
// @require      https://cdn.rawgit.com/kapetan/jquery-observe/master/jquery-observe.js
// @match        *://*.stackexchange.com/*
// @match        *://*.stackoverflow.com/*
// @match        *://*.superuser.com/*
// @match        *://*.serverfault.com/*
// @match        *://*.askubuntu.com/*
// @match        *://*.stackapps.com/*
// @match        *://*.mathoverflow.net/*
// ==/UserScript==

var userscript = function($) {
    $('.icon-inbox .unread-count, .icon-achievements .unread-count').observe({
        attributes: true,
        attributeFilter: ['style']
    }, function() {
        var title = document.title;
        var isInbox  = $(this).parent().is(".icon-inbox") ? true : false;
        if (!$(this).attr('style')) {
            document.title = updater(title, $(this), isInbox);
        } else if ($(this).attr("style") == "display: none;") {
            debugger;
            var frags =  title.replace(/• /,"•").split(/\s(?=\w)/);
            var rgx = (isInbox ? /\[\d+\]/ : /\[\+\d+\]/);
            if(frags[0].indexOf("•") == -1){
                title = frags[0].replace(rgx, "") + frags.slice(1).join(" ");
            } else {
                rgx = /^(\[)(\+\d+) •(\d+)(\])/;
                title = frags[0].replace(rgx, isInbox ? "$1$2$$4" : "$1$3$4");
            }
            document.title = title + frags.slice(1).join(" ");
        } else { }

    });

    function updater(title, elm, isInbox){
        var txt = elm.text().trim();
        var rgx = (isInbox ? /\[\d+\]/ : /\[\+\d+\]/);
        if(title.indexOf("•") > -1){
            rgx = isInbox ? /^(\• )\d+/ : /^(\[)+\d+/;
            title = title.replace(rgx, "$1" + txt);
        }
        else if(rgx.test(title)){
            title = title.replace(rgx, "[" + txt + "] ");
        }
            else {title = "[" + txt + "] " + title;}

        if(title.indexOf("[")> -1 && title.match(/\[/g).length == 2){
            var arr = title.split(/\s(?=\w)/), rtn =['[',,' • ',,']'];
            arr[0].split(" ").forEach(function(e){
                rtn[e.indexOf("+") > -1 ? 1 : 3] = e.replace(/\[|\]/g,"");
            });
            title = rtn.join("") + " " + arr.slice(1).join(" ");
        }
        return title;
    }
}
var el = document.createElement('script');
el.type = 'text/javascript';
el.text = '(' + userscript + ')(jQuery);';
document.head.appendChild(el);

What this does is when inbox item alone comes up, it shows as:

  [{number of inbox item here}]

and same for rep change:

  [+{rep change here}]

When both come, they will be displayed in the following style:

  [+{rep change here} • {inbox items here}]

Also once the notifications are seen, it will be subsequently removed as well. I'm using MutationsObservers, which is warped by a plugin called jQuery.observe which looks to settle cross-browser issues.

How can this be improved?


texts: Does this C binary search tree have memory leaks?

texts:
I am new to C, so I have been trying to get practice doing some coding.

Usually I use languages like Java, python, ruby, etc: Garbage collected languages. So manually cleaning up is new to me and I would appreciate any advice on whether there are major flaws in my approach.

Also any other comments on the overall idomatic-ness of this code, and things that I need to watch out for as I try to learn more C. (If it matters, I am compiling this to the c99 standards)

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

/* a reference counted BST node... */
typedef struct _node node;
struct _node {
    char *word;
    unsigned int refs;
    node *left;
    node *right;
};

/* allocate a node onto the heap.
 * copy word into a new array so that it can free it when it wants to
 * later without fear of clobbering another node's string.
 *
 * TODO: Maybe implement word counting so that if someone else adds a
 *       word that's already in the tree, I don't need to store two
 *       instances.
 */
node* node_new(char *word) {
    node *n = malloc(sizeof(node));

    char *nword = malloc(strlen(word) + 1);
    memcpy(nword, word, sizeof(nword));
    n->word = nword;

    n->refs = 0;
    n->left = NULL;
    n->right = NULL;

    return n;
}

/* Decrement the references and if it is determined that no one holds
 * a ref to this object, then free it and check its children.
 *
 * Return the number of nodes freed in this manner. If this node has
 * referents, then return 0 since no nodes were freed.
 */
int node_del(node *n) {
    n->refs -= 1;

    if (n->refs > 0) return 0;

    int removed = 1;

    if (n->left != NULL)
        removed += node_del(n->left);

    if (n->right != NULL)
        removed += node_del(n->right);

    free(n->word);
    free(n);

    return removed;
}

/* replace link with n.
 * Cleans up link if needed.
 */
void node_setlink(node **link, node *n) {
    if (*link != NULL) {
        node_del(*link);
    }

    n->refs += 1;
    *link = n;
}

/* Add a node to the BST.
 */
void node_additem(node *root, node *n) {
    int comp = strcmp(root->word, n->word);

    node **target = (comp > 0) ? &(root->left) : &(root->right);

    if (*target == NULL)
        node_setlink(target, n);
    else
        node_additem(*target, n);
}

/* Traverse the BST in order, dumping the words to standard out.
 * No side effects.
 */
void node_traverse(node *root) {
    if (root->left != NULL)
        node_traverse(root->left);

    printf("%s\n", root->word);

    if (root->right != NULL)
        node_traverse(root->right);
}

/* Go through each argument, adding it to the tree. Then traverse the tree. Then
 * free the tree.
 */
int main(int argc, char **argv) {
    if (argc < 3) {
        printf("Please give me two arguments, or there won't be anything to sort!");
        return 1;
    }

    node *n;

    node_setlink(&n, node_new(argv[1]));

    for (int i = 2; i < argc; i++) {
        node_additem(n, node_new(argv[i]));
    }

    node_traverse(n);
    printf("n is %s %d\n", n->word, n->refs);
    printf("%d removed when n freed.\n", node_del(n));

    return 0;
}


texts: Modular dynamic based routing with wildcards

texts:
I've created this router for my framework and wanted to get some feedback on if it's the most efficient way to search the routes.

The main router

public static function route($modules = true){
    $route = (isset($_GET['route']) && $_GET['route'] != '') ? trim($_GET['route'], '/') : '/';

    $parts = explode('/', $route);

    if($parts[0] == 'debug' && ENVIROMENT == 'development'){
        array_shift($parts);
        static::$debug = true;
    }

    unset($_GET['route']);

    if($route != '/' && count($parts) != 0){
        static::$routeParts = $parts;

        if($parts[0] == 'modules' && $modules){
            $path = null;

            $fullpath = md5('/'.implode('/', $parts));

            //exact match
            $pathFound = key_exists($fullpath, static::$routingTable);

            //if full path not found look for partial
            if(!$pathFound){
                $elements = count($parts);// - 2;//parts after the module name
                $bits = $parts;

                if($elements > 0){
                    //array_pop($bits); //remove the final element - wildcard

                    $paths = array();
                    for($i = 0; $i < $elements; $i++){
                        $searchPath = '/'.implode('/', $bits).'/*';
                        $paths[] = $searchPath;
                        foreach(static::$routingTable as $rt){
                            if($searchPath == $rt['path']){
                                $pathFound = true;
                                $path = $rt;
                                break;
                            }
                        }

                        if($pathFound)
                            break;
                        else
                            array_pop($bits);
                    }

                    /*if($pathFound !== true){
                        //match base module and send rest as params
                        $moduleSlug = $parts[1];
                        $fullpath = md5('/modules/'.$parts[1]);
                        $pathFound = key_exists($fullpath, static::$routingTable);
                        $path = static::$routingTable[$fullpath];
                    }*/
                }
                else{
                    $fullpath = md5('/'.implode('/', $parts).'/*');

                    $pathFound = key_exists($fullpath, static::$routingTable);
                    $path = static::$routingTable[$fullpath];
                }
            }
            else
                $path = static::$routingTable[$fullpath];

            array_shift($parts);
            array_shift($parts);
            if($pathFound){
                static::$view = 'view';
                static::$args['dir'] = $path['callback']['config']['directory'];
                static::$args['slug'] = $parts;
                $_GET['params'] = $parts;
                static::$args['module'] = true;
                static::$args['fullwidth'] = (isset($path['callback']['config']['fullwidth']) ? $path['callback']['config']['fullwidth'] : false);

                ModuleLoader::runModule($path);
            }
            else{
                //not ideal
                static::$view = '404';
                static::$args['fullwidth'] = true;
            }
        }
        else{
            static::$view = $parts[0];
            array_shift($parts);
            array_shift($parts);
            static::$args['slug'] = $parts;
            $_GET['params'] = $parts;
        }
    }
    else{
        //home page module
        static::$view = 'index';
        static::$args['fullwidth'] = true;
    }
    static::$routed = true;
}

Some examples routes added are which will all be pre-pended with site directory + '/modules/' :

/
/test
/test/
/test/*


texts: Extending java.util.Random.nextInt(int) into nextLong(long)

texts:
In java.util.Random the Oracle implementation of nextInt(int) is as follows:

public int nextInt(int n) {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    if ((n & -n) == n)  // i.e., n is a power of 2
        return (int)((n * (long)next(31)) >> 31);

    int bits, val;
    do {
        bits = next(31);
        val = bits % n;
    } while (bits - val + (n-1) < 0);
    return val;
}

I have a need to do the same thing for longs, but this is not included as part of the class signature. So I extended the class to add this behavior. Here's my solution, and even though I'm pretty sure I have it right, bit-twiddling can subtly fluster even the best of devs!

import java.util.Random;

public class LongRandom extends Random {

    public long nextLong(long n) {
        if (n <= 0)
            throw new IllegalArgumentException("n must be positive");

        if ((n & -n) == n)  // i.e., n is a power of 2
            return nextLong() & (n - 1); // only take the bottom bits

        long bits, val;
        do {
            bits = nextLong() & 0x7FFFFFFFL; // make nextLong non-negative
            val = bits % n;
        } while (bits - val + (n-1) < 0);
        return val;

    }
}

Have I introduced a subtle bug? Are there improvements to make? What might I need to watch out for?


texts: Finding unique/obsolete binary Debian packages

texts:
I have a script I use to prune packages that have gone stale from my custom Debian repository (i.e. they no longer exists on any of the official repositories):

import apt_pkg
import gzip
import subprocess

CUSTOM_REPO = ("/home/tshepang/.custom_repo/dists/tshepang/main/"
               "binary-amd64/Packages.gz")
TEMPLATE = ("/var/lib/apt/lists/http.debian.net_debian_dists_{}_{}_"
            "binary-amd64_Packages")
CODENAMES = 'jessie sid experimental'.split()
ARCHIVE_AREAS = "main contrib non-free".split()

def main():
    custom_repo = apt_pkg.TagFile(gzip.open(CUSTOM_REPO))
    wheezy_packages = list()
    for codename in CODENAMES:
        for archive_area in ARCHIVE_AREAS:
            repo = TEMPLATE.format(codename, archive_area)
            repo = apt_pkg.TagFile(gzip.open(repo, "rb"))
            wheezy_packages.extend([pkg["Package"] for pkg in repo])
    for package in custom_repo:
        package_name = package["Package"]
        if package_name not in wheezy_packages:
            cmd = "apt-cache policy " + package_name
            subprocess.call(cmd.split())
            choice = raw_input("remove from cache [Y/n]? ")
            if not choice or choice.lower().startswith("y"):
                cmd = ("reprepro -vv --basedir /home/tshepang/.custom_repo/ "
                       "remove tshepang " + package_name)
                subprocess.call(cmd.split())

if __name__ == "__main__":
    main()

I strongly suspect the code can be better.

As a sidenote, here is sample UI:

apache2.2-common:
      Installed: (none)
      Candidate: 2.2.22-13
      Version table:
         2.2.22-13 0
            500 file:/home/tshepang/.custom_repo/ tshepang/main amd64 Packages
    remove from cache [Y/n]?
    removing 'apache2.2-common' from 'tshepang|main|amd64'...
    Exporting indices...
    Deleting files no longer referenced...
    deleting and forgetting pool/main/a/apache2/apache2.2-common_2.2.22-13_amd64.deb


texts: HackerRank New Year Chaos: arriving at a given list using neighbor swaps

texts:
I am trying to solve the HackerRank New Year Chaos problem where the aim is as follows:

A vector of size n is having values [1,2,3,...,(n-1),n] with no repetition. A kth element can switch only with the (k-1)th element. An element can maximum switch 2 times with its predecessor.

Thus we can say that any kth element should find its place at minimum (k-2)th index

Now, The vector given to the below given function minimumBribes() is the unordered / unsorted one, and I need to find the minimum switched occurred to the sorted vector.

NOTE: If the any element makes more than 2 switches, only print "Too chaotic"

void minimumBribes(vector<int> q) {
  int count = 0;

  for (int p_number = 0; p_number < q.size() - 1; p_number++) {

    if ((p_number+1) != q[p_number]) {
      vector<int>::iterator it = find(q.begin(), q.end(), (p_number+1));
        int index = distance(q.begin(), it);

        for (; index > p_number; index--) {
          if (q[index - 1] - index > 2) {
            cout << "Too chaotic" << endl;
            return;
          } else {
            q[index] = q[index - 1];
            count++;
          }
        }

        q[p_number] = (p_number+1);
    }
  }

  cout << count << endl;
}

The above solution works. but fails for 2 testcases with timeout error.

How to bring down the run time here?


texts:
This is my implementation of quicksort (algorithm taken from Cormen book). This is an in place implementation. Please let us know issues with this or any ideas to make it better. It performs at logN.

import java.util.ArrayList;

public class MyQuickSort {

    /**
     * @param args
     */
    public static void main(String[] args) {

        //int[] a = { 1, 23, 45, 2, 8, 134, 9, 4, 2000 };
        int a[]={23,44,1,2009,2,88,123,7,999,1040,88};
        quickSort(a, 0, a.length - 1);
        System.out.println(a);
        ArrayList al = new ArrayList();
    }

    public static void quickSort(int[] a, int p, int r)
    {
        if(p<r)
        {
            int q=partition(a,p,r);
            quickSort(a,p,q);
            quickSort(a,q+1,r);
        }
    }

    private static int partition(int[] a, int p, int r) {

        int x = a[p];
        int i = p-1 ;
        int j = r+1 ;

        while (true) {
            i++;
            while ( i< r && a[i] < x)
                i++;
            j--;
            while (j>p && a[j] > x)
                j--;

            if (i < j)
                swap(a, i, j);
            else
                return j;
        }
    }

    private static void swap(int[] a, int i, int j) {
        // TODO Auto-generated method stub
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}


texts: Proper naming for objects which have a position and bounds on a plane

texts:
I have an interface which is for an object which has bounds in a 2D plane.

interface Boundable : Positionable {

    /**
     * Returns the [Bounds] (the [Position] and [Size]) of this [Boundable].
     */
    fun bounds(): Bounds

    /**
     * Returns the [Size] of this [Boundable].
     */
    fun size(): Size

    /**
     * Tells whether this [Boundable] intersects the other `boundable` or not.
     */
    fun intersects(boundable: Boundable): Boolean

    /**
     * Tells whether `position` is within this boundable's bounds.
     */
    fun containsPosition(position: Position): Boolean

    /**
     * Tells whether this boundable contains the other `boundable`.
     * A [Boundable] contains another if the other boundable's bounds
     * are within this one's. (If their bounds are the same it is considered
     * a containment).
     */
    fun containsBoundable(boundable: Boundable): Boolean
}

This is something like Rect in the Java SDK for example. Currently Boundable inherits from Positionable:

/**
 * Represents an object which is positionable within its parent.
 * Note that once positioned a [Positionable] can't be moved.
 * If you want re-positionable objects @see [Movable].
 */
interface Positionable {

    fun position(): Position = Position.zero()

}

Positionable is for objects which have a Position within a larger object on the same plane. This setup worked so far but now I need to have 3 versions of Boundable. One, which does not inherit from Positionable (to be used for detached or root objects), one which does and one which is Movable:

/**
 * A [Movable] object is a specialized [Positionable].
 * It can not only be positioned but moved as well.
 */
interface Movable : Positionable {

    fun moveTo(position: Position): Boolean

    fun moveBy(position: Position) = moveTo(position() + position)

    fun moveRightBy(delta: Int) = moveTo(position().withRelativeX(delta))

    fun moveLeftBy(delta: Int) = moveTo(position().withRelativeX(-delta))

    fun moveUpBy(delta: Int) = moveTo(position().withRelativeY(-delta))

    fun moveDownBy(delta: Int) = moveTo(position().withRelativeY(delta))
}

My problem is figured out a name for the variants, but I'm not satisfied with them. I came up with PositionableBoundable and MovableBoundable but they sound weird.

Are these names adequate or should I change them to something more descriptive?


texts:
The code below takes header variables, retrieves the column index, and then, using an Index/Match function, returns data from a matching account number.

The reason it is written this way is because I wanted to make the code "reusable". By being able to change the hard-coded header names, I can update the Macro based on our client.

The code itself is unreasonably slow. It takes 35 secs to pull 4 accounts.

I'm looking to make the code more efficient.
Is there a different approach to making "reusable" code, which would be easier to read and look neater.

   Sub RetrieveData()

Dim Headers(1 To 21, 1 To 2)

 Headers(1, 1) = "StockNbr"
    Headers(2, 1) = "Customer Last Name"
    Headers(3, 1) = "Customer First Name"
    Headers(4, 1) = "Date Sold"
    Headers(5, 1) = "Amount Financed"
    Headers(6, 1) = "Finance Charges"
    Headers(7, 1) = ""
    Headers(8, 1) = "APR Rate"
    Headers(9, 1) = ""
    Headers(10, 1) = "Payment Amount"
    Headers(11, 1) = "Payment Schedule"
    Headers(12, 1) = "Contract Term (Month)"
    Headers(13, 1) = "Year"
    Headers(14, 1) = "Make"
    Headers(15, 1) = "Model"
    Headers(16, 1) = "VIN"
    Headers(17, 1) = "Odometer"
    Headers(18, 1) = "Principal Balance"
    Headers(19, 1) = "Cash Down"
    Headers(20, 1) = ""
    Headers(21, 1) = ""

    Dim FundingSheet As Worksheet
    Dim AccountNumber As Variant
    Dim AccountRange As Range

    Dim i As Integer
    Dim x As Integer
    Set AccountRange = Selection
    Debug.Print AccountRange.Address

    'B/c there is no naming convention, many different static data names
    Set FundingSheet = Sheets("StaticFunding")
    i = 1

    'looking for the column index and attaching to second dimension
    For i = LBound(Headers) To UBound(Headers)
        If Headers(i, 1) = "" Then
            Headers(i, 2) = ""
        Else
            Headers(i, 2) = Application.Match(Headers(i, 1), FundingSheet.Rows(3), 0)
        End If

    Next i

    'retrieving information using Index Match

    For Each Cell In AccountRange
    AccountNumber = Cell.Value
    x = 2
    i = 1

    For i = LBound(Headers) To UBound(Headers)

        If Headers(x, 2) = "" Then
            x = x + 1
        Else
            Cell.Offset(0, x).Value = Application.index(FundingSheet.Columns(Headers(x, 2)), Application.Match(CStr(AccountNumber), FundingSheet.Columns(Headers(1, 2)), 0))
            x = x + 1
        End If

        If x = 22 Then Exit For
    Next i

    Next Cell

    End Sub


texts:
I'm sure everyone here knows what FizzBuzz is. I would like constructive criticism for my solution.

I'm a beginner to programming as a whole and this isn't my first solution, but it's what I think is my best solution. I'd like to see if this is a reasonable solution, or is just plain terrible.

for(var i=1;i<=100;i++) {
var output = "";

    if(i % 15 == 0) {output = "FizzBuzz"}
    else if(i % 3 == 0) {output = "Fizz"}
    else if(i % 5 == 0) {output = "Buzz"}
    else {output = i;}

console.log(output);
}

The output is correct. It's your standard FizzBuzz output.


texts: Two similar MongoDB-querying functions to find distinct and non-distinct documents

texts:
I'd like to remove some of the repeated code in my mongo data access layer. The code is all the same except for these key areas:

Function signature parameters differ between collectionFind and collectionDistinct though they both have a callback cb.
The line below // HERE IS THE LINE THAT VARIES

I suspect I can use a closure to pass in cb to the (innerErr, result) callback but that only solves part of the problem so was curious about other ideas.

  collectionFind: function collectionFind(collectionName, query, fields, options, cb) {
    var url = getUrl();
    if (!url) {
      logger.error('No mongodb connection set');
    } else {
      getConnection(url, (err, db) => {
        if (err) {
          logger.error(`Cannot connect to mongo: ${err}`);
          clearConnection();
        } else {
          // HERE IS THE LINE THAT VARIES
          find(db, collectionName, query, fields, options, (innerErr, result) => {
            if (innerErr) {
              clearConnection();
              cb(innerErr);
            } else {
              cb(null, result);
            }
          });
        }
      });
    }
  },
  collectionDistinct: function collectionDistinct(collectionName, field, filter, cb) {
    let url = getUrl();
    if (!url) {
      logger.error('No mongodb connection set');
    } else {
      getConnection(url, (err, db) => {
        if (err) {
          logger.error(`Cannot connect to mongo: ${err}`);
        } else {
          // HERE IS THE LINE THAT VARIES
          distinctDocuments(db, collectionName, field, filter, (innerErr, result) => {
            if (innerErr) {
              clearConnection();
              cb(innerErr);
            } else {
              cb(null, result);
            }
          });
        }
      });
    }
  }


texts: PHP script to connect to MySQL database using PDO

texts:
Introduction

I am preparing to use a basic script to cover how you can connect to a MySQL database using PDO. This script is meant for educational purposes (introductory class on PHP/MySQL) and does of course not cover all security aspects of database connections.

Points of focus

Conformity to the PSR-1 and PSR-2 standards.
Structure for connecting to database connection.
Security aspects that has not been covered.

Code (settings.php):

<?php
  // Defines database connection information
  $settings = [
    'host'     => '127.0.0.1',
    'name'     => 'c9',
    'port'     => '3306',
    'charset'  => 'utf8',
    'username' => 'admin',
    'password' => 'root'
  ];
?>

Code (db.php):

<?php
  // Includes database connection information
  require_once('../settings.php');

  // Establishes connection to database server
  try {
    $dbh = new PDO(
            sprintf(
              'mysql:host=%s;dbname=%s;port=%s;charset=%s',
              $settings['host'],
              $settings['name'],
              $settings['port'],
              $settings['charset']
            ),
            $settings['username'],
            $settings['password']
    );
    // Prevents emulated prepare statements and sets error mode
    // to PDO::ERRMODE_EXCEPTION
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  // Prints out errors raised by PDO
  catch (PDOException $e) {
    die('Error: ' . $e->getMessage());
  }
?>

The ../ for settings.php indicates that the file is outside document root for security purposes. Much appreciated in advance for any comments that could improve this code.


texts: Toy Vector Library - Magnitude & Unit Vector Functions

texts:
I'm writing a toy vector library in C to learn a bit about the language. The excerpt below shows my vector structure and two functions:

vec2_magnitude calculates the magnitude (length) of a vector
vec2_unit uses the magnitude to calculate the unit vector

#include <math.h>

// A fixed-length vector w/ 2 elements.
typedef struct
{
        double a;
        double b;

} vec2_t;

// Compute the magnitude of a vec2_t.
double vec2_magnitude(const vec2_t *vec)
{
        double a2 = vec->a * vec->a;
        double b2 = vec->b * vec->b;
        return sqrt(a2 + b2);
}

// Compute the unit vector of a vec2_t.
void vec2_unit(const vec2_t *vec, vec2_t *unit)
{
        double mag = vec2_magnitude(vec);
        unit->a = (vec->a / mag);
        unit->b = (vec->b / mag);
}

Currently, vec2_unit takes two vector arguments. It performs the calculation based on the first argument, then stores its result in the second argument. I wrote the function this way so the original vector wouldn't be affected (in case it is still needed).

That being said, I'd like a way to calculate the unit vector in-place, since you may not always need the old vector (in such a situation, an in-place calculation is more convenient). I was originally going to write two functions, but noticed a clever way to achieve both functionalities using only the function shown above.

To operate non-destructively, vec2_unit can be called like this:

vec2_t orig_vector = {1, 1};
vec2_t unit_vector;
vec2_unit(orig_vector, unit_vector);

To operate in-place, vec2_unit can be called like this:

vec2_t orig_vector = {1, 1};
vec2_unit(orig_vector, orig_vector);

I like this solution, and it seems to work. I also understand that C is a language where many things aren't "safe", and just because you can do something doesn't mean you should. Are there any reasons something like this shouldn't be done? Are there other examples of common C functions that work in a similar way? Is there a better way to accomplish what I'm trying to do?

I appreciate all help. Feel free to comment on anything else you see as well. Thanks!


texts: Setting image margins and location based on orientation

texts:
This code is for Android but I guess anyone can take a chance at it.

It does what I want it to do. Just that I am not comfortable with its deep level of nesting and too much of value swapping.

Can this be optimized for readability or in compactness?

for(int imagenum, imagenum <76, imagenum++){

    if (orientation.contentEquals("landscape")
            || orientation.contentEquals("reverse landscape")) {
        params.height = imageheight;
        params.width = imagewidth;
        imageButton.setImageResource(R.drawable.imageback);
        if (imagenum <= 38) {

            params.leftMargin = imagenum * xspaceforeachimage;
            params.topMargin = 0;
        } else {
            params.leftMargin = (imagenum - 39) * xspaceforeachimage;
            params.topMargin = topMargin;
        }
    } else if (orientation.contentEquals("portrait")
            || orientation.contentEquals("reverse portrait")) {
        params.height = imagewidth;
        params.width = imageheight;
        imageButton.setImageResource(R.drawable.imagebacklaid);
        if (imagenum <= 38) {
            params.leftMargin = 0;
            params.topMargin = imagenum * xspaceforeachimage;
        } else {
            params.leftMargin = topMargin;
            params.topMargin = (imagenum - 39) * xspaceforeachimage;
        }
    }
}


texts:
I intend to accept all of the following answers:

y
Y
yes
YES
Yes
plus mixtures, such as yeS, yES, which I didn't intend to accept but it's a consequence of my code
the same applies to No and its variants

#include <iostream>     // std::cout, std::cin
#include <string>       // std::string
#include <algorithm>    // std::transform

int main()
{

    bool answer_valid = false;
    std::string answer;

    do
    {
        std::cout << "Should the password include digits? [Y/n] ";
        std::cin >> answer;

        std::transform(answer.begin(), answer.end(), answer.begin(), ::tolower);

        answer_valid =
            (answer == "y") ||
            (answer == "n") ||
            (answer == "yes") ||
            (answer == "no");

    } while (!answer_valid);

    return 0;

}

It works flawlessly, or it seems so. Is there better approach?


texts: Testing PersonFirstName class as a Value Object

texts:
For reference:

  A Value Object is an immutable type that is distinguishable only by the state of its properties. That is, unlike an Entity, which has a unique identifier and remains distinct even if its properties are otherwise identical, two Value Objects with the exact same properties can be considered equal.

Please see the code below:

public class PersonFirstName
{
    //public string FirstName { get; set; }

    private string _firstName;

    public PersonFirstName(string firstName)
    {
        if (firstName == null)
            throw new ArgumentNullException("Surname");
        if (!PersonFirstName.IsValid(firstName))
            throw new ArgumentException("Invalid value.", "Surname");
        this._firstName = firstName;
        FirstName = firstName;
    }

    public PersonFirstName() //for NHibernate
    {
    }

    public static bool IsValid(string candidate)
    {
        if (string.IsNullOrWhiteSpace(candidate))
            return false;
        if (candidate.Length > 255)
            return false;
        return true;
    }

    public string FirstName
    {
        get { return _firstName; }
        private set
        {
            _firstName = value;
        }
    }

    public override bool Equals(object obj)
    {
        PersonFirstName PersonFirstName = obj as PersonFirstName;
        if (ReferenceEquals(PersonFirstName, null))
            return false;
        return _firstName == PersonFirstName.FirstName;
    }

    public override int GetHashCode()
    {
        return _firstName.GetHashCode();
    }
}

and the Unit Test below:

[Test]
public void Domain_FirstNameValue_ValueObjectCreated()
{
    //Arrange
    var PersonFirstName1 = new PersonFirstName("Ian");
    var PersonFirstName2 = new PersonFirstName("Ian");
    //Act
    var firstNameCompareResult = PersonFirstName1.Equals(PersonFirstName2);
    //Assert
    Assert.True(firstNameCompareResult);
}

I would be grateful for comments on the quality of this test.


texts: Calculate a month later than current month (without rolling over to next month)

texts:
I needed a script for working out billing dates over a period of time.  The date should be the same day every month however if the billing date starts on a date that doesn't exist in another month, then it should be on the last day of that month. This rules out the DateTimeInterval Object, because that causes months to 'rollover' (31/01 becomes 03/03 etc.) which is unacceptable for my use case.

Try as I might, I couldn't find anything in-built to accommodate for this, so I wrote the following, however it seems like a lot of code for what I'm trying to achieve so I was wondering if anyone could suggest a better / in-built way?

$replaceVars = array(
    'effectivedate' => '30-9-2014',
    'vatpc'         => 0.15,
    'paymentamount' => 150.00,
    'duration'      => 12
);

$effectivedateObj = new DateTime($replaceVars['effectivedate']);

$iD = array(
    'd' => $effectivedateObj->format('d'),
    'm' => $effectivedateObj->format('m'),
    'y' => $effectivedateObj->format('Y')
);

$payments = '';

for ($i=0; $i < $replaceVars['duration']; $i++)
{
    $newDate = array(
        'd' => $iD['d'],
        'm' => (($iD['m'] + $i) > 12) ? (($iD['m'] + $i) % 12) : $iD['m'] + $i,
        'y' => (($iD['m'] + $i) > 12 ? $iD['y'] + 1 : $iD['y'])
    );

    if($newDate['d'] > cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']))
    {
        $newDate['d'] = cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']);
    }

    $paymentString = '
';

    $paymentString .= 'Payment Number '.($i+1).'	';
    $paymentString .= ''. $newDate['d'] .'/'. $newDate['m'] .'/'. $newDate['y'] .'	';
    $paymentString .= '&pound;'. round(( $replaceVars['paymentamount'] + ( $replaceVars['paymentamount'] * $replaceVars['vatpc'] )), 2) .'	';

    $paymentString .= '
';

    $payments .= $paymentString;

    echo $paymentString . '
';
}

The top array and the lines that build the string are just for testing, but it still seems like a lot of code?

Also I have no idea how necessary my parenthesis are when creating ternary statements, and I do feel a bit neurotic about the amount that I use, so some advice on that would be appreciated.


texts: Recursion vs iteration of tree structure

texts:
Some recursive code is part of a particularly slow path of a project. Out of curiosity I was playing around with reimplementing the code using stack context iteration instead of recursion. Below are snippets reduced to just the iteration patterns of tree elements using a DOM structure for simplicity.

I was surprised when benchmarking the code that the recursive variant was faster than iterative approaches. Is there a flaw in my implementations (they each iterate the same number of elements to the same depth)? The snippets aren't strictly equivalent in the order they touch the elements though I doubt that effects the performance.

Recursive depth first approach

function iterate(current, depth) {
    var children = current.childNodes;
    for (var i = 0, len = children.length; i < len; i++) {
        iterate(children[i], depth + 1);
    }
}
iterate(parentElement, 0);

Iterative breadth first forwards

var stack = [{
    depth: 0,
    element: treeHeadNode
}];
var stackItem = 0;
var current;
var children, i, len;
var depth;

while (current = stack[stackItem++]) {
    //get the arguments
    depth = current.depth;
    current = current.element;
    children = current.childNodes;
    for (i = 0, len = children.length; i < len; i++) {
        stack.push({ //pass args via object or array
            element: children[i],
            depth: depth + 1
        });
    }
}

Iterative breadth first backwards approach

var stack = [{
    depth: 0,
    element: treeHeadNode
}];
var current;
var children, i, len;
var depth;
while (current = stack.pop()) {
    //get the arguments
    depth = current.depth;
    current = current.element;
    children = current.childNodes;
    for (i = 0, len = children.length; i < len; i++) {
        stack.push({ //pass args via object or array
            element: children[i],
            depth: depth + 1
        });
    }
}

I was expecting the second snippet to be fastest in JS (no array popping), is there opportunity for further optimization to improve the performance of the iterative approach? I believe part of the slowness is creating the arguments in an object (i.e. {depth: depth+1,element: someElement}). The recursive snippet is more intuitive and explicit and may benefit from tail recursion in ES6 interpretors.

Repeating myself, is there a more performant way to iterate tree data structures in JavaScript than recursively?

JSPerf comparing the snippets


texts: Hacker Rank Challenge : Find count of substrings which are special palindrome

texts:
I am getting timeout for test cases having very large input.

-= Challenge Link =-

-= Test case example =-

Code is working fine as can be checked on ideone. (Note: Here fout has been replaced with cout.)

  Problem Statement :

  A string is said to be a special palindromic string if either of two
  conditions is met:

  All of the characters are the same, e.g. aaa.
  All characters except the middle one are the same, e.g. aadaa.

  A special palindromic
  substring is any substring of a string which meets one of those
  criteria. Given a string, determine how many special palindromic
  substrings can be formed from it.

  For example, given the string s = mnonopoo , we have the following special
  palindromic substrings: {m, n, o, n, o, p, o, o, non, ono, opo, oo}.

  Function Description

  Complete the substrCount function in the editor below. It should
  return an integer representing the number of special palindromic
  substrings that can be formed from the given string.

  substrCount has the following parameter(s):

  n: an integer, the length of string s
  s: a string

  Input Format

  The first line contains an integer, n , the length of s.  The second line
  contains the string .

  Constraints

  1 ≤ n ≤ 10^6

  Each character of the string is a lowercase alphabet, ascii[a-z].

  Output Format

  Print a single line containing the count of total special palindromic
  substrings.

  Sample Input 0

5
asasd

  Sample Output 0

7

  Explanation 0

  The special palindromic substrings of s = asasd are {a, s, a, s, d, asa, sas}.

  Sample Input 1

7
abcbaba

  Sample Output 1

10

  Explanation 1

  The special palindromic substrings of s = abcbaba are {a, b, c, b, a, b, a, bcb, bab, aba}.

  Sample Input 2

4
aaaa

  Sample Output 2

10

  Explanation 2

  The special palindromic substrings of s = aaaa are {a, a, a, a, aa, aa, aa, aaa, aaa, aaaa}.

Code:

#include <bits/stdc++.h>

using namespace std;

// Complete the substrCount function below.
long substrCount(int n, string s) {

    long int length_sub = 2;
    long int count = n;
    while(length_sub <= n){
        for(long int i = 0; i <= n - length_sub ; i++){
            string sub = s.substr(i, length_sub);
            //cout << sub << " ";
            string rev_sub(sub);
            reverse(rev_sub.begin(), rev_sub.end());
            //cout << rev_sub;;
            char c = sub[0];
            int flag = 0;
            for(long int j = 0; j < sub.length() / 2; j++){
                if(sub[j] != c || rev_sub[j] != c){
                    flag = 1;
                    break;
                }
            }
            if(flag == 0){
                //cout << " - Special\n";
                count++;
            }
            // else{
            //     cout << "\n";
            // }
        }
        length_sub++;
    }
    return count;

}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string s;
    getline(cin, s);

    long result = substrCount(n, s);

    fout << result << "\n";

    fout.close();

    return 0;
}


texts:
I'm looking for feedback on my atoi implementation here in C. Any feedback would great. I made my own atoi for fun and to learn about it.

I'm not trying to replace the standard library version. Reinventing the wheel is fun to me.

#include <limits.h> /* for LONG_MAX, INT_MAX */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define IS_ASCII_DIGIT(c) ((c >= 48) && (c <= 57))

long __my_atoi(char* buffer)
{
    long ret = 0;
    bool neg = false;

    if (*buffer == '-') {
        neg = true;
        buffer++; /* advance to next position to pass ascii check */
    }

    while (*buffer) {
        if (IS_ASCII_DIGIT(*buffer)) {
            ret = ret * 10 + (*buffer - '0');
        } else {
            fprintf(stderr, "Fatal Error: unexpected '%c' passed to %s\n", *buffer, __func__);
            exit(EXIT_FAILURE);
        }
        buffer++;
    }

    return neg ? -ret : ret;
}

int main(void)
{
    printf("%ld\n", __my_atoi("-10004"));
    return EXIT_SUCCESS;
}


texts:
I am new to the divide and conquer paradigm.  I wanted to verify that there's nothing wrong with this implementation of binary search.

I ran it a few times and it does print the correct result, but I also wanted a sanity check and any possible improvements.

def search(array, item):

    if len(array) == 1:
        if array[0] == item:
            return 1
        return 0

    mid = len(array) // 2
    x = array[:mid]
    y = array[mid:]

    found = []

    found.append(search(x, item))
    found.append(search(y, item))

    for elm in found:
        if elm ==  1:
            return True

    return False

print(search([1,2,3,4], 8))
print(search([1,2,3,4], 3))

Also, the running time of this is \$O(n log(n))\$, correct? \$O(log(n))\$ being the recursion and \$O(n)\$ being the loop that checks the result list.