texts: Stock price history SQL database with Python, Pandas and yfinance

texts:
I have a program that lists and downloads a year of history of two stock tickers (AMZN and GOOG). I download these to a SQL database, C:\Databases\hist_prices.db, inside a table called hist_prices_tickers.

How can I organize my code for a more Pythonic approach?

I intend to use this SQL database for a machine learning project later on. Is this method of calling the database the best way possible?

import yfinance as yf
import pandas as pd
import sqlite3, shutil, glob, os
from pathlib import Path

NewFolderPath  = r"C:\Databases\\"
isFile = os.path.exists(NewFolderPath)
if isFile is False:
    Path(NewFolderPath).mkdir(parents=True, exist_ok=True)

df = pd.DataFrame()
df2 = pd.DataFrame()
tickers = ["AMZN","GOOG"]

#SQL Connect
conn = sqlite3.connect(NewFolderPath+'hist_prices.db')
c = conn.cursor()
dest = sqlite3.connect(':memory:')
conn.backup(dest)
conn.commit()

for ticker in tickers:
    tkr = yf.Ticker(ticker)
    hist = tkr.history(period="1y")
    df2 = df2.append(hist)
    df2['Ticker'] = ticker
    df = df.append(df2.reset_index())

    df.fillna(0, inplace=True)
    df = df.applymap(str)
    df = df.apply(lambda x: x.str.replace('.', ','))
    df['Date'] = df['Date'].apply(pd.to_datetime)
    df.to_sql('hist_prices_tickers', conn, index=False, if_exists='append')

df = pd.read_sql_query("SELECT * from hist_prices_tickers", conn)
df.drop_duplicates(subset=None, keep="last", inplace=True)
df.to_sql('hist_prices_tickers', conn,  if_exists='replace', index=False)

print(df)

conn.close()


texts:
I am in the progress of creating a MVC structured website. I've opted to make my own instead of using pre-constructed MVC systems as a way to teach myself better coding and understanding how applications work. I've got everything laid out, but I'm not happy with my routing system. It is VERY crude and I'd like it to be more robust.

I'd like to get feedback to help improve my code.

Below is the full code for index.php, where my routing code is:

<?php

session_start();

// Estabilish Database Connections and system defaults
include('config.php');

function setReporting() {
    if (DEVELOPMENT_ENVIRONMENT == true) {
        error_reporting(E_ALL);
        ini_set('display_errors','On');
    } else {
        error_reporting(E_ALL);
        ini_set('display_errors','Off');
        ini_set('log_errors', 'On');
        ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');
    }
}
function db_connect() {
    $connection = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD);
    if (!$connection) {
        die("
Error Connecting to Database
");
    }
    if(!mysql_select_db(DATABASE, $connection)) {
        die("
Database Does Not Exist
");
    }
    return $connection;
}
function hook() {
    $params = parse_params();
    $url = $_SERVER['REQUEST_URI'];
    $url = str_replace('?'.$_SERVER['QUERY_STRING'], '', $url);

    $urlArray = array();
    $urlArray = explode("/",$url);
    var_dump($urlArray);
    if (isset($urlArray[2]) & !empty($urlArray[2])) {
        $route['controller'] = $urlArray[2];
    } else {
        $route['controller'] = 'front'; // Default Action
    }
    if (isset($urlArray[3]) & !empty($urlArray[3])) {
        $route['view'] = $urlArray[3];
    } else {
        $route['view'] = 'index'; // Default Action
    }
    include(CONTROLLER_PATH.$route['controller'].'.php');
    include(VIEW_PATH.$route['controller'].DS.$route['view'].'.php');
    var_dump($route['controller']);
    var_dump($route['view']);
    var_dump($urlArray);
    var_dump($params);

    // reseting messages
    $_SESSION['flash']['notice'] = '';
    $_SESSION['flash']['warning'] = '';
}

// Return form array
function parse_params() {
    $params = array();
    if(!empty($_POST)) {
        $params = array_merge($params, $_POST);
    }
    if(!empty($_GET)) {
        $params = array_merge($params, $_GET);
    }
    return $params;
}

// Prepare General Application Models
require($_SERVER['DOCUMENT_ROOT'].'/'.APP.'/'.'models/'.'general.php');

setReporting();
date_default_timezone_set(get_timezone());
$current_theme = current_theme();
hook();

if($_SESSION['flash']['notice']) {
    echo $_SESSION['flash']['notice'];
}

One big problem is that my hook call won't work properly when the urls are two levels deep. Say I wanted to visit mywebsite.com/admin, it would work, however mywebsite.com/admin/dashboard would not. The problem is in the arrays. How could I get the array to load content after the 2nd level along with the second level?

Would it be best to create an array like this?

Array
     - controller
     - view
          - dashboard

What would be the best way to set up "custom" URLs?

If I were to put in mywebsite.com/announcement, it would check to see if it has controllers.  Failing that, it would check to see if it has custom content (maybe a file of the same name in "customs" folder, and then if there's nothing, execute the 404 page not found stuff).  This isn't a priority question though, but loosely associated in how the code works so I thought it best to add.


texts:
I am looking for a elegant solution to this. I am new to Spring framework. I have a method:

public String getStringProperty(String property) {
        Object value = SomeWrapper.getPropertyValue(property);
        return (value != null) ? String.valueOf(value) : "";
    }

The immediate upstream method is:

public String getValueForHeader(String header) {
        return getStringProperty(LOOKUP_TABLE.get(header));
    }

Where LOOKUP_TABLE is an ImmutableMap (google guava). An example representation of it:

private final ImmutableMap<String, String> LOOKUP_TABLE = ImmutableMap.<String, String>builder()
            .put(LogHeaders.Phone, "Person.phone")
            .put(LogHeaders.Address, "Person.personal.address")
            .put(LogHeaders.Email, "Person.billing.contact.primary.email")
            .put(LogHeaders.Ip, "Person.ip")
            .build();

So, when I call getStringProperty method with property "Person.billing.contact.primary.email" I get a "" String. My aim here is to return empty String when some property does not exist. For example if "Person.billing.contact.primary.email" does not have "email" set in address an empty String is returned. Now if "contact" or "primary" is not set I would get a NullValueInNestedPathException but I should return an empty String.

One way to deal with this is to introduce the try catch lock in this method and have the catch block return empty string.

public String getStringProperty(String property) {
    try {
        Object value = transactionWrapper.getPropertyValue(property);
        return (value != null) ? String.valueOf(value) : "";
    } catch (NullValueInNestedPathException e) {
        return "";
    } catch (NotReadablePropertyException nr) {
        LOGGER.error("Invalid property {} ", property);
        return "!invalid property!";
    }
}

The NotReadablePropertyException is to warn me when I am trying to get some property which does not exist (or getter for that property is not readable).

The other solution could be to throw same exception and let methods upstream worry.

Is there some alternative, elegant way to handle this inside my getStringProperty() method ?


texts:
I made a simple program for my study that calculates words in a text files and prints every word and its repeated times in the files.

How can I improve this code?

#include <future>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>

typedef std::unordered_map<std::string, std::size_t> Words;

Words wordsInFile(const std::string& fileName)
{
    std::ifstream file(fileName);
    if (!file.is_open())
    {
        throw "Can't open the file" + fileName;
    }

    Words loadFromFile;

    for (std::string word; file >> word;)
    {
        ++loadFromFile[word];
    }

    return loadFromFile;
}

int main(int argc, char *argv[])
{
    std::vector<std::future<Words>> futures;

    for (int i = 1; i < argc; ++i)
    {
        futures.push_back(std::async([=] { return wordsInFile(argv[i]); }));
    }

    Words words;

    for (auto& i : futures)
    {
        const auto results = i.get();

        for (const auto& j : results)
        {
            words[j.first] = j.second;
        }
    }

    std::cout << "Word\tRepeated Times\n-------------------------\n";
    for (const auto& i : words)
        std::cout << i.first << "\t\t" << i.second << '\n';
}

test.txt

File system is huge subject need more work out. file is plain text file
This is some junk words. simple program for words counting in text file. 1 2 3
2 2 2 2
@ % & ^ *
all so good
this test text file

Output:

Word    Repeated Times
-------------------------
File            1
out.            1
1               1
system          1
2               5
is              3
need            1
huge            1
subject         1
work            1
more            1
%               1
file            3
plain           1
text            3
This            1
some            1
junk            1
program         1
words.          1
simple          1
for             1
words           1
counting                1
in              1
file.           1
so              1
3               1
@               1
&               1
^               1
this            1
*               1
all             1
good            1
test            1


texts: Compose valid subtractions using all digits from a set

texts:
I have created a brainteaser, which I called the "impossible problem" (see this video I made).  The aim is to create a valid 3-digit subtraction which uses every digit from 1 to 9 once. Here is an example of one of the solutions: 873-254=619.

After finding it hard to come up with answers I created this program. What it basically does is iterate through every possible 3-digit subtraction and if it finds one which fits the criteria, it prints it.

from math import trunc

def solver(number,number2, numberofdigits):
    seq = str(number),str(number2), str(number - number2)
    digits = "".join(seq)
    goodChecks = 0
    count= numberofdigits/3
    for i in range(1,10):
        if digits.count(str(i)) == count:
            goodChecks += 1
    if goodChecks == 9:
        return digits
    else:
        return False

middlenumber =[]
successes = 0
num_of_digits = int(input("please enter a number of digits, which is a multiple of 3"))
if num_of_digits == 3:
    minY = 381
    maxY = 987
if num_of_digits == 6:
    minY =246912
    maxY = 998877

if num_of_digits == 3:
    minX = 123
if num_of_digits == 6:
    minX =123123

for y in range(minY, maxY+1):
    numberlist = []
    if y%100 == 0:
        print(y)
    for x in range(minX,trunc(y/2)):
        digits = solver(y,x,num_of_digits)
        if digits is not False:
            successes += 2
            print(digits)
            numberlist.extend([x,y-x])
            middlenumber.extend([x, y-x])

print("")
print("I found: ", successes, " successful solution to your brainteaser")
if successes < 20:
    print("there were almost no solutions")
elif successes < 100:
    print("there were not many solutions")
elif successes < 1000:
    print("there were more than a hundred solutions it is definitely not impossible :)")
else:
    print("that's a lot of successes")

print("There were ", len(middlenumber) - len(set(middlenumber)) , " duplicates, by the way :)")

My program worked quite well but then I decided could you do the same for 6 digits? For the 3 digit problem the program had 96 possiblities to iterate over. Which is a measly 531,441 iterations. However for the 6 digit there is 912 possiblities, which is a colossal 282,429,536,481 iterations. This is going to take my computer days to solve.

I have already tried optimizing my program but I can't figure out how to do it any faster.


texts: Lorentz Attractor visualization using functional programming

texts:
I have been working on this Lorenz Attractor visualization for the past day. I am currently also trying to change my coding style into a more functional programming one.

I find it quite hard, to be honest, especially the "Only use pure functions." rule. That mostly means no side effects and functions that perform 1 small task. The "No side effect." rule is, of course, impossible while drawing on the HTML canvas. So I am looking for performance optimization and code style tips for FP in general.

I also should like to pass the 3 global variables (x, y, z) as parameters when calling the update function ("No global variables allowed.") however I have had no luck so far. I can't find a way to keep them from resetting while using parameters. Unlike the draw function that calls itself. Any help is welcome, thanks for your time.

https://jsfiddle.net/9r8qcgnh/3/

{
  const canvas = document.querySelector('#canvas')
  const ctx = canvas.getContext('2d')
  ctx.fillStyle = 'rgb(255, 255, 255)'
  ctx.translate(500, 400)
  ctx.scale(10.5, 10.5)

  let x = 0.01
  let y = 0.0
  let z = 0.0

  function update () {
    const a = 10.0
    const b = 28.0
    const c = 8.0 / 3.0
    const dt = 0.015
    const dx = a * (y - x) * dt
    const dy = (x * (b - z) - y) * dt
    const dz = (x * y - c * z) * dt
    x = x + dx
    y = y + dy
    z = z + dz
    return { x: x, y: y, z: z }
  }

  function draw (hue) {
    const { x, y } = update()
    hue = hue || 0
    hue >= 240 ? (hue = 0) : hue++
    ctx.fillStyle = `hsl(${hue},100%, 50%)`
    ctx.fillRect(x, y, 0.1, 0.1)
    setTimeout(() => {
      return draw(hue)
    }, 5)
  }

  draw()
}


texts: Password Attacker (Google apac test problem)

texts:
Original Problem

Short Summary:

  Given a \$M\$ possible characters all of which must be used at least
  once, find the number of possible combinations of length (exactly)
  \$N\$.

  The first input contains the number of cases, followed by pairs of M,
  N. Output is modulo 1000000007(\$10^9+7\$).

  Example Input:

4
1 1
3 4
5 5
15 15

  Example Output:

Case #1: 1
Case #2: 36
Case #3: 120
Case #4: 674358851

The stupid solution is to simply generate all possible repeated_permutations and then exclude the ones which do not use at least M different characters (this of course is painfully slow).

def num_pw_slow(m,n)
  m.times.to_a.repeated_permutation(n).count do |row|
    m.times.map {|i| row.include? i}.all?
  end
end

The real solution:

It's noticeable that the number of solutions which include all M characters is also: (The number of repeated permutations) \$ - \$ (the number of repeated permutations missing at least one character).

The number of repeated permutations is simply \$m^n\$. The second is a little more involved. Combinations are given by \$n!/ (n-k)!k!\$ where \$n=m\$ and \$k = m-1\$. Permutations are \$(m-1)^n\$, the tricky part is we need the set of permutations, since each of the \$(m-1)\$ possible combinations differs from another by a single character, its repeated_permutations will contain a duplicates for all permutations which exclude that character.

For example if m=3, n=4, there are \$3^4\$ repeated_permutations possible - with repeated permutations of ab, bc, ca (possible combinations of m, with length m-1) missing one required character when expanded to length n, the set operation over which needs to eliminate duplicates from repeated_permutations of a, b, c So the solution is then:

3**4 - (2**4*3 - 1**4*3)

This can be generalized for any m, n e.g.

m**n - (m-1)*num_combinations**n
#second term is the number of duplicates amongst repeated_permutations of (m-1)
+ (m-2)*num_combinations**n
#third term is the number of duplicates in the second term
- (m-3)*num_combinations**n
#fourth term is duplicates in the third term
+ (m-4)*num_combinations**n
#and so on

Which gives the following code in Ruby:

(m**n) - (1..m-1).reduce(0) { |sum, i| sum + (i % 2 == 0 ? -1 : 1)*combinations(m, m-i)*(m-i)**n }

Full Solution:

def factorial(num)
  (1..(num.zero? ? 1 : num)).reduce(:*)
end

def combinations(n, k)
  factorial(n) / (factorial(n-k)*factorial(k))
end

def num_pw(m, n)
  (m**n) - (1..m-1).reduce(0) { |sum, i| sum + (i % 2 == 0 ? -1 : 1)*combinations(m, m-i)*(m-i)**n }
end

num_cases = gets.chomp.to_i
num_cases.times do |num|
  m, n = gets.chomp.split.map(&:to_i)
  puts "Case ##{num+1}: #{num_pw(m, n) % (10**9+7)}"
end

This took me over three hours to figure out (well over the exam running time) and quite inconsistent with my times on other problems (which are usually close or slightly better than average) - so for whoever solved this in under 45 minutes or so, I'd be very much interested how. Math SE gives a concise solution with the use of Sterling's number (I'd never heard of it before and I'm not sure if this is expected knowledge or not?)


texts: Automatically backup website files and database

texts:
For each of my various websites, I back up the web site files and the associated database for into a single dated compressed archive file (one zip file per website) and download that to my local Windows Vista machine.  My websites are hosted on Unix machines accessible via ssh.  I've decided to use Python Fabric as it seems to be well-fit for the job.

This works but it's kind of a mess because I just hacked it together.  I want to make it cleaner and a little more generalized.  For example, right now it hard-codes where I'm storing web apps on the server, but actually for some of my websites they are stored in different places.  Also, it feels a little wonky to save a db file to a web file directory, but I'm not sure how else I can easily get it into the zip archive.

import time
from fabric.api import *

env.hosts = ['example.com']
env.user = 'someuser'
env.password = 'somepassword'

def backup_database(app_name, db_name):
    db_passwords = {'somedatabasename': 'somedbpassword'}
    mysqldump_command = 'MYSQL_PWD=%(password)s ionice -c2 -n6 mysqldump -u' +
        ' %(database_name)s %(database_name)s ' +
        '> ./webapps/%(app_name)s/%(database_name)s.sql' % {
        'password': db_passwords[db_name],
        'database_name': db_name,
        'app_name': app_name
        }
    run(mysqldump_command)

def backup_site(app_name):
    date = time.strftime('%Y-%m-%d')
    zip_filename = '%(app_name)s-%(date)s.zip' % { 'date': date, 'app_name': app_name }
    zip_command = 'zip -r %(zip_filename)s ./webapps/%(app_name)s > /dev/null' % {
        'zip_filename': zip_filename, 'app_name': app_name }
    run(zip_command)
    get(zip_filename, zip_filename)
    run('rm ' + zip_filename)

def backup_webapp(app_name, db_name):
    backup_database(app_name, db_name)
    backup_site(app_name)
    rm_command = 'rm $HOME/webapps/%(app_name)s/%(database_name)s.sql' % {
        'database_name': db_name,
        'app_name': app_name
    }
    run(rm_command)

def backup():
    backup_webapp('somewebappfoldername', 'somedatabasename')

Using the fabric tool I call the script like this:

  c:> fab backup

If you don't know fabric, the script file is Python and the run commands are executed via ssh on the remote server. And the get command will pull a file from the remote server to the local machine.

What it does is:

Backup database to a an SQL file and put it in webdirectory
Zip web directory
Download zip to my local machine
Delete the zip file on the server and delete the database backup from the web directory


texts:
I'm writing a templatized container and wanted to use an universal reference for the Add(T&& object) function. Check out isocpp if you need an update on your universal/rvalue references. A quick example from that page states that, since the class is templatized, T&& is fully specified and therefore a rvalue, not an universal reference.

template <class T, class Allocator = allocator<T> >
class vector {
public:
    ...
    void push_back(T&& x);       // fully specified parameter type ⇒ no type deduction;
    ...                          // && ≡ rvalue reference
};

This means that I cannot pass lvalues to the push_back function above.

vector<T> list;

list.Add(T()); // rvalue, compiles fine.

T data;
list.Add(data); // lvalue, does not compile.

In the case of std::vector this is solved by having a push_back(const T& object) overload.
However, since the code in my Add function is quite complex, I didn't want to copy it over.

However, if I am to templatize my add function, it does become universal reference. So I came up with the following code.

#include <iostream>
#include <type_traits>
#include <vector>
using namespace std;

template <class T>
class Container
{
    public:
    template <class UR = T>
    void Add(UR&& object)
    {
        static_assert(std::is_same<std::remove_cv_t<std::remove_reference_t<UR>>, T>::value, "UR and T should be the same!");
        m_Vector.push_back(std::forward<UR>(object));
    }
    std::vector<T> m_Vector;
};

class Data
{
    public:
    int x;
    int y;
};

int main() {
    Container<Data> list;
    Data d;
    list.Add(d);
    return 0;
}

I've added the static assert to make sure that people do not actually templatize the Add function. Does anyone know a cleaner solution, since this feels a bit of template magic? Should I follow the std method and just copy my add function (which is a bit more complex than this minimal example)? Can anyone come up with a case where my solution will not work?

Here is a small ideone version for you to play around with.


texts: Nicely tabulate a list of strings for printing

texts:
I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns.  I have the following code, which works as I want it to currently, but I feel it is a bit ugly.  How can I simplify it/make it more pythonic (without changing the output behaviour)?

For starters I think I could probably use the alignment '<' option of the str.format stuff if I could just figure out the syntax properly...

def tabulate(words, termwidth=79, pad=3):
  width = len(max(words, key=len))
  ncols = max(1, termwidth // (width + pad))
  nrows = len(words) // ncols + (1 if len(words) % ncols else 0)
  #import itertools
  #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue=''))  # row-major
  table = [words[i::nrows] for i in xrange(nrows)]                          # column-major
  return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table)


texts:
I'm new to programming and started with some tutorials about C++ on YouTube. Now I was wondering how I should continue solving below. It does work but already it has been like a lot of code to write. And I have more linetypes to define. So hope someone can point out a better way

std::string filepath = "path/to/file.ext";
std::ifstream stream(filepath);
std::string line;
int i = 1; //For debug purpose
while (getline(stream, line))
{
    if (line!= "" && line.at(0) == '0')
    {
        std::cout << "Line "<< i << " type 0: " << line << std::endl;
    }
    else if (line != "" && line.at(0) == '1')
    {
        std::cout <<  "Line " << i << " type 1: " << line << std::endl;
    }
    else if (line != "" && line.at(0) == '2')
    {
        std::cout << "Line " << i << " type 2: " << line << std::endl;
    }
    else if (line != "" && line.at(0) == '3')
    {
        std::cout << "Line " << i << " type 3: " << line << std::endl;
    }
    else if (line != "" && line.at(0) == '4')
    {
        //Example string: 4 16 -40 0 -20 -40 24 -20 40 24 -20 40 0 -20
        std::cout << "Line " << i << " type 4: " << line << std::endl;
        std::stringstream iss{ LDrawLine };

        float lineType{}, color{}, x1{}, y1{}, z1{}, x2{}, y2{}, z2{}, x3{}, y3{}, z3{}, x4{}, y4{}, z4{};
        iss >> lineType >> color >> x1 >> y1 >> z1 >> x2 >> y2 >> z2 >> x3 >> y3 >> z3 >> x4 >> y4 >> z4;
        //What I could do is make a line like below for every coordinate. The color and the lineType need to be handled different
        //The positions is passed in to the function. Afterwords i need to draw the quads.
        (*positions).push_back(  0.0f); //so else i need to write this code 16 times for this linetype and still have some other line types to go
    }
    else if (line != "" && line.at(0) == '5')
    {
        std::cout << "Line " << i << " type 5: " << line << std::endl;
    }
    else
    {
        std::cout << "Line " << i << " No type" << std::endl;
    }
    i++;
}

If anyone could give me some advice on how to handle this or a tutorial which can help me on this. The code does what it needs to do. I only want it more elegant and why less to type.


texts: Serving images from a Raspberry Pi camera over HTTP

texts:
I have a Pi with a camera module that I control with Python.

I created a web server with web.py that allows me to make HTTP requests to the PI to retrieve an image. There are two optional parameters to specify the width and height of the image. The code looks like this (imports omitted):

urls = (
    '/capture', 'Capture'
)

# start with default values for resolution
width = 1024
height = 768

if __name__ == "__main__":

    app = web.application(urls, globals())
    app.run()

class Capture:
    def GET(self):
        input = web.input(w="0", h="0")                 # reading user input of resolution values for

        input.w = int(input.w)                          # to integer
        input.h = int(input.h)

        if input.w == 0:
            input.w = width                             # no width given, use saved one
        else:
            input.w = max(0,min(2592, input.w))         # clamp to range of valid values

        if input.h == 0:
            input.h = height                            # no height given, use saved one
        else:
            input.h = max(0,min(1944, input.h))         # clamp to range of valid values

        camera = picamera.PiCamera()                    # camera
        camera.resolution = (input.w, input.h)
        camera.capture('picture.jpg')                   # capture image to file
        camera.close()

        web.header('Content-Type', 'image/jpg')
        return open('picture.jpg',"rb").read()          # read image from file and respond

I understand that the code handling the width and height is not very elegant and could be shorter.

To get an image, I can enter http://<PI IP address>/capture in a browser. The problem is that it takes quite a while (1311ms): waiting 1264ms and receiving 47ms.

The results are obviously the same on different browsers because this is a server-side issue.

How can I get the image more quickly?

I think saving to an image file first and reopening that to get the return value is redundant (and possibly slow), but I don't know how to make the capture() function return the value directly (so that I could return it to the client directly). I do not necessarily need jpeg format.


texts: Queries for the number of users seen each day

texts:
The below code returns an array filled with the number of users last seen for each day for $dayCount number of days that is specified via a parameter into the function.
It does this by executing a database query for each day from the previous day going back $dayCount amount of days, and another function produces from this data to provide an output in CSV-style formatting for a graph.

This essentially means that if, say, I wanted the number of users last seen on each day for the last thirty days, a total of 30 database queries will be run.

To me this seems incredibly inefficient, but I can't think of a way around this myself. Can anything be done to make this more efficient?

function GetUserCountFromDays($dayCount) {
    $arrCnt = array();
    $baseQuery;
    $result;
    for ($day = $dayCount; $day >= 1; $day--) {
        $baseQuery = "SELECT * FROM example.servers WHERE last_seen >
                      UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -" . $day . " DAY))";
        $result = ConnectToMySQL()->query($baseQuery);
        if ($result){
            array_push($arrCnt, $result->num_rows);
        }
    }
    return $arrCnt;
}


texts: Haskell: Efficient and clear list concatenation

texts:
I'm trying to write a function explodeBy:

explodeBy :: Int -> [Int] -> [Int]
explodeBy n arr = foldr (\x acc-> (take n.repeat) x ++ acc ) [] arr

This works as follows:

λ> explodeBy 2 [1,2,3]
[1,1,2,2,3,3]

The above uses list concatenation, so I tried writing a more efficient version:

explodeBy2 n arr = foldr (\x acc -> f n x acc) [] arr

f 0 _ rest = rest
f rep val rest = f  ( rep -1) val (val:rest)

Though this looks ugly, I expected it would work better. Reason: here we are using the (:) operator. Since rest is larger than (take n.repeat) x, I believe the second approach should have always been faster.

Surprisingly:

λ> sum $ explodeBy2 500 [2..1001]
250750000
(0.48 secs, 199527400 bytes)
λ> sum $ explodeBy 500 [2..1001]
250750000
(0.14 secs, 102259320 bytes)

explodeBy2 is consuming more time and memory!

Is there something wrong with this code or my understanding of (++)? Are there also any tips on how to write explodeBy better?

PS: This is where I got the impression ++ isn't efficient. Is this outdated?


texts:
I really like the ruby ? : syntax for if/else statements.

However, I'm not sure how to do the following with a nested statement:

if information.is_empty?
  if leader? || possessor?
    link_to('update ' + contextual('your') + ' credentials!', edit_user_path)
  else
    user.name + ' hasn\'t entered this info!'
  end
else
  information
end

Should I bother? Does the ? : syntax (for want of a term!) actually make code pretty unreadable and non-self-documenting?

If you think I should use the ? : syntax, how would I tackle this?


texts: php Laravel - given a certain argument, call different function

texts:
I am building a simple calendar with recurring events.

CalendarEvent.php

id
start_date

CalendarRecurringPattern.php

parent_id
pattern_type // daily, weekly, monthly, yearly ...

Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is the function getNextOccurrence(), I'd like to refactor the if/else block because it's not very clean. Here it is:

use \Carbon\Carbon;
....

public function getNextOccurrence(Carbon $startDate) {

    $pattern_type = $this->getPatternType() // daily, weekly...

    if ($pattern_type == 'daily') {
        $startDate->addDay();
    } else if ($pattern_type == 'weekly') {
        $startDate->addWeek();
    } else if ($pattern_type == 'monthly') {
        $startDate->addMonth();
    } else if ($pattern_type == 'yearly') {
        $startDate->addYear();
    }

}

Thanks!


texts: Critique some Ruby + RSpec Code for a SERP checker

texts:
I found a SERP checker written in PHP and I decided, in order to better learn to program, I would re-write it in Ruby.

All I have written so far takes a list of keywords that a user inputs and cleans the list and turns each keyword into a url for Google search.

Here is the code:

require 'sinatra'
require 'rspec'
get '/serp_checker' do
  "<form action='/ranked' method='post'>
  Keyword
  <textarea name='keyword' id='keyword' type='text' /></textarea>
  URL
  <input name='url' id='url' type='text' />
  <input type='submit' value='Go!' />
  </form>"
end

def clean_up_keywords(str)
  str.gsub("\n", ",").delete("\r").split(',')
end

def clean_up_list(arr)
  arr.reject(&:empty?).each(&:lstrip!)
end

def make_strings_url_friendly(arr)
  arr.each do |e|
    e.gsub!(" ", "+")
  end
end

def make_urls(arr)
  arr.map {|e| "http://www.google.com/search?num=100&q=" + e}
end

post '/ranked' do
  dirty_list = clean_up_keywords(params[:keyword])
  clean_list = clean_up_list(dirty_list)
  url_ready_list = make_strings_url_friendly(clean_list)
  url_list = make_urls(url_ready_list)
end

Here is the spec:

require_relative '../lib/rankypanky.rb'

describe "#clean_up_keywords" do
  it "should push items separated by a newline into array as separate items" do
    clean_up_keywords("apples\noranges").should == ["apples", "oranges"]
  end
  it "should delete all \r chars" do
    clean_up_keywords("Chat\r").should == ["Chat"]
  end
  it "should push items separated by commas into an array" do
    clean_up_keywords("Chat, Meta, About").should == ["Chat", " Meta", " About"]
  end
  it "should push items separated ONLY by a \s char into array as one item" do
    clean_up_keywords("New York, apples").should == ["New York", " apples"]
  end
end

describe "#clean_up_list" do
  it "should not include empty strings/items in array" do
    clean_up_list(["apples", "", "oranges"]).should == ["apples", "oranges"]
  end
  it "should remove any leading white space from items in array" do
    clean_up_list([" oranges", "apples"]).should == ["oranges", "apples"]
  end
end

describe "#make_strings_url_friendly" do
  it "should replace /s with a +" do
    make_strings_url_friendly(["oranges apples"]).should == ["oranges+apples"]
  end
end

describe "#make_urls" do
  it "should append array items to http://www.google.com/search?num=100&q=" do
    make_urls(["pie"]).should == ["http://www.google.com/search?num=100&q=pie"]
  end
end

Basically I'm looking for any better ways to do this as well as whether my code meets hmmm standards... just some general critique. Thank you so much!


texts: Finding the market price for each order at the time it was placed

texts:
I have two datasets. The first dataset “insideMarke1” contains the Best Bid / Best Ask (=BBA) data for a given day, starting at 8.00 am. Every time the BBA is updated, there is a new row with a new timestamp.

The second dataset “orders1” contains order data. The order entry timestamps (‘Entry date and time’) in this dataset could be older than the oldest timestamp in the “insideMarke1” dataset. Each row contains one order. There are more orders in “orders1” than BBAs in “insideMarket1” (because not every order entry leads to a BBA update).

What I want to achieve is to create a new dataset “orders1Complete”, with is a combination of both datasets: For every order in “orders1”, I want the Best Bid / Best Ask Price at the moment when the order was entered. If the order entry timestamp is older than the oldest timestamp in the “insideMarke1” dataset, I just want the oldest BBA for these orders.

Therefore, I first added a new column to the “orders1” dataset, called ‘BBA_Timestamp’. And then I merged both datasets on this column. As a want the BBA timestamp at the moment before the order was entered, it is necessary to consider that the BBA timestamp has to be older than the order ‘Entry Date and Time’ timestamp.

Below stands my code:

import pandas as pd

insideMarke1 = pd.DataFrame({'Timestamp':['2019-12-01 08:00:00.123456', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:05.123456'],
                             'bestBidQnt':[100, 100, 50, 50, 100],
                             'bestBidPrice':[50.01, 50.01, 50.02, 50.02, 50.01],
                             'bestAskPrice':[51.00, 50.99, 50.99, 50.50, 50.50],
                             'bestAskQnt':[200, 100, 100, 200, 200]})

orders1 = pd.DataFrame({'Entry Date and Time':['2019-11-30 17:29:50.000000','2019-12-01 07:30:01.112233', '2019-12-01 08:00:00.123456', '2019-12-01 08:00:00.512341', '2019-12-01 08:00:01.123456', '2019-12-01 08:00:02.123456', '2019-12-01 08:00:02.987654', '2019-12-01 08:00:03.123456', '2019-12-01 08:00:04.000000', '2019-12-01 08:00:05.123456'],
                       'Bid':['True', 'True', 'False', 'False', 'False', 'True', 'True', 'False', 'True', 'True'],
                       'Price':[49.00, 49.50, 51.00, 51.50, 50.99, 50.02, 48.00, 50.50, 49.00, 50.01 ],
                       'Qnt':[50, 100, 200, 150, 100, 50, 10, 200, 80, 100 ]})

insideMarke1[['Timestamp']] = insideMarke1[['Timestamp']].apply(pd.to_datetime, unit='ns')
orders1[['Entry Date and Time']] = orders1[['Entry Date and Time']].apply(pd.to_datetime, unit='ns')

orders1['BBA_Timestamp'] = 0
i = 0
minInsideMarke1 = min(insideMarke1['Timestamp'])

for i in range(len(orders1['Entry Date and Time'])):
    if orders1['Entry Date and Time'][i] <= minInsideMarke1:
        orders1['BBA_Timestamp'][i] = minInsideMarke1
    else:
        insideMarke1_temp = insideMarke1.loc[(insideMarke1['Timestamp'] < orders1['Entry Date and Time'][i])]
        orders1['BBA_Timestamp'][i] = min(insideMarke1_temp['Timestamp'], key=lambda x: abs(orders1['Entry Date and Time'][i]-x))

orders1 = orders1.reset_index(drop=True)
insideMarke1 = insideMarke1.reset_index(drop=True)

insideMarke1 = insideMarke1.drop_duplicates('Timestamp', keep='last')
insideMarke1.rename(columns={'Timestamp': 'BBA_Timestamp'}, inplace=True)
insideMarke1[['BBA_Timestamp']] = insideMarke1[['BBA_Timestamp']].apply(pd.to_datetime, unit='ns')
insideMarke1 = insideMarke1.sort_values(by=['BBA_Timestamp']).reset_index(drop=True)
orders1[['BBA_Timestamp']] = orders1[['BBA_Timestamp']].apply(pd.to_datetime, unit='ns')
orders1 = orders1.sort_values(by=['BBA_Timestamp']).reset_index(drop=True)

orders1Complete = pd.merge_asof(orders1, insideMarke1, on='BBA_Timestamp')

The code works fine, but it is soooo sloooow. My data sets contain several thousand lines and I have to do this for several of those data sets...

I would be very very glad for any help, tips, advices,...


texts: jQuery range slider change text based on hidden field value

texts:
I am working on a jQuery ratings function that uses the Foundation range slider. My current implementation works correctly on 2 of 7 of my range sliders. However, I am quickly realising that my implementation will become bloated as I have to repeat myself for each of the 7 range sliders.

HTML:

      <%= f.hidden_field :quality %>

    Average

      <%= f.hidden_field :communication %>

    Average

jQuery:

$(document).on("page:load ready", function() {
  function ratings(selector, callback) {
    var input = $(selector);
    var oldvalue = input.val();
    setInterval(function(){
      if (input.val()!= oldvalue){
        oldvalue = input.val();
        callback();
      }
    }, 100);
  }
  ratings('input#agent_score_quality', function() {
    var inputValue = $('input#agent_score_quality').val();

    if(inputValue === '1') { // Terrible
      $("span#sliderOutput1").fadeOut(function() {
        $(this).text('Terrible').fadeIn();
      });
    }
    if(inputValue === '2') { // Poor
      $("span#sliderOutput1").fadeOut(function() {
        $(this).text('Poor').fadeIn();
      });
    }
    if(inputValue === '3') { // Average
      $("span#sliderOutput1").fadeOut(function() {
        $(this).text('Average').fadeIn();
      });
    }
    if(inputValue === '4') { // Good
      $("span#sliderOutput1").fadeOut(function() {
        $(this).text('Good').fadeIn();
      });
    }
    if(inputValue === '5') { // Excellent
      $("span#sliderOutput1").fadeOut(function() {
        $(this).text('Excellent').fadeIn();
      });
    }
  });
  ratings('input#agent_score_communication', function() {
    var inputValue = $('input#agent_score_communication').val();

    if(inputValue === '1') { // Terrible
      $("span#sliderOutput2").fadeOut(function() {
        $(this).text('Terrible').fadeIn();
      });
    }
    if(inputValue === '2') { // Poor
      $("span#sliderOutput2").fadeOut(function() {
        $(this).text('Poor').fadeIn();
      });
    }
    if(inputValue === '3') { // Average
      $("span#sliderOutput2").fadeOut(function() {
        $(this).text('Average').fadeIn();
      });
    }
    if(inputValue === '4') { // Good
      $("span#sliderOutput2").fadeOut(function() {
        $(this).text('Good').fadeIn();
      });
    }
    if(inputValue === '5') { // Excellent
      $("span#sliderOutput2").fadeOut(function() {
        $(this).text('Excellent').fadeIn();
      });
    }
  });
});

How can I improve this code so I don't have to repeat the same thing over and over just with different selectors? My idea is to use a single selector for the sliderOutput and use the .closest() method to target each and insert my text, but I'm new to jQuery, so could I be way off?


texts:
I have accomplished what I wanted to do but I think this can be done better. I want my code to look professional.
What my code does is ask for your name and gives output in below form.

Input: Jack
Output: j = joyful a = awesome c = curious k = kindhearted

Please show me how to code in a professional manner by reviewing the below code.
#!/usr/bin/env python
import sys
import string

names = {
'a': 'awesome',
'b': 'bold',
'c': 'curious',
'd':'delightful',
'e':'emotional',
'f':'fearless',
'g':'gifted',
'h':'helpful',
'i':'imaginary',
'j':'joyful',
'k':'kindhearted',
'l':'lovable',
'm':'memorable',
'n':'naughty',
'o':'open',
'p':'playful',
'q':'quarrelsome',
'r':'reliable',
's':'serious',
't':'thoughtful',
'u':'unique',
'v':'victorious',
'w':'wise',
'x':'xerox copy',
'y':'yummy',
'z':'zealous'
}

def main():
 i=j=0
 user = raw_input("What is your name?: ")
 print ""
 while i<len(user):
  while j<len(names):
   if user[i]==names.keys()[j]:
    print " " + user[i] + ' = ' + names.values()[j]
   j=j+1
  while j!=0:
   j=0
  i=i+1

if __name__ == '__main__':
  main()


texts: Detect if string contains more than 1 period

texts:
This function returns true if the string contains zero or one periods, and returns false if the string contains more than one period.

bool isStringValid(std::string str){
    std::size_t pos = str.find('.', 0);
    if(pos != std::string::npos){
        pos = str.find('.', pos + 1);
        if(pos != std::string::npos){
            std::cout << "\nError: Multiple decimal marks\n";
            return false;
        }
    }
    return true;
}

For example:

If str is 1.519, it returns true;
If str is 159, it returns true;
If str is 1.541.1, it returns false;
If str is 1.1.1.1, it returns false, and so on.

I am using the Boost C++ libraries elsewhere in the program, if that's useful in any way. This code isn't specific for finding the period . character, it should work with any character, but this is the use case for me.

Can this be done more efficiently?


texts: Counting the number of letters in a .txt file in Pascal

texts:
I wrote this program that counts the number of letters in random.txt file in the Pascal programming language.
It doesn't matter if the letters are capitalized. Other characters are ignored. When it finishes it writes every letter in a single line and then after it the number of appearences of that letter in the text file.

program letters;
var
random:text;
a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1:integer;

procedure counting(random:text; var a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1:integer);
var
c:char;
begin
a1:=0;
b1:=0;
c1:=0;
d1:=0;
e1:=0;
f1:=0;
g1:=0;
h1:=0;
i1:=0;
j1:=0;
k1:=0;
l1:=0;
m1:=0;
n1:=0;
o1:=0;
p1:=0;
q1:=0;
r1:=0;
s1:=0;
t1:=0;
u1:=0;
v1:=0;
w1:=0;
x1:=0;
y1:=0;
z1:=0;
while not eof(random) do
while not eoln do
begin
if (c='A') or (c='a') then a1:=a1+1;
if (c='B') or (c='b') then b1:=b1+1;
if (c='C') or (c='c') then c1:=c1+1;
if (c='D') or (c='d') then d1:=d1+1;
if (c='E') or (c='e') then e1:=e1+1;
if (c='F') or (c='f') then f1:=f1+1;
if (c='G') or (c='g') then g1:=g1+1;
if (c='H') or (c='h') then h1:=h1+1;
if (c='I') or (c='i') then i1:=i1+1;
if (c='J') or (c='j') then j1:=j1+1;
if (c='K') or (c='k') then k1:=k1+1;
if (c='L') or (c='l') then l1:=l1+1;
if (c='M') or (c='m') then m1:=m1+1;
if (c='N') or (c='n') then n1:=n1+1;
if (c='O') or (c='o') then o1:=o1+1;
if (c='P') or (c='p') then p1:=p1+1;
if (c='Q') or (c='q') then q1:=q1+1;
if (c='R') or (c='r') then r1:=r1+1;
if (c='S') or (c='s') then s1:=s1+1;
if (c='T') or (c='t') then t1:=t1+1;
if (c='U') or (c='u') then u1:=u1+1;
if (c='V') or (c='v') then v1:=v1+1;
if (c='W') or (c='w') then w1:=w1+1;
if (c='X') or (c='x') then x1:=x1+1;
if (c='Y') or (c='y') then y1:=y1+1;
if (c='Z') or (c='z') then z1:=z1+1;
end;
close(random);
end;

procedure result(a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1:integer);
begin
writeln('A','',a1);
writeln('B','',b1);
writeln('C','',c1);
writeln('D','',d1);
writeln('E','',e1);
writeln('F','',f1);
writeln('G','',g1);
writeln('H','',h1);
writeln('I','',i1);
writeln('J','',j1);
writeln('K','',k1);
writeln('L','',l1);
writeln('M','',m1);
writeln('N','',n1);
writeln('O','',o1);
writeln('P','',p1);
writeln('Q','',q1);
writeln('R','',r1);
writeln('S','',s1);
writeln('T','',t1);
writeln('U','',u1);
writeln('V','',v1);
writeln('W','',w1);
writeln('X','',x1);
writeln('Y','',y1);
writeln('Z','',z1);
end;

begin
    assign(random,'random.txt');
    reset(random);
    counting(random,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1);
    result(a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1);
    readln();
end.

I'm a beginner and I suppose this can be done a lot better and simpler without having to use 26 variables. How could I improve my code to make it work better? Could you give me some tips?


texts: Minimal substring with all characters contained in string

texts:
I was given following task in the interview:

  Given a string, find shortest substring in it that contains all of the different characters contained in the original string.

Here is my solution in emacs lisp:

(defun add-to-hash (c ht)
  "Add an instance of character C to hash table HT"
  (puthash c (1+ (gethash c ht 0)) ht))

(defun remove-from-hash (c ht &optional try)
  "Remove an instance of character C from hash table HT
Return nil if no instances of C remain in HT"
  (let ((old (gethash c ht 0)))
    (if (and try (< 2 old))
        nil
      (if (> 1 (puthash c (1- (gethash c ht 0)) ht))
          (remhash c ht)
        t))))

(defun find-min-substring (sstr)
  "Find minimal substring that contains all the characters in a given string"
  ;; get all characters
  (let* ((all-chars (make-hash-table))
         (slen (length sstr))
         (fcnt (progn
                 (mapc (lambda (c) (add-to-hash c all-chars)) sstr)
                 (hash-table-count all-chars)))
         (beg 0) (end fcnt)
         (res sstr))
    (if (= end slen)
        res
      (let* ((cand (substring sstr beg end))
             (cand-chars (make-hash-table))
             (ccnt (progn
                     (mapc (lambda (c) (add-to-hash c cand-chars)) cand)
                     (hash-table-count cand-chars))))
        ;; find first candidate, that is a substring with all the characters
        (while (< ccnt fcnt)
          (add-to-hash (aref sstr end) cand-chars)
          (setq end (1+ end))
          (setq ccnt (hash-table-count cand-chars)))
        (setq cand (substring sstr beg end))
        ;; shorten it as much as possible
        (while (remove-from-hash (aref sstr beg) cand-chars t)
          (setq beg (1+ beg)))
        (setq cand (substring sstr beg end))
        (setq res cand)
        ;; check other variants
        (while (< end slen)
          ;; advance both ends
          (add-to-hash (aref sstr end) cand-chars)
          (setq end (1+ end))
          (remove-from-hash (aref sstr beg) cand-chars)
          (setq beg (1+ beg))
          (setq ccnt (hash-table-count cand-chars))
          ;; another candidate is found
          (when (= ccnt fcnt)
            ;; only change candidate if it was shortened
            (while (remove-from-hash (aref sstr beg) cand-chars t)
              (setq beg (1+ beg))
              (setq cand (substring sstr beg end)))
            (setq res cand)))
        res))))


texts: Rust Iterator that correlates a slice with itself

texts:
In my effort to learn Rust I've tried implementing an Iterator that splits up a buffer in two halves, and correlates both halves by sliding them over each other with different positions (lags). You could use this e.g. to do autocorrelation, given a correlation function between two buffers (dot product for example).

I'm fairly new to Rust (coming from a C++ background), so any and all advice is welcome. Specifically to lifetimes, generics and idiomatic usage of Rust.

Also, should I turn this into an iterator adapter that takes an iterator and collects the data in an internal Vec? Would that cover a wider array of input?

pub struct Slide<'a, T, F> {
    items: &'a [T],
    func: F,
    lag: usize,
}

impl<'a, T, F> Slide<'a, T, F> {
    pub fn new<Out>(items: &'a [T], func: F) -> Slide<'a, T, F>
    where
        F: Fn(&'a [T], &'a [T]) -> Out,
    {
        Slide {
            items,
            func,
            lag: 0,
        }
    }
}

impl<'a, T, F, Out> Iterator for Slide<'a, T, F>
where
    F: Fn(&[T], &[T]) -> Out,
{
    type Item = Out;

    fn next(&mut self) -> Option<Out> {
        let half_length = self.items.len() / 2;

        if self.lag < half_length {
            let y = (self.func)(
                &self.items[0..half_length],
                &self.items[self.lag..self.lag + half_length],
            );

            self.lag += 1;
            Some(y)
        } else {
            None
        }
    }
}
```


texts:
List<int> types = new List<int>();
foreach (var d in myTableList)
{
    if (!types.Contains((int)d.item_type))
        types.Add((int)d.item_type);
}

I have a table in db called myTable. There is a column in it called item_type. It is integer.

I want to make a list which would have all item_type which are in myTableList, but there shouldn't be duplicates.

I tried:

types = myTableList.Distinct(x => x.item_type)

but I want types to be list of integers, not items of type myTable.


texts: Binary Search Tree to store objects by object ID

texts:
I'm trying to create a binary search tree that would be used to insert my Packet objects'. It holds information like partId, description, price, and partCount. It's a basic binary search tree. Could you take a look and tell me if there's nothing odd in the code? Because I'm trying to brush up on my BST. Please give me your comments and reviews.

I'm not doing anything complicated, just simple BST. I haven't done C++ in months, trying to review everything again.

This is my testing program:

#include <iostream>
#include "BST.h"
#include "Packet.h"

using namespace std;

int main() {
    BST test1;
    cout << "-------------------------------------------------------" << endl;
    cout << "Testing BST" << endl;
    cout << "-------------------------------------------------------" << endl;
    Packet packetTest(123, "This is a packet of cheese.", 12.95, 10);
    Packet packetTest1(321, "This is a packet of cheese.", 12.95, 10);
    Packet packetTest2(456, "This is a packet of cheese.", 12.95, 10);
    Packet packetTest3(7, "This is a packet of cheese.", 12.95, 10);
    Packet packetTest4(119, "This is a packet of cheese.", 12.95, 10);
    Packet packetTest5(456, "This is a packet of cheese.", 12.95, 10);
    test1.insert(packetTest);
    test1.insert(packetTest1);
    test1.insert(packetTest2);
    test1.insert(packetTest3);
    test1.insert(packetTest4);
    test1.insert(packetTest5);
    test1.preorderTraversal();
    system("pause");
}

Here's my BST.h:

#pragma once

#include <string>
#include <iostream>
#include <stack>
#include "Packet.h"
using namespace std;

class Node
{
    friend class BST;
public:
    Node() : packet(packet), rlink(nullptr), llink(nullptr) {}
    ~Node() {}

private:
    Packet *packet;
    Node *rlink, *llink;
};

class BST {
public:
    BST();
    void BST::insert(Packet& packet);
    void BST::insert(Node* &p, Node *newNode);
    void preorderTraversal() const;
private:
    Node *root;
    void preorderTraversal(const Node *p) const;
};

The BST.cpp Careful with this part, I might have done some things here, can you take an extra look here?:

#include "BST.h"

BST::BST() : root(nullptr) {}

void BST::insert(Packet& thisPacket) {
    Node *newNode = new Node;
    newNode->packet = &thisPacket;
    insert(root, newNode);
}

void BST::insert(Node *&p, Node *newNode)
{
    if (p == nullptr)
        p = newNode;
    else if (p->packet->getPartId() < newNode->packet->getPartId())
        insert(p->llink, newNode);
    else
        insert(p->rlink, newNode);
}

void BST::preorderTraversal() const {
    if (root == nullptr)
        cerr << "There is no tree.";
    else
    {
        preorderTraversal(root);
    }
}

void BST::preorderTraversal(const Node *p) const {
    if (p != nullptr) {
        cout << p->packet->getPartId() << " ";
        preorderTraversal(p->llink);
        preorderTraversal(p->rlink);
    }
}

And finally Packet.h:

#pragma once
#include <string>

using namespace std;

class Packet {
public:
    Packet(int partId, string description, double price, int partCount) :
        partId(partId), description(description), price(price), partCount(partCount) {}
    int getPartId() const {return partId;}

private:
    int partId;
    string description;
    double price;
    int partCount;
};


texts: Aggregate cost for a directed graph in Prolog

texts:
I've come up with a simple graph traversal algorithm to calculate the aggregated cost of a directed graph or its subgraphs. Given a directed graph, the code visits all reachable nodes and sums up the cost related to the node paying attention to already visited nodes. The return value is the total cost of (sub)graph.

For example, for the graph embedded in the code below all the following is true:

graphCost(a, 63).
graphCost(b, 26).
graphCost(c, 60).
graphCost(f, 32).

As you can see, I wasn't able to avoid duplicated paths without using global variables. I'm new to Prolog, so would like to have someone more experienced to look at it and check whether or not it's reasonable. Perhaps there's a ready to use function to do the same? Is there a more effective way to do it?

edge(a,b).
edge(a,c).
edge(b,d).
edge(c,d).
edge(d,e).
edge(b,b).
edge(c,f).

cost(a, 1).
cost(b, 2).
cost(c, 4).
cost(d, 8).
cost(e, 16).
cost(f, 32).

visitAndMove2(A) :-
  \+edge(A, _),
  nb_getval('Visited', Visited),
  ( \+member(A, Visited) ->
    nb_setval('Visited', [A | Visited]),
    cost(A, C),
    nb_getval('Cost', Cost),
    TC is Cost + C,
    nb_setval('Cost', TC),
    write(' --> '), write(A), write(': '), writeln([A | Visited])
  ;
    write(A), writeln(' --|')).

visitAndMove2(A) :-
  edge(A, Child),
  A \== Child,
  nb_getval('Visited', Visited),
  \+member(Child, Visited),
  nb_setval('Visited', [Child | Visited]),
  cost(Child, C),
  nb_getval('Cost', Cost),
  TC is Cost + C,
  nb_setval('Cost', TC),
  write(A), write(' --> '), write(Child), write(': '), writeln([Child | Visited]),
  visitAndMove2(Child).

graphCost(A, Cost) :-
  nb_setval('Visited', [A]),
  cost(A, C),
  nb_setval('Cost', C),
  visitAndMove2(A),
  nb_getval('Cost', Cost).


texts:
I'm pretty new to python, and coding in general.  For practice, I've written the following code, which uses Gaussian reduction to solve a system of linear equations.

import numpy as np

def gaussian_reduce(matrix, b):

    '''
    Solve a system of linear equations matrix*X = b using
    Gaussian elimination.
    ---
    Inputs:
    matrix -> an nxn numpy array of the linear equation coefficients
    b -> an nx1 numpy array of the linear equation constants
    ---
    Output:
    a numpy array giving the solution to the system of equations
    ---
    Example:
    http://web.mit.edu/10.001/Web/Course_Notes/GaussElimPivoting.html
     '''

    if(matrix.shape[0] != matrix.shape[1]):
        raise Exception("Matrix should be square")

    matrix = np.append(matrix, b, axis=1)
    matrix = to_row_echelon(matrix)
    if all(matrix[-1,:] == 0):
        raise Exception("System of equations is inconsistent")
    b = matrix[:,-1].copy()
    matrix = np.delete(matrix, -1, axis =1)
    b = backsolve(matrix, b)

    return np.array([b])

def to_row_echelon(matrix):
    '''
    Loops over the input matrix to reduce the matrix to row echelon
    form
    '''
    for i in range(matrix.shape[0] -1):
        matrix[i:, i:] = pivot(matrix[i:, i:])

    return matrix

def pivot(matrix):
    '''
    Finds the max element of the first column, switches this row to be
    the first row of the matrix, then adds linear multiples of this row
    to set all other elements of the first row to be zero.
    '''
    idx_of_max = np.argmax(list(map(abs, matrix.T[0])))
    if idx_of_max != 0:
        swap_rows(matrix, 0, idx_of_max)

    matrix[1:,] = np.apply_along_axis(subtract_rows, 1, matrix[1:], matrix[0])

    return matrix

def subtract_rows(row, top_row):
    '''
    Subtracts a linear multiple of top_row from row such as to
    set the first element of row to zeros
    '''

    return row - (row[0]/top_row[0])*top_row

def backsolve(matrix, b):
    '''
    Backsolves a set of linear equations matrix*X = b, where
    matrix is in row echelon form
    '''
    b[-1] = b[-1]/matrix[-1,-1]
    for i in range(len(matrix) - 2, -1, -1):
        b[i] = (b[i] - (b[i+1:]*matrix[i, i+1:]).sum())/matrix[i,i]

    return b

def swap_rows(matrix, a, b):
    '''
    Swaps row a and b in a numpy array
    '''
    t = matrix[a].copy()
    matrix[a] = matrix[b]
    matrix[b] = t

I suppose my observations would be:

a) I wrote this as a number of different functions, which I hoped would make the code more readable - however, I think this might in fact have made it less so?

b) Ideally, I would have done most of the operations without having to reassign the matrix a number of times - however, I couldn't find a way to easily do the subtract rows step in place.  Would this make it much less efficient?


texts: How can I Shorten and Simplify Ajax callback processes?

texts:
I've reusing this code for multiple areas and will like to make it more short and/or portable. What suggestions or changes could I make to simplify shorten it's callback processes?

        $("#add_question_member").submit(function(){
            $.ajax({
                    type:'post',
                    url: '/posts_in.php',
                    dataType: "json",
                    data: $(this).serialize(),
                    success: function(data){
                        var response = data[0];
                        $("#entry_area").fadeOut(function(){
                            if(response==1){
                                $("#msg0").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
                                    $("#entry_area").stop().fadeIn("slow");
                                });

                            }else{
                                $("#msg1").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
                                    $("#entry_area").stop().fadeIn("slow");
                                });
                            }
                        });

                    }
                });
            return false;
        });


texts: Function for getting strings consisting of random characters

texts:
I've made this function for to be used while testing.

// ----- THE ACTUAL FUNCTION -------------------------

// Returns a string consisting of random alphabetic
//  characters.

// @param { string } separator - Char which shall be
//  used to separate the single chars.
// @param { number } min - Minimal length of the string.
// @param { number } max - Maximal length of the string.
// @param { string } inCase - Case of characters to use.
//  - Use 'both' for getting a string consisting of
//   lower- and upper-case character.
//  - Use 'upper' for getting a string consisting of
//   only upper-case characters.
//  - Leave the parameter out, pass an empty string or
//   any other string for getting a string consisting
//   of only lower characters.
// @return { string }
// @throws { object } in case of error.

function getRandomString(separator, min, max, inCase) {
  var getPartRandomString = function() {
    return Math.random()
    .toString(36)
    .replace(/[^a-z]+/g, '');
  };

  var setReturnString = function() {
    ret += getPartRandomString();

    if (ret.length < min) {
      setReturnString();
    }
  }

  var ret = '';

  if (min >= max) {
    throw {
      message: 'Minimum can not be greater or equal Maximum.'
    }
  }

  min = min || 5;
  max = max || 8;

  separator = separator || '';

  setReturnString();

  ret = ret.split('');

  if (inCase === 'both') {
    ret = ret.map(function(currentChar) {
      if (Math.random() >= 0.5) {
        currentChar = currentChar.toUpperCase();
      }

      return currentChar;
    });
  }

  ret = ret.join(separator);

  if (inCase === 'upper') {
    ret = ret.toUpperCase();
  }

  ret = ret.slice(0, ret.length <= max ? ret.length : max);

  if (separator && ret.charAt(ret.length - 1) === separator) {
    ret = ret.slice(0, ret.length - 1);
  }

  return ret;
}
// ----- THE ACTUAL FUNCTION ---- End ----------------------

function testGetRandomString(min, max, caseToTest, limit, regExp) {
  var logMessage = function(message) {
    console.log('%s%s => %s',
                receivedResult,
                new Array(max - receivedResult.length + 1)
                .join(' '),
                message
               );
  }

  var receivedResult;

  min = min || 6;
  max = max || 12;
  limit = limit || 10;
  regExp = regExp || /[^a-z]/g;

  for (let i = 0; i < limit; i++) {
    receivedResult = getRandomString('', min, max, caseToTest);

    if (receivedResult.length < min) {
      logMessage('Less then min.');
    } else if (receivedResult.length > max) {
      logMessage('Larger or equal max.');
    } else if (receivedResult.search(regExp) !== -1) {
      logMessage('Unallowed chars.');
    } else {
      logMessage('Test passed.');
    }
  }
}

testGetRandomString(6, 12, '', 10);
console.log('\n');
testGetRandomString(6, 12, 'both', 10, /[^a-zA-Z]/g);
console.log('\n');
testGetRandomString(10, 18, 'upper', 10, /[^A-Z]/g);

console.log('\n');
console.log(getRandomString('-', 1, 2, 'both'));

console.log('\n');
console.log(getRandomString('-', 10, 20, 'both'));

It seem to work alright. But frankly: With all the parameter-checking and taking different possibilities into account it has become a lot of code.

If someone knows a possibility to write it more elegant then I would appreciate his or her answer. Any other hints welcomed too.

Should mention: I can't use ES 6-syntax because we got only Internet Explorer 11 here and there won't be change in any nearer future.


texts: Flexible Image Transport System (FITS) file parser

texts:
I have a simple class which currently has some code in the constructor, which makes it difficult to inject and also test.

public class FitsParser implements Parser {

private Header header;

/**
 * Constructor from a FITS File object and a HDU position.
 *
 * @param file The FITS file object from which the object is constructor.
 * @param hduNumber The HDU position where the keywords are located.
 * @throws Exception If any error is found.
 */
public FitsParser(final File file, final int hduNumber) throws Exception {
    try (Fits f = new Fits(file)) {
        this.header = f.getHDU(hduNumber).getHeader();
    }
}

/**
 * Constructor from a FITS Filename and a HDU position.
 *
 * @param filename The FITS filename from which the object is constructor.
 * @param hduNumber The HDU position where the keywords are located.
 * @throws Exception If any error is found.
 */
public FitsParser(final String filename, final int hduNumber) throws Exception {
    try (Fits f = new Fits(filename)) {
        this.header = f.getHDU(hduNumber).getHeader();
    }
}

@Override
public String getKey(String key) {
    return header.getStringValue(key);
}

@Override
public String getStringKey(String key) {
    return header.getStringValue(key);
}

@Override
public Integer getIntegerKey(String key) {
    return (header.containsKey(key)) ? header.getIntValue(key) : null;
}

@Override
public Float getFloatKey(String key) {
    return (header.containsKey(key)) ? header.getFloatValue(key) : null;
}

@Override
public Date getDateKey(String key) throws Exception {
    return DateParser.parseDate(this.getKey(key));
}

@Override
public Set<String> keys() {
    throw new UnsupportedOperationException("keys method is unsupported");
}

@Override
public String getFilename() {
    throw new UnsupportedOperationException("getFilename method is unsupported");
}

@Override
public Set<String> getComments() {
    throw new UnsupportedOperationException("getComments method is unsupported");
}

What would the best way to do this be? Would it be to simply create a parse method which does the parsing before calling the desired get method? The only thing about this is that the client would need to know to call parse first. Do you have any more ideas?


texts: Automatic condensing of whitespace in HTML

texts:
One of the things that has occurred to me more recently is that if you add up all of the bandwidth that is taken up by thousands of users downloading the newlines and tabs used to make HTML source code readable... that's a LOT of wasted bandwidth.

So I wanted to add some code that would condense whitespace on-the-fly before sending it to the browser.

I then very quickly realised that sometimes, whitespace is significant. For example, in <textarea>s or <pre> tags.

After double-checking, I've come to the firm conclusion that there is absolutely no use of white-space CSS values such as pre-wrap that would make whitespace significant, except in the case of a custom <rainbow> tag (which is parsed by JavaScript for colour codes and things - long story XD)

So with that in mind, I wanted to condense whitespace that is not contained in a <textarea>, <pre> or <rainbow>. I accomplished this with DOMDocument and a DOMXPath, in other words, "doing it right". But then I learned about regex verbs, and replaced my code with this:

// uber hax with regex
$str = trim(preg_replace("(<(textarea|rainbow|pre).*?</\\1>(*SKIP)(*F)|\s+)s"," ",$str));

It, um... well, it works, or at least it seems to from what I can tell. But I wanted to post here so I can ask, have I missed anything important? Or is it really this simple?


texts: Can anyone improve my multidimensional array more distinctive?

texts:
What I've been working on is some kind of function that can take basically any well constructed multi-dimensional array and remove any and all duplicates within matching key sets.

The particular function I've designed provides convenience and functionality but it is far from pretty and seemingly slow compared to a possibly more optimized function.

Sample Data

$echo['level-one'][] = '1';
$echo['level-one'][] = '1';
$echo['level-one'][] = '1';
$echo['level-one'][] = '1';
$echo['level-one']['level-two'][] = '1';
$echo['level-one']['level-two'][] = '1';
$echo['level-one']['level-two'][] = '1';
$echo['level-one']['level-two'][] = '1';
$echo['level-one']['level-two']['level-three'][] = '1';
$echo['level-one']['level-two']['level-three'][] = '2';
$echo['level-one']['level-two']['level-three'][] = '3';
$echo['level-one']['level-two']['level-three'][] = '4';

Function Declaration and Execution

function array_unique_multidimensional($name=null,$tv=null,$tk=null,$ta=null){

  if(!isset($ta)){$ta = ''.$name.'';}else{$ta .= '['.$tk.']';}

  if(!isset($tv)){$tv = '$v';}else{$tv .= 'v';}

  if(!isset($tk)){$tk = '$k';}else{$tk .= 'k';}

  return('
    foreach('.$ta.' as '.$tk.' => '.$tv.'){

      if(is_array('.$tv.')){
        eval(array_unique_multidimensional(\'\',\''.$tv.'\',\''.$tk.'\',\''.$ta.'\'));
      }else{
        '.$ta.' = array_unique('.$ta.');
      }

     }
  '); //end return

}

eval(array_unique_multidimensional('$echo'));
//Yes this function returns a foreach loop so it must be eval'd
//then it recursively calls itself until the entire array is traversed
//This will ensure every segment of the array is unique individually

Alright so I spaced it out a lot more then it probably needs to be and it is probably best viewed in some kind of program editor. Anyway after running the script as it is shown above you should get level's one and two reduced to a single entry and level three should have all four of it's entries (since their values are unique and one and two's are not).

I've seen a lot of answers using array_map to serialize and unique but I've found that they do not work for multidimensional arrays of varying calibers. Ultimately this function will accept any size and depth of array, compare every single key set to itself, remove any duplicates, and preserve every array name/key contained within.

Does anyone know of a better way to go about this? If not enjoy the working code above, if you do please share :)


texts:
Here is my code for removing duplicated values from an array. I think I tested it with the most possible cases. Any suggestions or bugs?

class duplicate {

    public static int[] removeDuplicates(int[] arr) {
        int end = arr.length;

        for (int i = 0; i < end; i++) {
            for (int j = i + 1; j < end; j++) {
                if (arr[i] == arr[j]) {
                    int shiftLeft = j;

                    for(int k = j + 1; k < end; k++, shiftLeft++) {
                        arr[shiftLeft] = arr[k];
                    }

                    end--;
                    j--;
                }
            }
        }

        int[] whitelist = new int[end];

        for (int i = 0; i < end; i++) {
            whitelist[i] = arr[i];
        }

        return whitelist;
    }
}

After some tests, it appears really inefficient because an array with 1,000,000 elements takes a very long time to end. Is there any better way to implement this on arrays?


texts: Generic Repository, UnitOfWork and IOC container

texts:
I am stuck to define a generic repository with AutoFac IOC container. I am keeping thing very simple and only showing relevant information.

BaseEntity

public abstract class BaseEntity
{
    public int Id { get; set; }
}

IRepository

public interface IRepository<TEntity> where TEntity : BaseEntity
{
    List<TEntity> GetAll();
    void Insert(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

IUnitOfWork

public interface IUnitOfWork : IDisposable
{
    int SaveChanges();
    void Dispose(bool disposing);
    IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity;
}

IService

public interface IService
{
    IUnitOfWork UnitOfWork { get; }
}

IService<TEntity>

public interface IService<TEntity> : IService where TEntity : BaseEntity
{
    List<TEntity> GetAll();
    TEntity GetById(int id);
    void Add(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

UnitOfWork

public class UnitOfWork : IUnitOfWork
{

    private readonly IEntitiesContext _context;
    private bool _disposed;
    private ObjectContext _objectContext;
    private Hashtable _repositories;
    private DbTransaction _transaction;

    public UnitOfWork(IEntitiesContext context)
    {
        _context = context;
    }

    public int SaveChanges()
    {
        return _context.SaveChanges();
    }

    public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
    {
        if (_repositories == null)
        {
            _repositories = new Hashtable();
        }
        var type = typeof(TEntity).Name;
        if (_repositories.ContainsKey(type))
        {
            return (IRepository<TEntity>)_repositories[type];
        }
        var repositoryType = typeof(EntityRepository<>);
        _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
        return (IRepository<TEntity>)_repositories[type];
    }
}

Service<TEntity>

public class Service<TEntity> : IService<TEntity> where TEntity : BaseEntity
{
    public IUnitOfWork UnitOfWork { get; private set; }

    public Service(IUnitOfWork unitOfWork)
    {
        UnitOfWork = unitOfWork;
    }

    public List<TEntity> GetAll()
    {
        return UnitOfWork.Repository<TEntity>().GetAll();
    }
}

EntityRepository<TEntity>

public class EntityRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
    private readonly IEntitiesContext _context;
    private readonly IDbSet<TEntity> _dbEntitySet;

    public EntityRepository(IEntitiesContext context)
    {
        _context = context;
        _dbEntitySet = _context.Set<TEntity>();
    }

    public List<TEntity> GetAll()
    {
        return _dbEntitySet.ToList();
    }
}

Now these are generic repository, services and unit-of-work. In my presentation I am using IService<T> which will be injected through AutoFac. Now I have 2 concerns:

I am directly using EntityRepository inside UnitOfWork var repositoryType = typeof(EntityRepository<>), which is a problem for me because I am injecting dependencies through IOC.
If I need to use a custom Repository (by inheriting EntityRepository) in future, how can I inject it in my UnitOfWork?


texts: Transfer the format of an old string to a new string

texts:
First, I've extended the String class to detect uppercase and lowercase characters:

class String

    def is_uppercase?
         self == self.upcase
    end

    def is_lowercase?
        self == self.downcase
    end

end

I then use these instance methods to fulfil my main goal of transferring the format of an old string to a new string:

def maintain_format(instring, outstring)
      instring_array = instring.split(//)
      outstring_array = outstring.split(//)

      both_arrays = instring_array.zip(outstring_array)

      both_arrays.each do |character|
        if character[0] == nil || character[0].is_lowercase?
          character[1].downcase! if character[1]
        elsif character[0].is_uppercase?
          character[1].upcase! if character[1]
        end
     end

     outstring_array.join("")
end

It works well and does exactly what I want:

2.0.0p247 :002 > maintain_format('jimmy','Jam')
 => "jam"
2.0.0p247 :003 > maintain_format('Jimmy','xam')
 => "Xam"
2.0.0p247 :004 > maintain_format('realLylongname','shorter')
 => "shorTer"
2.0.0p247 :005 > maintain_format('rSeHorteR','muchmuchmuchlongerfoos')
 => "mUcHmuchMuchlongerfoos"

However, what I love about ruby is how it is sort self-documenting if you use sensible variable and method names and hash keys. With this code it is a bit hard to follow regarding the 1character[0]character[1]` stuff. I attempting it with hashes but got in a bit of a mess. How would you tackle this problem?

Also interested in any ruby tricks to make this take up less lines.

Note this is part of a rails project, so all rails methods are available to me.


texts: Stanford developing calculator iOS app assignment

texts:
I'm currently learning Swift by following the Stanford developing iOS app 2015 lecture series. I have completed assignment 1 but am wondering if there is any improvement can be made to my code.

Also, I have not been able to complete extra credit no. 4, so I would appreciate if someone could offer me a hint.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    @IBOutlet weak var history: UILabel!

    var userIsInTheMiddleOfTyping = false

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!

        if digit == "." && display.text!.rangeOfString(".") != nil {
            return
        }

        if userIsInTheMiddleOfTyping {
            display.text = display.text! + digit
        } else {
            display.text = digit
            userIsInTheMiddleOfTyping = true
        }

    }

    @IBAction func operate(sender: UIButton) {
        if userIsInTheMiddleOfTyping {
            enter()
        }

        let symbol = sender.currentTitle!

        appendToEntryRecord(symbol)
        appendToEntryRecord("  =  ")

        switch symbol {
        case "×": performOperation {$0 * $1}
        case "÷": performOperation { $1 / $0}
        case "+": performOperation {$0 + $1}
        case "−": performOperation {$1 - $0}
        case "√": performOperation {sqrt($0)}
        case "sin": performOperation {sin($0)}
        case "cos": performOperation {cos($0)}
        case "tan": performOperation {tan($0)}
        case "π": performOperation {M_PI}

        default: break
        }

    }

    func performOperation(operation: (Double, Double) -> Double){
        if operandStack.count >= 2 {
            displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
            enter()
        }
    }

    @nonobjc
    func performOperation(operation: (Double) -> Double){
        if operandStack.count >= 1{
            displayValue = operation(operandStack.removeLast())
            enter()
        }
    }

    @nonobjc
    func performOperation(operation: () -> Double){
        displayValue = operation()
        enter()
    }

    var operandStack = [Double]()

    @IBAction func enter() {
        userIsInTheMiddleOfTyping = false
        appendToEntryRecord("\(displayValue)")

        operandStack.append(displayValue)

        print("operandStack = \(operandStack)")
    }

    var displayValue: Double {
        get {
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set {
            display.text = "\(newValue)"
            userIsInTheMiddleOfTyping = false

        }
    }

    func appendToEntryRecord(value: String){
        history.text = history.text! + "  " + value
    }

    @IBAction func clear() {
        display.text = "0"
        history.text = "0"
        operandStack = [Double]()
    }

    @IBAction func backspace() {
        if display.text!.characters.count > 0 {
            display.text = String(display.text!.characters.dropLast())
        }
    }

    @IBAction func changeSign() {
        if userIsInTheMiddleOfTyping {
            display.text = "-\(display.text!)"
        } else {
            performOperation {-$0}
        }

    }
}


texts:
The following code is part of my practice in implementing algorithms in Haskell. I'm aware that bubble sort is a bad choice for sorting sequences in real applications.

import Test.QuickCheck
import Data.List (sort)

-- Going from left to right, swaps two adjacent elements if they are not in order.
-- After the first go, the largest element in the list has bubbled up to the end
-- of the list. In the next go, we start swapping from the first element to the
-- penultimate element and so forth.
bubbleSort :: Ord a => [a] -> [a]
bubbleSort xs = go xs (length xs -1)
  where go xs limit | limit > 0 = let swapped = swapTill xs limit in
                                  go swapped (limit -1)
                    | otherwise = xs

-- Swaps adjacent elements in a list if they are not in order, until a limit.
-- After this, the largest elements, from limit to (length xs),
-- are sorted at the list's end.
swapTill :: (Ord a, Num p) => [a] -> p -> [a]
swapTill xs limit = go xs 0
  where go xs count | count < limit = swap xs
                    | otherwise = xs
                      where swap [x] = [x]
                            swap (x:y:xs) | x < y     = x : (go (y:xs) (count +1))
                                          | otherwise = y : (go (x:xs) (count +1))

-- Tests
bubbleSortWorks :: [Int] -> Bool
bubbleSortWorks xs = bubbleSort xs == sort xs

runQuickCheck = quickCheck bubbleSortWorks

I'd very much appreciate hints on how to make this implementation shorter (maybe using a fold) and/or more readable.


texts:
Can someone help in making this clock code more modular so I will be able to use it in other bigger projects for example: turn into a c function. Here is the code:

#include <stdio.h>
#include <time.h>
#include <windows.h>
COORD coord = {0, 0};
void gotoxy (int x, int y)
{
    coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}
void showClock(int x_1, int x_2, int x_3,int y){
    long i = 0;
    clock_t now = 0;                 int interval = 1;
    int elapsed = 0;
    int min=0,MIN=0,hrs=0,sec=0;
    int d=0,f=0;
    now = clock();
    for(i = 0L ;  ; i++){
        elapsed = (clock()-now)/CLOCKS_PER_SEC;
        if(elapsed>=interval){
            interval += 1;
            if(elapsed%60==0){
                min=elapsed/60;
                d=60*min;
                if(min%60==0){
                    hrs=min/60;
                    f=60*hrs;
                }
            }
            sec=elapsed-d;
            MIN=min-f;
            if(hrs<10){
                gotoxy(x_1,y);printf("0%d",hrs);
            }else{
                gotoxy(x_1,y);printf(":%d",hrs);
            }
            if(min<10){
                gotoxy(x_2,y);printf(":0%d",MIN);
            }else{
                gotoxy(x_2,y);printf(":%2d",MIN);
            }
            if(sec<10){
                gotoxy(x_3,y);printf(":0%d",sec);
            }else{
                gotoxy(x_3,y);printf(":%2d",sec);
            }
        }
    }
}
int main()
{
    showClock(2,4,7,4);
    return 0;
}


texts:
Lately, I've been working on the Euler projects. I just started coding in C++ and could really use some feedback. Basically, I wrote a program to calculate the factorial of any number between 1 and 100 (I have not tested it above 100).

I looked into the Boost library, but it seemed a little bit to easy, so I wrote some algorithms on my own.

Anyway, I would really like some comments about whether this is efficient or not, and if I can somehow optimize the algorithms? I hope this post is within the scope of the forum, since it is my first.

I first convert two integers to vectors, storing each digit separately:

// Converting number to vector
std::vector<int> LargeNumber(int number) {
    std::vector<int> numbers;
    while (number > 0) {
        numbers.push_back(number % 10);
        number /= 10;
    }
    return numbers;
}

Then I pass the vectors on to one of these two functions, depending on whether I want to add or multiply:

// Adds large numbers
std::vector<int> addition(std::vector<int> max, std::vector<int> min) {
    if (max.size() < min.size()) {
        max.swap(min);
    }
    std::vector<int> sum;
    int rest = 0;

    for (int i = 0; i < min.size(); i++) {
        int c = min[i] + max[i] + rest;
        sum.push_back(c % 10);
        rest = c / 10;
    }

    for (int i = min.size(); i < max.size(); i++) {
        int c = max[i] + rest;
        sum.push_back(c % 10);
        rest = c / 10;
    }
    while (rest > 0) {
        sum.push_back(rest % 10);
        rest /= 10;
    }

    return sum;
}

// Multiplying large numbers
std::vector<int> multiplication(std::vector<int> max, std::vector<int> min) {
    if (max.size() < min.size()) {
        max.swap(min);
    }

    std::vector<std::vector<int>> sums;
    std::vector<int> sum;
    for (int i = 0; i < min.size(); i++) {
        sum.resize(0);
        int n = i;
        while (n > 0) {
            sum.push_back(0);
            n--;
        }
        int rest = 0;
        for (int j = 0; j < max.size(); j++) {
            int c = max[j] * min[i] + rest;
            sum.push_back(c % 10);
            rest = c / 10;
        }
        while (rest > 0) {
            sum.push_back(rest % 10);
            rest /= 10;
        }
        sums.push_back(sum);
    }
    sum.resize(0);

    for (int i = 0; i < sums.size(); i++) {
        sum = addition(sum, sums[i]);
    }
    return sum;
}

I can then calculate the factorial as:

#include <vector>
int main () {
    // Calculating the factorial of the number N
    int N = 100;
    std::vector<int> fac;
    sum.push_back(1);
    for (int i = 2; i <= N; i++) {
        fac = multiplication(sum, LargeNumber(i));
    }
    // Printing the result
    std::cout << "The factorial of " << N << ": " <<  std::endl;
    for (int i = sum.size()-1; i >= 0; i--) {
        std::cout << fac[i];
    } std::cout << std::endl;
}

Since I am very new to C++, it is hard for me to know what exactly to ask for, so any comment is very welcome.


texts:
For my training, i've been given an assignment to build a simple, extendable 'grade' String calculator by a given grade.

For now, I had to work by this table:

When the grade was higher then 100, I had to return the String "You must have been cheating".

What I currently came up with is:

public String gradeBy(int grade) {
    TreeMap<Boolean, Grade> grades = new TreeMap<>();
    grades.put(grade <= 50, Grade.F);
    grades.put(grade >= 51 && grade <= 60, Grade.D);
    grades.put(grade >= 61 && grade <= 70, Grade.C);
    grades.put(grade >= 71 && grade <= 80, Grade.B);
    grades.put(grade > 80 && grade <= 100, Grade.A);

    for (Map.Entry<Boolean, Grade> currentGrade : grades.entrySet()) {
        if (currentGrade.getKey() != true) {
            continue;
        }
        return currentGrade.getValue().name();
    }
    return "You must have been cheating";
}

enum Grade {
    F,
    D,
    C,
    B,
    A
}

Where I test it as:

@Test
public void gradeBy() throws Exception {
    int[] grades = {45, 52, 66, 93, 102};
    for(int grade : grades) {
        String gradeString = this.grading.gradeBy(grade);
        System.out.println(grade + "gives :"+ gradeString);
    }
}

Can this be improved in a more OOP way? Can the grading list be apart from the grading system it self?


texts: Parsing and summarizing an aviation METAR (US) report

texts:
I have a list of objects, which contains field rawData (eg rawData="KLAX 141353Z 06003KT 6SM BR FEW002 FEW008 BKN280 12/12 A3007 RMK AO2 SLP182 T01170117 $"). In my case rawData is METAR report from which i want to extract the most severe weather condition (clouds, fog, rain, snow).
Currently I am applying parseWeather to each object of my list.

METAR string can contain multiple instance of same tag e.g. (BRN065 BRN033),  it even can contain all of them in same time . To my output - I want to display "simplified" worst weather condition, where the worst, for the current task, is considered as fog, then snow, then other weather conditions.

To answer why i return same type as argument - initial argument have some pre parsed detailed report from FlightAware service. However I have different requirenment for simplified report, than provided. Thus function parseWeather is a side effect function which fills extra fields.

  private PollFlightResponse.ResultEntity.MetarEntity parseWeather(
      PollFlightResponse.ResultEntity.MetarEntity d) {

    int severity = 0; //how bad is weather from 0 to 2
    String wCode = ""; // map key
    String weather = ""; // human readable weather
    if (d.getRawData().contains("FG")) {
      wCode = "FG";
    } else if (d.getRawData().contains("+SN")) {
      wCode = "+SN";
    } else if (d.getRawData().contains("SN")) {
      wCode = "SN";
    } else if (d.getRawData().contains("-SN")) {
      wCode = "-SN";
    } else if (d.getRawData().contains("+RA")) {
      wCode = "+RA";
    } else if (d.getRawData().contains("-RA")) {
      wCode = "-RA";
    } else if (d.getRawData().contains("RA")) {
      wCode = "RA";
    } else if (d.getRawData().contains("VV")) {
      wCode = "VV";
    } else if (d.getRawData().contains("OVC")) {
      wCode = "OVC";
    } else if (d.getRawData().contains("BKN")) {
      wCode = "BKN";
    } else if (d.getRawData().contains("SCT")) {
      wCode = "SCT";
    } else if (d.getRawData().contains("FEW")) {
      wCode = "FEW";
    } else if (d.getRawData().contains("NSC")) {
      wCode = "NSC";
    } else if (d.getRawData().contains("CLR")) {
      wCode = "CLR";
    }

    if (TextUtils.isEmpty(wCode)) {
      wCode = "CLR";
    }
    weather = SearchActivity.conditions.get(wCode);
    severity = SearchActivity.severity.get(wCode);
    if (d.getRawData().contains("MPS")) {
      int index = d.getRawData().indexOf("MPS");
      String wind = d.getRawData().substring(index - 2, index);
      int s = Integer.parseInt(wind);
      if (s == 0) {
        //no wind does not affect results
      } else if (s < 3) {
        weather += ", Light wind";
      } else if (s < 10) {
        weather += ", Windy";
        if (severity < 1) severity = 1;
      } else {
        weather += ", Strong wind";
        if (severity < 1) severity = 2;
      }
    }
    d.setGeneraWeather(weather);
    d.setWeatherSeverity(severity);
    return d;
  }

where conditions and severity is static public hashmaps

  private void generateWeatherMap() {
    conditions.clear();
    severity.clear();

    //Strings
    conditions.put("FG", "Fog");
    conditions.put("+SN", "Heavy snow");
    conditions.put("SN", "Snow");
    conditions.put("-SN", "Light snow");
    conditions.put("+RA", "Heavy rain");
    conditions.put("RA", "Rain");
    conditions.put("-RA", "Light rain");
    conditions.put("CLR", "Clear sky");
    conditions.put("NSC", "Little clouds");
    conditions.put("FEW", "Few clouds");
    conditions.put("SCT", "Scattered clouds");
    conditions.put("BKN", "Broken clouds");
    conditions.put("OVC", "Overcast");
    conditions.put("VV", "Heavy precipitation");
    //Values
    severity.put("FG", 2);
    severity.put("+SN", 2);
    severity.put("SN", 1);
    severity.put("-SN", 1);
    severity.put("+RA", 1);
    severity.put("RA", 1);
    severity.put("-RA", 1);
    severity.put("CLR", 0);
    severity.put("NSC", 0);
    severity.put("FEW", 0);
    severity.put("SCT", 1);
    severity.put("BKN", 1);
    severity.put("OVC", 2);
    severity.put("VV", 2);
  }


texts: Deleting everything between two quotes in a string

texts:
Is this the easiest way to delete everything between and including the two first quotes (if present) in an std::wstring?

unsigned int firstQuotePos = logFileName.find_first_of(L"\"");
unsigned int secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

if (firstQuotePos != std::wstring::npos && secondQuotePos != std::wstring::npos)
{
    logFileName = std::wstring(logFileName.begin(), logFileName.begin() + firstQuotePos)
        + std::wstring(logFileName.begin() + secondQuotePos + 1, logFileName.end());
}


texts: Improving a Medicare Beneficiary Identifier (MBI) generator

texts:
I am new to coding and looking for a few pointers on how I can improve my first project.
At work, I often need to create Medicare Beneficiary Identifiers (MBI) when creating test patients with Medicare coverage, and have to look up the format every time. I thought creating an MBI generator would be a great first project.
Doing a quick search, I found a similar project on this site (which is what lead me here), but the questioner wants to create 10,000 records, whereas I may only need one or two MBIs at a time (their question can be found here: Sequential MBI generator). Being new and not understanding all of the code, I was nervous to follow in their path and end up with a ton of records, so I actually followed an example of a random password generator and tweaked it to meet my needs. As the outcome is vastly different from the linked example and seems verbose, I wondered if anyone with more experience would be able to give me some pointers to get me off to improve my work.
#MBI is 11 characters in the following format
# 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11
# C - A - AN- N - A - AN- N - A - A - N  - N
# C = Numeric 1 - 9
# N = Numeric 0 - 9
# A = Alphabetic A...Z; Not S, L, O, I, B, Z
# AN = Either A or N

import random
letter = 'ACDEFGHJKMNPQRTUVWXY' # not = B, I, L, O, S, Z
digit = str('0123456789')
partdig = str('123456789')
dig_let = digit + letter

while 1:
     mbi_return = 1
     mbi_need = int(input("How many MBI numbers do you need to generate?: "))
      for x in range(0,mbi_need):
         mbi = ""
         for x in range(0, mbi_return):
            mbi_char0 = random.choice(partdig)
            mbi_char1 = random.choice(letter)
            mbi_char2 = random.choice(dig_let)
            mbi_char3 = random.choice(digit)
            mbi_char4 = random.choice(letter)
            mbi_char5 = random.choice(dig_let)
            mbi_char6 = random.choice(digit)
            mbi_char7 = random.choice(letter)
            mbi_char8 = random.choice(letter)
            mbi_char9 = random.choice(digit)
            mbi_char10 = random.choice(digit)
            mbi = (mbi_char0 + mbi_char1 + mbi_char2 + mbi_char3 + mbi_char4 + mbi_char5 +
            mbi_char6 + mbi_char7 + mbi_char8 + mbi_char9 + mbi_char10) # I imagine this could be much cleaner
            print(mbi)

Thanks in advance!


texts: Calculate temperature based on differing regression coefficients

texts:
The following function calculates temperature based off of a given suction pressure, where different regression coefficients are assigned depending on the value of the pressure.

The regression equation is fairly standard, of the form:

$$ax^2 + bx + c$$

where \$x\$ is the pressure, and \$a\$, \$b\$, and \$c\$ are the coefficients. There are three different set of coefficients that are outlined in the code. I apply the regression equation by mapping the current pressure to the coefficients with LINQ.

I would like to optimize this function, as it takes in as a parameter a very large array of pressures, and needs to perform this calculation on every element in the array, and return those numbers as either an array or a list.

public static List<double> GetSSTList(double[] suctionPressureList)
{
    var result = new List<double>();
    var coefficientList = new List<double[]>() {
        new double[] { -28.43, 1.96582, -0.1582 },
        new double[] { -27.955, 2.4866, -0.055 },
        new double[] { -17.178, 0.5952, -0.0048 }
    };

    foreach (var psig in suctionPressureList)
    {
        double[] coefficients;

        if (psig >= -9 && psig <= -4)
        {
            coefficients = coefficientList[0];
        }
        else if (psig > -4 && psig <= 9)
        {
            coefficients = coefficientList[1];
        }
        else if (psig > 9 && psig <= 85)
        {
            coefficients = coefficientList[2];
        }
        else
        {
            coefficients = null;
        }

        var sst = coefficients.Select(c => c * Math.Pow(psig, Array.IndexOf(coefficients, c))).Sum();
        result.Add(sst);
    }

    return result;
}


texts: This JavaScript implementation of range is fast. What are it's downsides?

texts:
This implementation of range() is very fast:

RANGE = []; for (var i=0; i<65536; ++i) RANGE.push(i-32768);
range = function(a,b){ return RANGE.slice(a+32768,b+32768); };

Are there downsides in using this approach?


texts:
I'm working on a Python function that takes a piece of text and indicates if words are modified by words like very or not.

I'm looking for instance to label very nice differently from not nice. This does what it's supposed to do but I feel it might be clunky or there might be a more very efficient approach I'm not aware of.

def polarizer(input_sentence, modifier_dict, window_length):
    """
    The polarizer attaches the label given in modifier_dict to all items in input_sentence occurring a window_length after the modifier.
    modifier_dict needs to be formatted like so: {'not':'-', 'yes':'+', ..}
    Returns list with labels added.
    """
    #find positions of modifiers
    indices= [(range(n+1, n+1+window_length), modifier_dict[i]) for n,i in enumerate(input_sentence) if i in modifier_dict.keys()]
    #iterate over modifiers
    for ind in indices:
        for n in ind[0]:
            #add label unless there is already a label attached
            if n < len(input_sentence) and not input_sentence[n].endswith(tuple(modifier_dict.values())):
                input_sentence[n]=input_sentence[n]+ind[1]
    outputsentence= input_sentence
    return outputsentence

#Test sentences
modifier_dict={'very':'+'}

test1="This is fine".split(" ")
test2="This is very fine".split(" ")

print polarizer(test1, modifier_dict, 2)
print polarizer(test2, modifier_dict, 2)


texts:
Can someone please find out why this store procedure is timing out?

ALTER PROCEDURE [dbo].[Insertorupdatedevicecatalog]
                (@OS                NVARCHAR(50)
                ,@UniqueID          VARCHAR(500)
                ,@Longitude         FLOAT
                ,@Latitude          FLOAT
                ,@Culture           VARCHAR(10)
                ,@Other             NVARCHAR(200)
                ,@IPAddress         VARCHAR(50)
                ,@NativeDeviceID    VARCHAR(50))
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @TranCount INT;
    SET @TranCount = @@TRANCOUNT;

    DECLARE @OldUniqueID VARCHAR(500) = ''-1'';
    SELECT @OldUniqueID = [UniqueID] FROM DeviceCatalog WHERE (@NativeDeviceID != '''' AND [NativeDeviceID] = @NativeDeviceID);

    BEGIN TRY
        IF @TranCount = 0
            BEGIN TRANSACTION
        ELSE
            SAVE TRANSACTION Insertorupdatedevicecatalog;

        DECLARE @Geo GEOGRAPHY = geography::STGeomFromText(''POINT('' + CONVERT(VARCHAR(100), @Longitude) + '' '' + CONVERT(VARCHAR(100), @Latitude) + '')'', 4326);

        IF EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @UniqueID)
        BEGIN
            DECLARE @OldGeo     GEOGRAPHY
                    ,@OldCity       NVARCHAR(100)
                    ,@OldCountry    NVARCHAR(100)
                    ,@OldAddress    NVARCHAR(100);

            SELECT  @OldGeo = [LastUpdatedLocationFromJob]
                    ,@OldCity = [City]
                    ,@OldCountry = [Country]
                    ,@OldAddress = [Address]
            FROM    DeviceCatalog
            WHERE   [UniqueID] = @UniqueID;

            UPDATE  DeviceCatalog
                SET [OS] = @OS
                    ,[Location] = @Geo
                    ,[Culture] = @Culture
                    ,[Other] = @Other
                    ,[IPAddress] = @IPAddress
            WHERE   [UniqueID] = @UniqueID;

                            IF (@OldGeo IS NULL OR @OldAddress IS NULL OR @OldCity IS NULL OR @OldCountry IS NULL OR ISNULL(@Geo.STDistance(@OldGeo) / 1000,0) > 50)
            BEGIN
                UPDATE  DeviceCatalog
                    SET [Lastmodifieddate] = Getdate()
                WHERE   [UniqueID] = @UniqueID;
            END

        END
        ELSE
        BEGIN
            INSERT INTO DeviceCatalog
                        ([OS]
                        ,[UniqueID]
                        ,[Location]
                        ,[Culture]
                        ,[Other]
                        ,[IPAddress]
                        ,[NativeDeviceID])
                VALUES  (@OS
                        ,@UniqueID
                        ,@Geo
                        ,@Culture
                        ,@Other
                        ,@IPAddress
                        ,@NativeDeviceID);
                IF(@OldUniqueID != ''-1'' AND @OldUniqueID != @UniqueID)
                BEGIN
                    EXEC DeleteOldAndroidDeviceID @OldUniqueID, @UniqueID;
                END
        END
LBEXIT:
        IF @TranCount = 0
            COMMIT;

    END TRY
    BEGIN CATCH
        DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
        SELECT  @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();

        IF @XState = -1
            ROLLBACK;
        IF @XState = 1 AND @TranCount = 0
            rollback
        IF @XState = 1 AND @TranCount > 0
            ROLLBACK TRANSACTION Insertorupdatedevicecatalog;

        RAISERROR (''Insertorupdatedevicecatalog: %d: %s'', 16, 1, @error, @message) ;
    END CATCH
END