texts:
I'm kind of new to Python. So, I wonder which method is better to use in a function to find an element in a list.

First:

def search_binary(xs,target):
    count = 0
    for i in xs:
        if i == target:
            return count
            count = count +1
        else:
            count = count +1
            continue
    return -1

Second:

def search_binary(xs, target):
    lb = 0
    ub = len(xs)
    while True:
        if lb == ub:
           return -1

        mid_index = (lb + ub) // 2

        item_at_mid = xs[mid_index]

        if item_at_mid == target:
            return mid_index
        if item_at_mid < target:
            lb = mid_index + 1
        else:
            ub = mid_index


texts:
I wrote this script for a link shortener just for fun.

Is it safe, or is it very easy to inject SQL have other security shortcomings? Also, do you have any tips against MySQL injection?

I don't know how to make it better. I don't know, but it tells me that this is mostly code, and I should add some details but I don't know what to write!

 <?
    $user     = check_user();
    $uid      = $user["id"];
    $uid2     = $_SESSION['userid'];
    $link1    = $_POST['link1'];
    $link2    = $_POST['link2'];
    $flink    = $_POST['url'];
    $action   = $_POST['action'];
    $action1  = $_POST['action1'];
    $action2  = $_POST['action2'];
    $faction  = $_POST['faction'];
    $adgrade  = $_POST['adgrade'];
    $monetize = $_POST['monetize'];
    // $re = '/^(?:https?\:\/\/)?[a-z0-9\-_]+\.[a-z0-9\-_\.\/%&=\?\+]+$/mi';
    $re2      = '/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i';
    if (isset($link1) && isset($link2) && isset($flink) && !empty($link1) && !empty($link2) && !empty($flink)) {
        if (!preg_match("~^(?:f|ht)tps?://~i", $link1)) {
            $link1 = "http://" . $link1;
        }
        if (!preg_match("~^(?:f|ht)tps?://~i", $link2)) {
            $link2 = "http://" . $link2;
        }
        if (!preg_match("~^(?:f|ht)tps?://~i", $flink)) {
            $flink = "http://" . $flink;
        }
    }
    if (isset($link1) && isset($link2) && isset($flink) && !empty($link1) && !empty($link2) && !empty($flink)) {
        if (preg_match($re2, $flink, $matches, PREG_OFFSET_CAPTURE, 0) && preg_match($re2, $link1, $matches, PREG_OFFSET_CAPTURE, 0) && preg_match($re2, $link2, $matches, PREG_OFFSET_CAPTURE, 0)) {
            if (isset($action) && isset($action1) && isset($action2) && isset($faction)) {
                //$id = substr(md5(time().$flink), 0, 5);
                $id = substr(str_shuffle(str_repeat("aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxYyYzZ", 5)), 0, 5);
                if ($conn->query("INSERT INTO `" . $database . "`.`link` (`id`, `link1`,`link2`,`action`,`action1`,`action2`,`faction`, `flink`,`adonly`,`userid`,`adgrade`,`monetize`) VALUES ('" . $id . "','" . $link1 . "','" . $link2 . "','" . $action . "','" . $action1 . "','" . $action2 . "','" . $faction . "', '" . $flink . "','false','" . $uid . "','" . $adgrade . "','" . $monetize . "');")) {
                    $html = 'Your STU-Link is https://example.com/' . $id . '';
                } else {
                    $error_sth_wrong = "Something went wrong!";
                }
            } else {
                $error_sl_actions = "Please select all actions!";
            }
            mysqli_close($db);
        } else {
            $error_iv_urls = "Invalid url(s)!";
        }
    } else {
        $error_iv_urls2 = "Invalid url(s)!";
    }
?>


texts: Downloading the oldest available version of some data files

texts:
I am using the cURL tool in MATLAB 2013b with Ubuntu to download a whole bunch of files. The files have one of three possible versions: 1.0.0, 2.0.0, or 2.1.0. Using the HTTP, I first check the headers with three queries to see which version exists. Then whichever exists I download it. If none exists (because of nonexistent dates) then I just move on.

Is there any other more efficient way of querying and then downloading the files? For example, check 1.0.0. If it exists, download it. If it doesn't exist then check 2.0.0 and so on. The only way I can think of doing that was some very ugly nested if-elseif statements. But this way, I query three times no matter what so a little wasteful I think.

Also any other comments on my coding style are welcome.

    clc
    close all
    clear all

    for y = 2012:2013
    for m = 1:12
    for d = 1:31

    % To limit the dates because of the available data
    if y==2012 && m < 9
        continue
    elseif y==2013 && m > 9
        break
    end

    % The date string is created with padded zeros
    if (m < 10) && (d < 10)
        thedate = [num2str(y) '0' num2str(m) '0' num2str(d)];
    elseif m < 10
        thedate = [num2str(y) '0' num2str(m) num2str(d)];
    elseif d < 10
        thedate = [num2str(y) num2str(m) '0' num2str(d)];
    else
        thedate = [num2str(y) num2str(m) num2str(d)];
    end

    newname = ['ephemA' thedate '.h5']

    % The entire file name is created
    thefile = ['http://www.rbsp-ect.lanl.gov/data_pub/rbspa/MagEphem/def/rbspa_def_MagEphem_TS04D_' thedate];

    % Use curl with --head flag to check the header to see which version exists
    [status, result1] = system(['curl --head ' thefile '_v1.0.0.h5']);
    [status, result2] = system(['curl --head ' thefile '_v2.0.0.h5']);
    [status, result3] = system(['curl --head ' thefile '_v2.1.0.h5']);

    % 200 means the file exists and is downloaded
    if ~isempty(strfind(result1,'HTTP/1.1 200'))
        [status, result] = system(['curl -o ' newname ' ' thefile '_v1.0.0.h5']);
    elseif ~isempty(strfind(result2,'HTTP/1.1 200'))
        [status, result] = system(['curl -o ' newname ' ' thefile '_v2.0.0.h5']);
    elseif ~isempty(strfind(result3,'HTTP/1.1 200'))
        [status, result] = system(['curl -o ' newname ' ' thefile '_v2.1.0.h5']);
    end

    end
    end
    end


texts:
I will like to improve my code in Java involving creating simulations and games. This is a problem-solving code so far in interest and percentage calculations.

import javax.swing.JOptionPane;
class interest {
    public static void main(String[] args){
        String name = JOptionPane.showInputDialog( "Item" );
        String message = String.format( "Word is, %s, is Items", name );

        JOptionPane.showMessageDialog( null, message );

        String firstNumber = JOptionPane.showInputDialog( "Enter QuantitySold Double " );
        String secondNumber = JOptionPane.showInputDialog( "Enter UnitCost Double " );
        String thirdNumber = JOptionPane.showInputDialog( "Enter OriginalPrice Double " );
        String fourthNumber = JOptionPane.showInputDialog( "Enter lowedPercentagePrice Double " );

        Double QuantitySold = Double.parseDouble( firstNumber );
        Double UnitCost = Double.parseDouble( secondNumber );
        Double OriginalPrice = Double.parseDouble( thirdNumber );
        Double LowedPercentagePrice = Double.parseDouble( fourthNumber );
        Double TotalCost = QuantitySold * UnitCost ;

        JOptionPane.showMessageDialog( null, " TotalCost is " + TotalCost, "TotalCost of Two Doubles",
        JOptionPane.PLAIN_MESSAGE );

        Double PercentagePrice = LowedPercentagePrice / 100;
        Double PricePercentage = OriginalPrice * PercentagePrice ;
        Double TotalPrice = OriginalPrice - PricePercentage;

        JOptionPane.showMessageDialog( null, " TotalPrice is " + TotalPrice, "TotalPrice of Two Doubles", JOptionPane.PLAIN_MESSAGE );
    }
}


texts: Determining if a target string is found in an array of strings

texts:
I wrote this simple function in CoffeeScript to see if elements are found in an array:

isFoundIn = (searchTerm, arrayToSearch) ->
  returnVal = false
  for a in arrayToSearch
    returnVal = true if searchTerm is a
  returnVal

Usage:

isFoundIn('james', ['robert', 'michael', 'james'])`

would return true.

I know in Ruby it is very concise and readable to do this:

myArr = ['robert', 'michael', 'james']
myArr.include? 'james'

Are there some strategies to refactor this to make it more readable or more like CoffeeScript?


texts: Am I approaching this ASP.Net MVC/Entity Framework pattern incorrectly?

texts:
I have experience is C#/ASP.NET, and I've done MVC in Ruby On Rails, so I figured making the jump to ASP.NET MVC would be a breeze.  Unfortunately, I'm second-guessing my every decision.  I'd like some more eyes on this to tell me if my way of doing things is insane.

My main question is around editing an entity.

My GET looks like this:

public ActionResult Edit(int id)
{
    var viewModel = from c in db.centres
                    // some joins are here
                    where c.id == id
                    select new CentreViewModel {
                      CentreId = c.id,
                      CentreName = c.Name,
                      etc...
                    };
    return View( viewModel );
}

And my POST is something like this:

public ActionResult Edit(CentreViewModel viewModel)
{
    // NOTE - Validation & Error handling exists, but has been omitted for berevity
    var centre = db.centres.First(c => c.id == viewModel.CentreId);
    centre = Mapper.Map<CentreViewModel, CentreEntity>(viewModel, centre);

    db.centres.ApplyCurrentValues( centre );
    db.SaveChanges();
}

Is this kinda-sorta right?  Are there any red flags here?  Is ApplyCurrentValues correct?  I see others using repository.Entry(), but I don't have a repository for my classes, near as I can tell...


texts: Summing the prices from Transaction files

texts:
I need to cut down the run time of this query. Currently it's taking 45 minutes. Is there something I can change in the table or the query to allow this to run faster?

SELECT SUM(B.PRICE),C.ST_FILE
FROM
    TAD1D.ST_EUCM AS B,
    TAD1D.ST_DSA_TRAN  AS C,
    TAD1A.TIBHLD T
WHERE C.ST_TRAN_FILE=B.ST_TRAN_FILE
    AND C.ST_IND='Y'
    AND C.ST_SRC_SYS_CD='HANN'
    AND C.ST_TBL_NAME='ST_EUCM'
    AND B.PARTNUMB=T.ACCT_NUM
    AND B.FVSRVCCODE=T.SRV_CD
GROUP BY C.ST_FILE
EXCEPT
SELECT sum(A.ACCUM_C),D.ST_FILE from
                    TAD1A.TIBHLD_DLY_VAL A,
                    TAD1D.ST_DSA_TRAN  AS D
            where A.SRC_SYS_CD = 'HANN'
                    AND D.ST_SRC_SYS_CD=A.SRC_SYS_CD
                    AND D.ST_TBL_NAME='ST_EUCM'
                    AND DATE(A.HLD_VAL_DT)=DATE(D.ST_FILE)
                    GROUP BY D.ST_FILE
                    WITH UR --

There are no indexes on either table. Please provide a tip/solution in the event i am able to change the table structure or add an index (I may not).


texts: Automatically update one-to-many bi-directional relationship

texts:
In an example game engine server, the game world could be represented by a World object. The game might have multiple game worlds and a player who is in a world only needs to receive position data of units in that world.

class World
{
    public List<Unit> Units { get; set; }
}

However a piece of code also needs to be able to look up what world a unit is in easily, so the unit object itself keeps track of a world reference.

class Unit
{
    public World World { get; set; }
}

This works for lookup, but quickly becomes problematic when changing data when the programmer isn't aware of the relationship between objects going on, so I changed Units in World to be readonly and have the following code in Unit.

public virtual World World
{
    get { return _world; }
    set
    {
        // If already this, don't do anything
        if (value == _world) return;

        var oldWorld = _world;
        _world = value;

        if(oldWorld != null) oldWorld.UpdateUnitEntry(this);
        _world.UpdateUnitEntry(this);
    }
}

This works, but it feels like there's a better way to do this. Especially as I add more stuff that needs to be linked the same way (a World also has Structures and Players, and Structures maintain a list of Units as well), a lot of repeated functionality comes in. As well when I remove a unit from the game, it continues to be kept alive by this, so I have to remember to set the unit's structure to null every time (which I already forgot multiple times, resulting in weird bugs). Is there a better way to achieve this one-to-many relationship without manually updating both sides?


texts:
While rewriting Array so I can practice my javascript, I looked at my implementation of .join(). It seems a little clunky to me.

I've tried to cover all the edges, like making sure separator isn't null before joining, not adding the separator at the end of the string, and writing some documentation.

What I'm looking for is a smoother way to write this function. Any recommendations about this function are appreciated and considered.

/**
 * Converts each element of the array to string then concats them.
 *
 * @param separator Value to separate the elements by.
 *
 * @return String of joined elements.
 */
ArrayRewrite.prototype.join = function(separator) {
    separator = separator || "";
    let string = "";
    for (let i = 0; i < this.content.length; i++) {
        string += (i !== this.content.length - 1)
            ? this.content[i] + separator
            : this.content[i]
        ;
    }
    return string;
}

A test case is below

// This is the main function that other functions are built onto //
function ArrayRewrite(...elements) {
    this.content = elements || [];
}

myArray = new ArrayRewrite("Hello", "Testing", "Testing Again");
console.log(myArray.join(", "))

// Output:
// Hello, Testing, Testing Again


texts: Backing up a file to prevent its corruption during processing

texts:
My program is iterating over list of files and processing each of them using some library. It's possible that file might be corrupted in the process so I want to backup it to prevent potential corruption.

I implemented it this way:

private static void ComprocessFiles(List<string> files)
{
    FileInfo file = null;
    foreach (string filepath in files)
    {
        bool backedUp = false;
        bool keepBackup = false;
        try
        {
            file = new FileInfo(filepath);
            if (!file.Exists) continue;
            if (file.IsReadOnly) continue;

            BackupHelper.Backup(file);
            backedUp = true;
            ProcessFile(file);

            BackupHelper.RestoreTimestamps(file);
            file.Refresh();
        }
        catch (Exception ex)
        {
            try
            {
                Logger.LogSkippedFile(ex.GetType().Name, ex.Message, filepath);
                if (backedUp) BackupHelper.RestoreFile(file);
            }
            catch (Exception ex)
            {
                keepBackup = true;
            }
            // Listed exceptions are not critical.
            if (!(ex is IOException || ex is UnauthorizedAccessException || ex is System.Security.SecurityException))
            {
                throw;
            }
        }
        finally
        {
            if (!IsCorrupted(file)) keepBackup = true;
            if (!keepBackup) BackupHelper.DeleteBackup(file);
        }
    }
}

BackupHelper class:

static class BackupHelper
{
    static private DateTime[] timestamps = new DateTime[3];

    static internal void Backup(FileInfo originalFile)
    {
        timestamps[0] = originalFile.CreationTime;
        timestamps[1] = originalFile.LastWriteTime;
        timestamps[2] = originalFile.LastAccessTime;

        File.Copy(originalFile.FullName, originalFile.FullName + "_backup", true);
    }

    static internal void Backup(string originalFile)
    {
        Backup(new FileInfo(originalFile));
    }

    static internal void RestoreFile(FileInfo originalFile)
    {
        File.Copy(originalFile.FullName + "_backup", originalFile.FullName, true);
    }

    static internal void RestoreFile(string originalFile)
    {
        RestoreFile(new FileInfo(originalFile));
    }

    static internal void RestoreTimestamps(FileInfo originalFile)
    {
        originalFile.CreationTime   = timestamps[0];
        originalFile.LastWriteTime  = timestamps[1];
        originalFile.LastAccessTime = timestamps[2];
    }

    static internal void RestoreTimestamps(string originalFile)
    {
        RestoreTimestamps(new FileInfo(originalFile));
    }

    static internal void DeleteBackup(FileInfo originalFile)
    {
        timestamps = new DateTime[3];
        File.Delete(originalFile + "_backup");
    }

    static internal void DeleteBackup(string originalFile)
    {
        DeleteBackup(new FileInfo(originalFile));
    }
}

I tried my best as I plan to publish source code online but still feel that there is room for improvement.

I guess methods ProcessFile() and IsCorrupted() are not important for that question as well as Logger class.

Important note - StackOverflowException and OutOfMemoryException can't be thrown by this code as it don't do many method calls and don't use much memory.


texts:
I'd like a little help here calculating the view matrix for OpenGL based on the lookat type function:

vec3f eye    = {0, 0, 0};
vec3f center = {10, 2, 21};
vec3f up     = {0, 1, 0};
mat4* vm;
mat4LookAt(vm, &eye, &center, &up);

mat4print("lookat",vm);

Matrix output:

  lookat
[ -0.902861   -0.036833   -0.428353   0.000000    ]
[ 0.000000    0.996324    -0.085671   0.000000    ]
[ 0.429934    -0.077349   -0.899541   0.000000    ]
[ 0.000000    0.000000    -0.000000   1.000000    ]

The code that I used to create this matrix:

vec3f x = {1, 0, 0};
vec3f y = {0, 1, 0};
vec3f z = {0, 0, 1};

vec3fsub(&z, eye, center);
vec3fprint("z unnorm    ",&z);
vec3fnorm(&z, &z);
vec3fprint("z norm      ",&z);

vec3fcross(&x, &y, &z);

vec3fprint("x = y cros z",&x);
vec3fcross(&y, &z, &x);

vec3fprint("y = z cros x",&y);
vec3fprint("x unnorm    ",&x);
vec3fnorm(&x, &x);
vec3fprint("x norm      ",&x);
vec3fprint("y unnorm    ",&y);
vec3fnorm(&y, &y);
vec3fprint("y norm      ",&y);

double xx, yy, zz, x1, y1, z1;
xx = vec3fdotr(&x, eye);
yy = vec3fdotr(&y, eye);
zz = vec3fdotr(&z, eye);

x1 = vec3fdotr(eye, &x);
y1 = vec3fdotr(eye, &y);
z1 = vec3fdotr(eye, &z);

printf("x:%f\ty:%f\tz:%f\t\n",xx, yy, zz);
printf("x:%f\ty:%f\tz:%f\t\n",x1, y1, z1);

double data[] = { (&x)->p[0], (&y)->p[0], (&z)->p[0], 0,
                  (&x)->p[1], (&y)->p[1], (&z)->p[1], 0,
                  (&x)->p[2], (&y)->p[2], (&z)->p[2], 0,
                  xx,        yy,       zz,        1      };

copyMatrix(out, data);

Is this the proper way to calculate the lookat matrix that will take my models from object to view space?


texts: Yield statement in a using block from a clarity point of view

texts:
I want an opinion of the community about readability and maintainability of the following code.
This is quite a rare case when yield statement included in a using construction.

I know that this code will work as intended and dispose will be called eventually.
But I'm worried it might be difficult for other developers to understand and reuse it.

    public IEnumerable<string> GetUsers()
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter())
        {
            DataSet ds = new DataSet();
            string sql = @"SELECT lead  FROM teams";

            using (var sqlCnn = new SqlConnection(connetionString))
            {
                sqlCnn.Open();

                using (var sqlCmd = new SqlCommand(sql, sqlCnn))
                {
                    adapter.SelectCommand = sqlCmd;
                    adapter.Fill(ds);

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        var login = row[0].ToString();
                        yield return login;
                    }
                }
            }
        }
    }


texts: Shift and merge numbers as in 2048 game code

texts:
I started to learn Rust last night. Given its parallelization capabilities, I thought a good starting point would be porting my C++ AI for 2048 to Rust.

This is the function implementing the shift of one line (from high to low indices) of the 2048 board, ported verbatim from C++. It is supposed to shift the numbers in the line and return the score made by that move.

static SCORE_MERGE_FACTOR: f32 = 1.2f32;

fn shift_line(line: [&mut u8, ..4]) -> u64 {
    let mut result: u64 = 0;
    let mut i = 0;
    while i < line.len() {
        let mut merged = false;
        if *line[i] != 0 &&
           i > 0 &&
           *line[i-1] == *line[i]
        {
            *line[i-1] += 1;
            *line[i] = 0;
            merged = true;
            result += *line[i-1] as u64;
        }
        if *line[i] == 0 {
            let mut shifted = false;
            let mut j = i+1;
            while j < line.len() {
                if *line[j] != 0 {
                    *line[i] = *line[j];
                    *line[j] = 0;
                    shifted = true;
                    break;
                }
                j += 1;
            }
            if !shifted || merged {
                i += 1;
            }
        } else {
            i += 1;
        }
    }

    (result as f32 * SCORE_MERGE_FACTOR).round() as u64
}

I would love a general review with respect to Rust's paradigms, but I feel especially uncomfortable for not using iterators and having to use mutable variables all over the place.

I also find these explicit casts quite cumbersome, are they really necessary?


texts:
I'm trying to learn some multithreading and this seems like a good example, want to apply this to frustum culling later.
The goal is to find prime numbers in randomly generated vector of numbers.
Single threaded solution is simple, multithreaded way is to divide vector of random numbers in two parts, solve each one in the same time and merge results.

Here is the time it took to solve:

mt:

solved in: 17185.4 ms

solved in: 15832.2 ms

solved in: 16012.5 ms

solved in: 16354.9 ms

st:

solved in: 26942 ms

solved in: 30577.9 ms

solved in: 26403.4 ms

solved in: 29625.7 ms

It obviously works, but is the code correct?

This is from main.cpp:

 #include "primeNumbers.h"
 int main(){
    PrimeNumbers numbers(100000, 0, 5000000);
    PrimeNumberSolver* solver = new PrimeNumberSingleThread;
    //PrimeNumberSolver* solver = new PrimeNumberMultiThread;
    numbers.Solve(solver);
    delete solver;
 }

This is the rest of the code:

//primeNumbers.h
#include <mutex>
#include <thread>
#include <vector>
#include <iostream>
class PrimeNumberSolver abstract {
public:
    bool isPrime(int n) {
        for (int i = 2; i < n/2; ++i) {
            if (n % i == 0)
                return false;
        }

        return true;
    }

    virtual void solve(const std::vector<int>& source, std::vector<int>& result) = 0;

};

class PrimeNumberSingleThread final : public PrimeNumberSolver {
    friend class PrimeNumbers;
private:
    virtual void solve(const std::vector<int>& source, std::vector<int>& result) override{
        for (unsigned i = 0; i < source.size(); ++i) {
            if (isPrime(source[i]))
                result.push_back(source[i]);
        }
    }
};

class PrimeNumberMultiThread final : public PrimeNumberSolver {
    friend class PrimeNumbers;

private:
    virtual void solve(const std::vector<int>& source, std::vector<int>& result) override {
        std::vector<int> r1;
        std::vector<int> r2;

        //split source
        int half = source.size() / 2;
        int end = source.size();

        std::mutex m;

        //run two threads
        std::thread t1([&]() {
            for (int i = 0; i < half; ++i) {
                //std::lock_guard<std::mutex> lock(m);  //do i need to lock mutex before accessing source
                if (isPrime(source[i]))
                    r1.push_back(source[i]);
            }
        });
        std::thread t2([&]() {
            for (int i = half; i < end; ++i) {
                //std::lock_guard<std::mutex> lock(m);  //do i need to lock mutex before accessing source
                if (isPrime(source[i]))
                    r2.push_back(source[i]);
            }
        });

        //join threads
        if(t1.joinable()) t1.join();
        if(t2.joinable()) t2.join();

        //merge results
        result.insert(result.end(), r1.begin(), r1.end());
        result.insert(result.end(), r2.begin(), r2.end());
    }
};

class PrimeNumbers {
public:
    PrimeNumbers(int size, unsigned min, unsigned max) {
        std::mt19937 rng;
        for (int i = 0; i < size; ++i) {
            rng.seed(std::random_device()());
            std::uniform_int_distribution<std::mt19937::result_type> dist6(min, max);
            randoms.push_back(dist6(rng));
        }
        std::cout << "Numbers are generated" << std::endl;
    }

    void Solve(PrimeNumberSolver* solver) {
        double time = glfwGetTime();
        solver->solve(randoms, primes);
        std::cout << "solved in: " << (glfwGetTime() - time) * 1000.0 << " ms" << std::endl;
    }

    void printPrimes() {
        for (unsigned i = 0; i < primes.size(); ++i)
            std::cout << primes[i] << std::endl;
    }

    std::vector<int> randoms;
    std::vector<int> primes;
};


texts: Efficent way of synchronizing between data

texts:
I'm currently working on a project where I have a punch of raw data and multiple components that use that data for various tasks. I would like to separate the raw data from the components as much as possible and keep the raw data as only data (So no logic or functionality) but the components should be able to read and write to the raw data at any time.

The program will run each component and once all components have been run than the process repeats until the program shuts down. A component can be threaded, but it must join before the process repeats.

Each component will create objects based on the data that will do various things. To avoid having to create and delete those objects at each run for performance the objects must persist and synchronize it's data with the raw data at the beginning of the run.

So to summarize, the design should look something like this

This brings up the issue of synchronization as I need the component to synchronize its data with the raw data at beginning of each run.

Speed is some what important and so I can't go through each object and check if it it's members are equal to that of the component as that is process consuming especially considering the data will not change for the majority of the time.

What I thought about doing is give each object a GUID and every time one of it's values changes than I generate a new GUID. Therefore, if the GUID in the component is different than what it is in the raw data than the value must have changed.

This is simple to implement with getter and setter for each member and in the setter I just generate a new GUID.

Now, I wanted to avoid using getter and setter for two reasons. First, that increases the amount of typing I have to do and that will only increase my chance of getting arthritis sooner. Second, I'm scared my colleagues will take the lazy way and not add getter and setter for when they add members or passing the setter all together and setting the value directly causing a huge headache and waste of debugging time.

Therefore, I decided to create a template class that handles this for me.

This is what I came up with

#include<iostream>
#include "uuid.hpp"
#include "uuid_generators.hpp"
#include "uuid_io.hpp"

template<typename T>
class MemberTracker
{
private:
    T m_value;
    boost::uuids::uuid& m_KeepingTrackOf;
public:
    MemberTracker(boost::uuids::uuid& KeepTrackof)
        : m_KeepingTrackOf(KeepTrackof)
    {
    }
    operator T()
    {
        return m_value;
    }
    MemberTracker& operator=(T input)
    {
        this->m_KeepingTrackOf = boost::uuids::random_generator()();
        this->m_value = input;
        return *this;
    }
};

class ObjectRawData
{
public:
    boost::uuids::uuid guid;
    MemberTracker<int> value;
    ObjectRawData()
        : value(guid)
    {
        guid = boost::uuids::random_generator()();
    }
    ObjectRawData(const ObjectRawData &obj)
        : value(guid)
    {
    }
};

int main()
{
    ObjectRawData h;
    std::cout << h.guid << std::endl;
    h.value = 4;
    std::cout << h.guid << std::endl;
}

The only thing I don't like about this design is that I have to pass in the GUID as a parameter in the constructor.

So, my question is did I go in the right direction and what are the flaws of this design??


texts:
Does anyone have any ideas on how I can refactor these methods to get rid of the duplication? The first, third and fourth lines of both methods do the same thing. I'm having trouble for some reason because the second argument of both methods are of different types (or rather they represent different types of values).

I was think of using procs and having the different code be a block, but I couldn't find a solution.

def buy_in_cash(symbol, cash_amt) # second argument is cash
  market_price = @exchange.price_by_symbol(symbol)
  coin_amt = cash_to_coin(cash_amt, market_price) # different
  withdraw_cash(cash_amt)
  @transactions << Transaction.new(symbol, coin_amt, market_price)
end

def buy_in_coin(symbol, coin_amt) # here second argument is coin
  market_price = @exchange.price_by_symbol(symbol)
  cash_amt = coin_to_cash(coin_amt, market_price) # different
  withdraw_cash(cash_amt)
  @transactions << Transaction.new(symbol, coin_amt, market_price)
end


texts: Code runs Speed Test CLI using the python wrapper and then stores values within CSV

texts:
I wanted to make use of the speedtest-cli while also incorporating pandas into the project. My initial goal, which I am posting here, was to take the values of the speed test and incorporate them into a CSV. I've been learning about Pandas and figured it would be a good way to accomplish the project.

import speedtest
import pandas as pd
import os

# Initial Speedtest variables
s = speedtest.Speedtest()
servers = []

# File path variables
localpath = ''
filepath = ''
filename = ''

# Functions #

def speedtest():
    """Makes use of the speed-test-cli python wrapper
    to get speed test data and returns in a dictionary"""
    s.get_servers(servers)
    s.get_best_server()
    s.download()
    s.upload()
    s.results.share()
    results_dict = s.results.dict()
    return results_dict

def convert_mbps(arg):
    arg = arg / 1000000
    return arg

def csv_upload(localpath, filepath, filename):
    """Attempts to append a csv file and, if none
    exists, creates one in a specified path"""
    try:
        df2 = pd.read_csv(localpath)
        df2 = df2.append(df)
        df2.to_csv(os.path.join(filepath, filename), index=False)
    except OSError:
        df.to_csv(os.path.join(filepath, filename), index=False)

# Speedtest and convert to Data Frame
result = speedtest()
df = pd.io.json.json_normalize(result)
df2 = None

# Uploads CSV
csv_upload(localpath, filepath, filename)

I've tried as best as I could to document throughout my code, as well as to not statically specify parameters within functions; something which I've been bad for in the past. I've also tried to incorporate in some exception handling, though this is something that I believe needs more work in my code.

I've tested the code within a cron, it does exactly what it seems to be functioning as I would like it to. Future developments will surround analyzing data collected from the CSV; trying to determine trends in bandwidth or latency as a function of time of day. Any feedback would be most appreciated.


texts: Business with dbcontext and static class

texts:
Many speak of using dependency injection. I do not use repository. The entity framework is uow/repository. What is wrong with using static class like the one below? My context is a new instance per request.

public class TenantManager
  {
    public static IEnumerable<Tenant> GetAll(AppDbContext context)
    {
      return context.Tenants;
    }
    public static Tenant GetById(int id, AppDbContext context)
    {
      return context.Tenants.Find(id);
    }
    public static Tenant Create(Tenant entity, AppDbContext context)
    {
      var tenant = context.Tenants.Add(entity);

      context.SaveChanges();
      return tenant;
    }
    public static void Update(Tenant entity, AppDbContext context)
    {
      context.Entry(entity).State = EntityState.Modified;
      context.SaveChanges();
    }
    public static void Delete(int id, AppDbContext context)
    {
      var tenant = context.Tenants.Find(id);
      context.Tenants.Remove(tenant);
      context.SaveChanges();
    }
  }


texts:
This is one of codeeval challenges

  Challenge Description:

  Credits: Programming Challenges by Steven S. Skiena and Miguel A.
  Revilla

  The problem is as follows: choose a number, reverse its digits and add
  it to the original. If the sum is not a palindrome (which means, it is
  not the same number from left to right and right to left), repeat this
  procedure. E.g.

  195 (initial number) + 591 (reverse of initial number) = 786

  786 + 687 = 1473

  1473 + 3741 = 5214

  5214 + 4125 = 9339 (palindrome) In this particular case the palindrome
  9339 appeared after the 4th addition. This method leads to palindromes
  in a few step for almost all of the integers. But there are
  interesting exceptions. 196 is the first number for which no
  palindrome has been found. It is not proven though, that there is no
  such a palindrome.

Here is my solution for it:

#!/usr/bin/env python
import sys

"""
I've done some tests with timeit and it seems that both numeric and string version
have the same performance (at least for numbers < 10000)

# def reverse_num(num):
#   rev = 0
#   while(num > 0):
#     rev = (10*rev)+num%10
#     num //= 10
#   return rev
"""

def reverse(num):
    """Reverses the number

       >>> reverse(1456)
       6541
       >>> reverse(111)
       111
    """
    return int(str(num)[::-1])

def palindrome(num):
    """Return the number of iterations required to compute a palindrome

       >>> palindrome(195)
       (4, 9339)
    """
    # compute in 100 iterations or less
    for i in range(100):
        rnum = reverse(num)
        if rnum == num:
            break
        num = num + rnum
    return (i, num)

if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        for line in f:
            print "%s %s" % palindrome(int(line))

Any remarks on the code style, on the algorithm itself?


texts:
I wrote a function that will pixelate an image using the average color of each 4x4 cell.

The function will "split" the image into 4x4 cells, and find the average color of each pixel in the 4x4 cell, and set the 4x4 cell to the average color.

I'd like some help optimizing my function so it can pixelate an image as fast as possible. In its current state the pixelation process is quite slow.

private static Image PixelateImage(Image image)
{
    var bitmap = new Bitmap(image.Width, image.Height);
    using (var graphics = Graphics.FromImage(bitmap))
    {
        graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
    }

    // Loop through the image in 4x4 cells.
    for (var yy = 0; yy < image.Height && yy < image.Height; yy += 4)
    {
        for (var xx = 0; xx < image.Width && xx < image.Width; xx += 4)
        {
            var cellColors = new List<Color>();

            // Store each color from the 4x4 cell into cellColors.
            for (var y = yy; y < yy + 4 && y < image.Height; y++)
            {
                for (var x = xx; x < xx + 4 && x < image.Width; x++)
                {
                    cellColors.Add(bitmap.GetPixel(x, y));
                }
            }

            // Get the average red, green, and blue values.
            var averageRed = cellColors.Aggregate(0, (current, color) => current + color.R) / cellColors.Count;
            var averageGreen = cellColors.Aggregate(0, (current, color) => current + color.G) / cellColors.Count;
            var averageBlue = cellColors.Aggregate(0, (current, color) => current + color.B) / cellColors.Count;

            var averageColor = Color.FromArgb(averageRed, averageGreen, averageBlue);

            // Go BACK over the 4x4 cell and set each pixel to the average color.
            for (var y = yy; y < yy + 4 && y < image.Height; y++)
            {
                for (var x = xx; x < xx + 4 && x < image.Width; x++)
                {
                    bitmap.SetPixel(x, y, averageColor);
                }
            }
        }
    }
    return bitmap;
}


texts: Is it ok to use Thread.Sleep and Thread.Interrupt for pausing and resuming Thread like this?

texts:
I need to observe a ConcurrentQueue, but to minimize the resources I want to pause the Thread if the Queue is empty and resume it from another Thread if there is a new Entry in the Queue. I implemented a pausing and an resuming of a thread like this:

My Worker, where the DoWork() method is called in a new Thread, looks like this:

public static class Worker
{
    public static bool Running = true;

    public static void DoWork()
    {
        while (Running)
        {
            try
            {
                Thread.Sleep(Timeout.Infinite);
            }
            catch (ThreadInterruptedException)
            {
                DoActualWork();
            }
        }
    }

    private static void DoActualWork()
    {
        //Do something
    }
}

I start the thread like this:

Thread workerThread = new Thread(Worker.DoWork);
workerThread.Start();

I interrupt the Thread like this:

workerThread.Interrupt();

I stop the Thread like this:

Worker.Running = false;

Everything is working as expected but I'm not sure if this is how it should be implemented.

Is this best practice?
What can go wrong?
Is there a problem with the static class and the members? (It have to be static because the Thread have to be interrupted by different Threads)


texts: How can I reverse the first K elements of an array?

texts:
I have an array and I need to make one function which has two parameters, array and K. I need to return a new array with only K elements reversed, the rest becoming the same as in array. I am able to get correct results but I think its performance is too slow. Is there any better solution to get the same results?

var arry=[2,3,1,5,7,9];
var k=3
function reverseOnlyK_elment(arr,k){
    var copyarray=[];
    var j=0;
    for(var i=k-1;i>=0;i--){
        copyarray[j++]=arr[i]
    }
    for(var i=k;i<=arr.length-1;i++){
        copyarray[j++]=arr[i]
    }
    console.log(copyarray)
}
reverseOnlyK_elment(arry,k)

Fiddle

Expected output:

[1, 3, 2, 5, 7, 9]


texts: Recording options selected from dropdown menu

texts:
I am hoping someone can help me attain better performance and better ways of writing this script.  Any help would be awesome!

Overall Goal: I have a dropdown that allows someone to select an option from it.  It will add that record to the table below, and then the option will be removed.  If they delete that row in the table, it then adds that option back to the dropdown.

$(function() {
$('#addResource').on('change', function(){
var $selectBox = $(this),
    oID   = $selectBox.val(),
    oText = $selectBox.children(':selected').text(),
    url   = '/admin/contacts/json',
    oSize = $selectBox.children('option').size()
    noResources = '
No Resources.
';

//if select box out of options lets hide it
if((oSize-1) == 1) {
    $selectBox.hide().parent().append('
No More Contacts Available
');
}

// lets remove the selected option
$selectBox.children(':selected').remove();
$selectBox.children(':first').attr('selected','selected');

// lets get the contact to add to the table
$.post(url, { id: oID },function(data){
    var tableRow = "
<input type='hidden' value='"+data.id+"' name='resouces[]'>"+data.name+"	"+data.phone+"	"+data.email+"	$"+data.rate+"
",
        table = $("#resourcesTable tbody");

    table.find('tr.no-resources').remove();
    table.append(tableRow);

    cssClass = '.remove_'+data.id;
    table.on('click',cssClass, function(e){
        var $trash  = $(this),
            rowId  = $trash.attr('data-id');

        // open confirm modal window
        modalMsg('Are you sure you wish to delete '+data.name+' as a resource?','',function(result){
            // remove deleted row
            $(".resource_"+rowId).fadeOut(function(){
                var size = table.find('tr').size(),
                    name = $(this).find('.name').text();

                $selectBox.append("<option value='"+rowId+"'>"+name+"</option>"); // add option back to dropdown
                $(this).remove(); // remove the table row when deleted
                if((size-1) == 0 ){ // if no more talbe rows put back no resources message
                    table.append(noResources);
                }
            });

            // need to
        })
        e.preventDefault();
     });
    // need to add input fields to post to save to database
}, "json" );
}); // end on change
});


texts:
I have this piece of code that is running too slow. I was wondering if anyone can help me optimize it as I can't seem to find any more shortcuts. I'm not sure if using List<> is going to help me but I need complex operation such as Union and Overlap.

Also, List is desirable because I don't know how many unique partitions an Image Region is going to be before running.

u1.length = 13254 which is the number of distinct elements in RevisedListMeanH
RevisedListMeanH.Count = 90000

The purpose of the first piece of code is to group together pixels via horizontal comparison and vertical comparison. This runs for about 70 seconds.

The second portion combines both vertical and horizontal pixel blocks into a 2D-block. This section runs for about 120 seconds. My goal is to have both of these loops complete under 10 seconds.

These numbers are from a 300x300 pixel region comparisons of a 4000x3000 image.

watch.Start();
for (int s = 0; s < u1.Length; s++ )//iterate through uniquelist
{
    List<int> ConnectedBlocksH = new List<int>();
    List<int> ConnectedBlocksV = new List<int>();

    float[] RH = RevisedListMeanH.ToArray();
    float[] RV = RevisedListMeanV.ToArray();

    for (int a = 0; a < RevisedListMeanH.Count; a++)//iterate through bitmap with res
    {
        if (u1[s] == RH[a])
        {
            ConnectedBlocksH.Add(a);//add the index

        }
    }
    for (int a = 0; a < RevisedListMeanV.Count; a++)//iterate through bitmap with res
    {
        if (u1[s] == RV[a])
        {
            ConnectedBlocksV.Add(a);//add the index

        }
    }
    ArrayOfConnectedBlocksH[s] = ConnectedBlocksH;//where the data IS
    ArrayOfConnectedBlocksV[s] = ConnectedBlocksV;//where the data IS
}
watch.Stop();
long asasasdda = watch.ElapsedMilliseconds; //71 sec
watch.Reset();

 watch.Start();
//if intersects then union the two lists
//iterate through both list
List<List<int>> ListOfConnectedBlocks = new List<List<int>>();
for (int a = 0; a < ArrayOfConnectedBlocksH.Length; a++ )
{
    HashSet<int> i = new HashSet<int>(ArrayOfConnectedBlocksH[a]);
    //trigger means it scanned and there was no overlap to add to the group
    while (true)
    {

        bool trigger = true;
        for (int b = 0; b < ArrayOfConnectedBlocksV.Length; b++)
        {
            if (i.Overlaps(ArrayOfConnectedBlocksV[b]))
            {
                i.UnionWith(ArrayOfConnectedBlocksV[b]);//combines all overlaps into one group
                ArrayOfConnectedBlocksV[b].Clear();//merged so just remove
                trigger = false;
            }

        }
        if (trigger)
        {
            break;
        }
        trigger = true;
        for (int c = 0; c < ArrayOfConnectedBlocksH.Length; c++)//now cycle through horizontal
        {
            if (i.Overlaps(ArrayOfConnectedBlocksH[c]))
            {
                i.UnionWith(ArrayOfConnectedBlocksH[c]);//combines all overlaps into one group
                ArrayOfConnectedBlocksH[c].Clear();//merged so just remove
                trigger = false;
            }

        }//first cycle to get T0

        if(trigger)
        {
            break;
        }
    }

    if (i.Count != 0)
    {
        ListOfConnectedBlocks.Add(i.ToList<int>());
    }
}

watch.Stop();
long asasasda = watch.ElapsedMilliseconds;//122 seconds


texts: Optimizing Node MySQL Query for CPU Utilization

texts:
I am working on a NodeJS port listener code that listens to a particular TCP port on the server. The obtaining the data from the port, the data is split using a delimited (for instance comma ,) and inserts this data into the MySQL database.

I have written the code and I was successfully able to insert data into MySQL server. My issue is that the process is consuming more CPU than expected.

For instance, I ran the code on a 2 core 4 GB RAM Linux Server. The process consumes about 25-50% CPU when only one packet is received every 60 secs. The project should be able to listen to at least 00 packets of data per second on this configuration.

var net = require('net');

    var mysql = require('mysql');
    var PORT = 5000;

    net.createServer(function(sock) {
     console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

  sock.on('data', function(data) {

    console.log('DATA ' + sock.remoteAddress + ': ' + data);
    var dataArray = data.toString().split(',');

    var pool = mysql.createPool({
    host: hostname,
    user: "abc",
    password: "123",
    database: "abc",
    connectionLimit:100
});

  console.log("Connected!");
  var sql = "INSERT INTO `table`(`val1`, `val2`, `val3`, `val4`, `val5`, `val6`) VALUES ('1','"+dataArray[6]+"','"+dataArray[10]+"','"+dataArray[9]+"','"+dataArray[11]+"','"+dataArray[13]+"')";
  console.log(sql);

  pool.getConnection(function(err, connection) {
        if (err) throw err;

  connection.query(sql, function (err, result) {
    connection.release()
    if (err) throw err;

    console.log("Data Inserted into Table1");
  });

  var sql = "INSERT INTO `table2`(`datafield`) VALUES ('"+data+"')";
  console.log(sql);
  pool.getConnection(function(err, connection) {
        if (err) throw err;

  connection.query(sql, function (err, result) {
    connection.release()
    if (err) throw err;
    console.log("Data Inserted into Table2");
  });

    sock.write('You said "' + data + '"');

    connection.release();
  });

 sock.on('close', function(data) {

   console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);

 });
}).listen(PORT);

console.log('Server listening on '+ PORT);


texts: Custom multiple div appends in JavaScript

texts:
I hope you can get me out of my current predicament which involves coding style when it comes to appending many elements in a pretty flexible and typesafe way.

Now I see my code below and I feel that it can be written in a more compact and shorter manner, especially in my set function. Also, I'm not sure if I should merge the arrays and keep it in one line.

What makes me wonder most however, is how to append all those divs to a document fragment before placing them to the real DOM as it is fairly complex.

Would you say I'm right about the possible improvements that can be made? If so, then how can I improve it?

jsFiddle

var superContainer = document.getElementsByClassName('superContainer');
    var article = document.getElementsByTagName('article');
    var obj = {};

    var wrappers = ['a', 'b', 'c'];

    var a1 = ['fruits', 'meat', 'milk', 'soup', 'sweets'];
    var a2 = ['troll', 'gollum', 'imp', 'ork', 'dolly'];
    var a3 = ['foobar'];

    var misc = ['boring', 'fun', 'annoying', 'great'];

    function Constructor() {
        function set() {
            for(var i = 0; i < article.length; i++) {
                var tempSC = document.createElement('div');

                tempSC.appendChild(article[i].parentNode.replaceChild(tempSC, article[i]));
                tempSC.className = 'superContainer';

                create(superContainer[i], wrappers, 0, 0);
                create(obj.a[i], a1, 0, 0);
                create(obj.b[i], a2, 0, 0);
                create(obj.c[i], a3, 0, 0);
                create(obj.milk[i], misc, 1, 2);
                create(obj.sweets[i], misc, 0, 1);
                create(obj.milk[i].children[0], misc, 3, 0);
                create(obj.sweets[i].children[1], misc, 3, 0);
            }
        }

        set();

        function create(parent, elem, loopStart, loopEnd) {
            for(var i = loopStart; i < elem.length - loopEnd; i++) {
                var result = document.createElement('div');
                result.className = elem[i];

                parent.appendChild(result);
                obj[elem[i]] = document.getElementsByClassName(elem[i]);
            }
        }
    }

    Constructor();
}


texts:
I have a table to Log visitor Count Like :

public class VisitorLog:BaseEntity
{
    public int Id { get; set; }
    public DateTime VisitedOn { get; set; }
    public string LocationIP { get; set; }
    public string BrowserName { get; set; }

    public VisitorLog()
    {
        VisitedOn = DateTime.Now;
    }
}

and in Global.asax I have this :

protected void Application_BeginRequest(object sender,EventArgs e)
{
    if (new HttpRequestWrapper(Request).IsAjaxRequest()) return;

    foreach (var task in ApplicationObjectFactory.Container.GetAllInstances<IRunOnEachRequest>())
    {
        task.Execute();
    }
}

and Implementation in Service Layer is like below :

public bool Add(string locationId, string browserName)
{
    if (string.IsNullOrEmpty(locationId) || string.IsNullOrEmpty(browserName)) throw new ArgumentNullException("Visitor Log");
  return  Add(new AddVisitLogViewModel { BrowserName=browserName,LocationIP=locationId.ToLower()});
}

public bool Add(AddVisitLogViewModel visitorLogViewModel)
{

    if (visitorLogViewModel == null) throw new  ArgumentNullException("visitorLog");
    if (Any(row => row.LocationIP == visitorLogViewModel.LocationIP && DbFunctions.TruncateTime(row.VisitedOn) ==DbFunctions.TruncateTime(DateTime.Now))) return false;
    var model = Mapper.Map<VisitorLog>(visitorLogViewModel);
    AddItem(model);
    return true;
}

In Application_BeginRequest I have to check request is Ajax or Action Call and others , is there a better way to check this or Improve these code ?


texts: Space complexity of the "add two binary strings" challenge

texts:
I was solving this problem of "adding two string binary numbers" and came up with the following algorithm. I am trying to analyze its time and space complexity. While I was satisfied with its time complexity which is \$O(n)\$, I am not really sure about the space. I think the space complexity is \$O(n)\$ as well but I might be wrong because of the StringBuilder usage here.

public String sumOfBinary(String x, String y) {
    if((x.length == 0 && y.length == 0) || (x == null && y == null))
       return;

    int i = x.length - 1, j = y.length - 1, carry = 0;
    StringBuilder sb = new StringBuilder();

    while(i > = 0 || j >= 0) {
     int sum = carry;
     if(i >= 0) {
       sum+= x.charAt(i--) - '0';
     }
     if(j>=0) {
       sum+=y.charAt(j--) - '0';
     }

     sb.append(sum%2);
     carry = sum/2;

    }
    if(carry!=0) {
      sb.append(carry);
    }
   return sb.reverse().toString();
}

It would be awesome if someone could review the code and let me know if there is any other better way to do this, along with what the space complexity is in the algorithm.


texts:
Here's a very small and basic script that sends commands over SSH to another computer on my network:

#!/bin/python
import sys, os
commands = ""
for i in sys.argv[1:]:
        commands += " " + i;

if len(sys.argv) <= 1:
        os.system("sshpass -p VerySecrectPassword ssh pi@172.16.0.141")
else:
        os.system("sshpass -p VerySecrectPassword ssh pi@172.16.0.141" + commands)

Am I being very "Pythonic"? Is it better to use a for loop to join all the commands or the join function?

commands = " ".join(sys.argv[1:])

Personally, I think the for loop reads better, but that's just my opinion and I'm a newbie. Which is considered the better way to do things?

Furthermore:

Are there any other areas in this script that could be improved?
Is it a bad idea to store the password in the script (located at /usr/bin)?

Note: This script is stored on a computer where I am the only user (except root).


texts: Copying one array to the end of another array

texts:
I wrote a program that places values in one array to the end of another array. It keeps the order of the values. If the second array is bigger, then there will be leading zeroes.

Is there anything I can improve? How do I simplify this program?

#include <iostream>

    int main()
    {
        int fromArray[10] = {11,22,33,44,55,66,77,88,99,100};
        int toArray[15] = {};

        int size = sizeof(fromArray)/sizeof(fromArray[0]);

        int * first = fromArray;
        int * last = first + size; //One past end of array
        int * toLast = toArray + sizeof(toArray)/sizeof(toArray[0]); //One past end of array

        for(first; first != last;)
            *(--toLast) = *(--last);

        for(int i=0; i<sizeof(toArray)/sizeof(toArray[0]); i++)
            std::cout << toArray[i] << " ";

    }


texts:
I've created this function that looks for sequences in a list. If [1,2,3] exists, it will print True. I've tested the code and it works fine.

def looking_patt(pattern,cursor,found):
    big_s = []
    for i in range(1,101):
        if i % 10 == 0:
            big_s.extend([1,2,3])
        else:
            big_s.append(i)
    # check control
    print(big_s)

    for i in big_s:
        if i == pattern[cursor]:
            cursor += 1
            if cursor == len(pattern):
                found.append(pattern)
                print(found)
                cursor = 0
        else:
            cursor = 0

    print(len(found) > 0)

Part of the script (the for i in big_s:) has been taken from an answer in this SO question.

How can it be improved?


texts: Checking for Null before adding into List

texts:
Is there any way to refactor this?

public IEnumerable<Option> Options
{
    get
    {
        {
            List<Option> ListOption = new List<Option>();

            if (!String.IsNullOrEmpty(Option1))
            {
                ListOption.Add(new Option() {Name=Option1 });
            }
            if (!String.IsNullOrEmpty(Option2))
            {
                ListOption.Add(new Option() { Name = Option2 });
            }
            if (!String.IsNullOrEmpty(Option3))
            {
                ListOption.Add(new Option() { Name = Option3 });
            }
            if (!String.IsNullOrEmpty(Option4))
            {
                ListOption.Add(new Option() { Name = Option4 });
            }

            return ListOption;
        }
    }
}

public class Option
{
    public string Name { get; set; }
}


texts: Wrap a long string to an array of short-enough strings

texts:
I have made a function that wraps text in pygame (i.e. it turns a long string into an array of smaller strings that are short enough so they fit within the given width when rendered in the given font).

My function is below. text is the string we want to break up, font is a pygame font object, and max_width is the number of pixels wide we want the lines to be at maximum (an integer).

def wrap_text(text, font, max_width):
    lines = []
    words = text.split(" ")

    while words:
        line = words.pop(0)
        if words:
            width = font.size(" ".join((line, words[0])))[0]
            while width < max_width:
                if words[0] == "\n":
                    # Forced newline when "\n" is in the text
                    del words[0]
                    break
                line = " ".join((line, words.pop(0)))
                if not words:
                    break
                width = font.size(" ".join((line, words[0])))[0]

        if font.size(line)[0] > max_width:
            # When there is only one word on the line and it is still
            # too long to fit within the given maximum width.
            raise ValueError("".join(("\"", line, "\"", " is too long to be wrapped.")))
        lines.append(line)

    return lines

note: font.size(string) returns a tuple containing the width and height the string will be when rendered in the given font.

As you can see, I have the statements while words:, if words: and if not words: all within each other. I have been trying to refactor this by moving things around but I simply cannot think of a way to remove any of the 3 statements above. Any help is much appreciated :). Any comments about anything else in my code is welcome too.


texts: "Sequence full of colors" challenge on HackerRank

texts:
This is the challenge:

You are given a sequence of N balls in 4 colors: red, green, yellow and blue. The sequence is full of colors if and only if all of the following conditions are true:

There are as many red balls as green balls.
There are as many yellow balls as blue balls.
Difference between the number of red balls and green balls in every prefix of the sequence is at most 1.
Difference between the number of yellow balls and blue balls in every prefix of the sequence is at most 1.
Your task is to write a program, which for a given sequence prints True if it is full of colors, otherwise it prints False.

and this is my solution:
import Control.Monad (replicateM, foldM)

main :: IO ()
main = do
  n <- getLine
  list <- replicateM (read n :: Int) getLine
  mapM_ (print . isgood) list

isgood :: String -> Bool
isgood = isValidFinal . foldM step (0,0)
  where
    step (x,y) c
      | c == 'R' = wrapValidInJust (x - 1, y)
      | c == 'G' = wrapValidInJust (x + 1, y)
      | c == 'Y' = wrapValidInJust (x, y - 1)
      | c == 'B' = wrapValidInJust (x, y + 1)
    isValid (x,y) = abs x <= 1 && abs y <= 1
    wrapValidInJust xy = if isValid xy then Just xy else Nothing
    isValidFinal (Just x) = x == (0,0)
    isValidFinal Nothing = False

I'm kind of happy with main and isgood, but the step function seems very hard to read.
Any feedback?


texts: Having a parent respond to a child's event

texts:
I have a parent object (a display window) and it has a few child objects (buttons and controls on the window). I would like one child object to hide itself when another is clicked. Currently, I have my parent object bind to a custom event expected to be fired from the child object. Then, the parent object passes the command on to its other child.

Example:

//Namespace for the 'Orders' page.
$(function Orders() {
    "use strict";
    var orders = $('#Orders');

    var ordersSearchResult = new OrdersSearchResult();
    var ordersSearchDisplay = new OrdersSearchDisplay();
    var ordersEditDisplay = new OrdersEditDisplay();

    ordersSearchResult.selector.bind('searchResultLinkClicked', function () {
        ordersEditDisplay.hide();
        ordersSearchDisplay.fadeIn();
    });
});

I have two questions / concerns about this code:

I expose a property called 'selector' for ordersSearchResult. This is a direct reference to the jQuery DOM element. As I understand it this is bad practice -- objects should expose methods to affect their DOM elements, but not the DOM elements themselves. Previously, I passed the onSearchResultLinkClicked anonymous function into a method of ordersSearchResult which bound the event to the selector internally. I felt that that implementation was counter-intuitive, though, as it did not read very clearly to see anonymous functions being passed into 'binding' methods.
ordersEditDisplay and ordersSearchDisplay expose methods hide() and fadeIn() which affect their DOM elements, but ordersEditDisplay/ordersSearchDisplay are not DOM elements themselves. Is it bad practice to 'confuse' other developers like this? The code could read: ordersEditDisplay.selector.hide() but I did not want to expose the selector publically.


texts: Updating list of Dictionaries from other such list

texts:
Basically I have created a function which takes two lists of dicts, for example:

oldList = [{'a':2}, {'v':2}]
newList = [{'a':4},{'c':4},{'e':5}]

My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList.
So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}].

Is there a better way to do this?

def sortList(oldList, newList):
    for new in newList: #{'a':4},{'c':4},{'e':5}
        isAdd = True
        for old in oldList: #{'a':2}, {'v':2}
            if new.keys()[0] == old.keys()[0]: #a == a
                isAdd = False
                old.update(new) # update dict
        if isAdd:
            oldList.append(new) #if value not in oldList append to it
    return oldList

sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])
print sortedDict

[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]


texts:
Consider the following code.

public async void Connect()
{
  bool success = await ConnectAsync();
  if (success) NotifyUserOfSuccess();
}

public async Task<bool> ConnectAsync()
{
  var t = await Task.Run(()=>
    try {
       ConnectSynchronously();
    } catch (Exception e)
    {
       return false;
    }
    return true;
   );
}

When analyzing this code, I come to the conclusion that I potentially am kicking off three threads.
Assume that both await's will not already be completed when called, then the first thread is kicked off by the await ConnectAsync(); which in turn kicks off the await Task, and the Task.Run will kick off the function inside in a third thread.
I really only need one thread, namely the one in Connect().

How can I improve the design?

As Connect() contains the await keyword, shouldn't it really be called ConnectAsync() regardless of its return value?


texts: Find all files that match a filename pattern in a folder tree

texts:
I am an old python newbie here, migrating from fortran77 ;)
Still unsure of the python terminology at the moment :(

The python3 script below fetches a large list of matching files in a folder tree, in the format:

[ fully_qualified_folder_name, [list of matching files in this folder] ]

Being only a python newbie, there HAS to be a better way ?

I hope to use the code to generate a nightly json file underpinning a chromecasting web server on a Raspberry Pi 4, based on Google's example chrome (web page) "sender".
The web page will eventually use javascript on the client-side for the user to choose a file from a list and "cast" it from the Pi4's apache2 web server over to the chromecast device.
So, I thought, why not give try Python a try ?

Suggestions would be appreciated.

import os
import fnmatch
def yield_files_with_extensions(folder_path, file_match):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if fnmatch.fnmatch(file.lower(),file_match.lower()):
                #yield os.path.join(root, file)
                yield file
        break  # without this line it traverses the subfolders too
def yield_files_in_subfolders(folder_path, file_match):
    for root, dirs, files in os.walk(folder_path):
        for d in dirs:
            subfolder = os.path.join(root, d)
            mp4_files = [subfolder, [f for f in yield_files_with_extensions(subfolder, file_match)]]
            yield mp4_files
#
the_path = r'/mnt/mp4library/mp4library'
# retieve the topmost folder's files
mp4_files1 = [[ the_path, [f for f in yield_files_with_extensions(the_path, "*.mp4")] ]]
mp4_files2 = [f for f in yield_files_in_subfolders(the_path, "*.mp4")]
mp4_files2 = mp4_files1 + mp4_files2
crecords=0
cfiles=0
for a in mp4_files2:
    crecords=crecords+1
    print ("-----record "+str(crecords)+"---" + a[0] + " ... files=" + str(len(a[1])))
    #print (a[0])
    #print (a[1])
    c=0
    for b in a[1]:
        c=c+1
        print ("mp4 File "+str(c)+"---" + b)
    cfiles=cfiles+c
print ('Count of files: ' + str(cfiles))


texts:
I am new to Java programming, and to help me learn, I created a simple telephone address book.  The code runs as expected, but I would be interested to here from more advanced programmers if they think I should do it differently.

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

import java.net.UnknownHostException;
import java.util.Scanner;

import org.bson.types.ObjectId;

public class MongodbPhonebook {
    public static void main(String[] args) {
        boolean boolContinue = true;
        String stringCommand;
        Scanner input = new Scanner(System.in);

        try {
            MongoClient mongoClient = new MongoClient();
            DB db = mongoClient.getDB( "myphonelist" );
            DBCollection coll = db.getCollection("myphonelist");

            do {
                System.out.println("Enter command (add, find, show, quit): ");
                stringCommand = input.nextLine();
                if(stringCommand.equals("quit")){
                    boolContinue = false;
                }
                else if(stringCommand.equals("show")){
                    displayAll(coll);
                }
                else if(stringCommand.equals("add")){
                    insertNumber(coll);
                }
                else if(stringCommand.equals("find")){
                    findNumber(coll);
                }
                else {
                    System.out.println("Unknown command!");
                }
            } while(boolContinue == true);
        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (MongoException e) {
            e.printStackTrace();
        }
    }

    public static void displayAll(DBCollection collDisplay) {
        DBCursor cursor = collDisplay.find();
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
        return;
    }

    public static void insertNumber (DBCollection collInsert) {
        Scanner input = new Scanner(System.in);
        ObjectId stringID;
        String stringName = "";
        String stringNumber = "";
        System.out.println("Enter name: ");
        stringName = input.nextLine();
        System.out.println("Enter number: ");
        stringNumber = input.nextLine();
        BasicDBObject doc = new BasicDBObject("name", stringName).
                append("number", stringNumber);
        collInsert.insert(doc);
        stringID = (ObjectId)doc.get( "_id" );
        System.out.println("Result: " + stringID.toString());
        return;
    }

    public static void findNumber (DBCollection collFind) {
        Scanner input = new Scanner(System.in);
        String stringName = "";
        System.out.println("Enter name: ");
        stringName = input.nextLine();
        BasicDBObject query = new BasicDBObject("name", stringName);

        DBCursor cursor = collFind.find();
        cursor = collFind.find(query);

        try {
            while(cursor.hasNext()) {
                System.out.println("found " + cursor.next());
            }
        } finally {
            cursor.close();
        }
    }
}


texts:
What do you think of this code?

#include <utility>

namespace
{

template <typename F, int I, typename L, typename R, typename ...A>
inline F cify(L&& l, R (*)(A...) noexcept(noexcept(
  ::std::declval<F>()(::std::declval<A>()...))))
{
  static thread_local L l_(::std::forward<L>(l));
  static thread_local bool full;

  if (full)
  {
    l_.~L();

    new (static_cast<void*>(&l_)) L(::std::forward<L>(l));
  }
  else
  {
    full = true;
  }

  struct S
  {
    static R f(A... args) noexcept(noexcept(
      ::std::declval<F>()(::std::forward<A>(args)...)))
    {
      return l_(::std::forward<A>(args)...);
    }
  };

  return &S::f;
}

}

template <typename F, int I = 0, typename L>
F cify(L&& l)
{
  return cify<F, I>(::std::forward<L>(l), F());
}

It can be used to supply a capturing lambda as a C callback:

int main()
{
  int a;

  auto const f(cify<void(*)()>([a]{::std::cout << "a: " << a << ::std::endl;}));

  f();

  return 0;
}

If you need the same callback across multiple threads, or when thread_local is unimplemented in your compiler, you can remove the thread_local keyword.

To fix the problem in the answer, one can make use of the __COUNTER__ macro. It is only one of numerous possible solutions.

std::vector<void(*)()> callbacks;

template <int I>
void add_callback (int x)
{
        callbacks.emplace_back(cify<void(*)(), I>([x] () { std::cout << x; }));
}

int main ()
{
        add_callback<__COUNTER__>(1);
        add_callback<__COUNTER__>(2);

        for (auto& callback : callbacks) {
                callback();
        }
        return 0;
}


texts:
I am writing a Comparator for my TreeMap. It looks like this:

private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR =
new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        int cmp = o1.toLowerCase().compareTo(o2.toLowerCase());
        if (cmp != 0) return cmp;

        return o1.compareTo(o2);
    }
};

My IDE hints me that it could be written in a lambda. I came up with this idea:

private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR_LAMBDA =
(s1, s2) ->
s1.toLowerCase().compareTo(s2.toLowerCase()) == 0 ?
s1.compareTo(s2) : s1.toLowerCase().compareTo(s2.toLowerCase());

But then I am duplicating the first call s1.toLowerCase().compareTo(s2.toLowerCase(). This is doing two  String manipulation and one comparison more than the not lambda expression.


texts:
The task is taken from leetcode

  Given an array A of non-negative integers, return an array consisting
  of all the even elements of A, followed by all the odd elements of A.

  You may return any answer array that satisfies this condition.

  Example 1:

  Input: [3,1,2,4]

  Output: [2,4,3,1]

  The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be
  accepted.

  Note:

  1 <= A.length <= 5000

  0 <= A[i] <= 5000

My functional solution 1

const sortArrayByParity = A => A.reduce((acc, x) => {
        if (x % 2 === 0) { acc.unshift(x); }
        else { acc.push(x); }
        return acc;
    }, []);

My functional solution 2

const sortArrayByParity = A => A.reduce((acc, x) => x % 2 === 0 ? [x, ...acc] : [...acc, x]);

My imperative solution

function sortArrayByParity2(A) {
  const odd = [];
  const even = [];
  for (const a of A) {
    if (a % 2 === 0) {
      even.push(a);
    } else {
      odd.push(a);
    }
  }
  return [...even, ...odd];
};


texts:
I'm writing a piece table library in Rust with the structures:
#[derive(Default)]
struct Piece {
    additional: bool,
    offset: usize,
    length: usize,
}

and
/// PieceTable contains the additional, original buffers and a vector of pieces.
/// It also maintains a length variable.
pub struct PieceTable {
    table: VecDeque<Piece>,
    orig_buffer: String,
    add_buffer: String,
    length: usize,
}

I'm fairly confident that I didn't mess anything up here, though I'm not sure if VecDeque is the best structure to hold the pieces. My insert method is:
impl PieceTable {
    ...
    pub fn insert(&mut self, index: usize, text: &string) {
        match self.piece_at(index + 1) {
            Ok((index, offset)) => {
                // isolate piece being inserted into
                let into = &self.table[index];
                // create necessary Pieces to enter
                let previous = Piece {
                    additional: into.additional,
                    offset: into.offset,
                    length: offset - into.offset,
                };
                let insert = Piece {
                    additional: true,
                    offset: self.add_buffer.len(),
                    length: text.len(),
                };
                let next = Piece {
                    additional: into.additional,
                    offset: offset,
                    length: into.length - (offset - into.offset),
                };

                // remove index, add in previous, insert, next
                self.table.remove(index);
                self.table.insert(index, previous);
                self.table.insert(index + 1, insert);
                self.table.insert(index + 2, next);

                // update buffer, length vars
                self.add_buffer.push_str(text);
                self.length += text.len();
           }
           Err(_) => self.push_str(text),
        }
    }
}

Which refers to the piece_at method:
fn piece_at(&self, index: usize) -> Result<(usize, usize>, i32> {
    if index > self.length {
        return Err(-1);
    }

    let mut remaining = index.clone();
    for (i, piece) in self.table.iter().enumerate() {
        if remaining <= piece.length {
            return Ok((i, remaining));
        }
        remaining -= piece.length;
    }

    return Err(-1);
}

It also relies on the push_str method, which is just appends a piece with the proper parameters to the end of self.table.
This algorithm is stolen basically verbatim from the python implementation at https://github.com/saiguy3/piece_table, so hopefully there's nothing terribly wrong with it that I missed. Rust is hard and I started learning it yesterday, so I'm fully expecting I horribly misused some language feature.
Thanks!


texts: Form submission handler with terms and conditions checkbox and double-click prevention

texts:
I'm experienced with JavaScript, but new to refactoring.  Sonar specified that the below function is too complex.  I'm looking for suggestions on how to simplify it, mainly the conditional statements.

_executeWhenReady: function() {
    if ($('#applyButton').length) {
        $('#applyButton').on('click', function(e) {
            if (appProcessing.isTermsChecked() && !$('#applyButton').hasClass('noClick')) {
                $('#applyButton').addClass('noClick');
                appProcessing.proceedToApp();
            } else {
                e.preventDefault();
                $("#termsConditionsChBx").removeClass('checkbox-checked').removeClass('checkbox').removeClass('checkbox-error').addClass('checkbox-error');
                if ($('.checkboxErrorText').length) {
                    $('.checkboxErrorText:first').removeClass('hidden');
                }
                return false;
            }
        });
    }

    if ($('#btnBenefitsCancel').length) {
        $('#btnBenefitsCancel').on('click', function() {
            $('#benefitsCancel').attr('value', true);
        });
    }

    if ($("#termsConditionsChBx").length) {
        $('#termsConditionsChBx').on('click', function() {
            appProcessing._eConsentCheck("termsConditionsChBx");
        });
    }
    $("#termsConditionsChBx_Native").on('change', function() {
            appProcessing._eConsentCheck("termsConditionsChBx");
    });
}


texts:
Though this program tells the truth (unless you change the source code), it does tell Fibonacci numbers, depending on the user's input. Keeping in mind of all (or most) of the feedback given from previous questions, I wrote this program to see how well I have progressed.

def get_fibonacci_sequence(max):
    '''
    Returns the Fibonacci sequence from the
    first to the nth Fibonacci number.
    '''

    fib1 = 1
    fib2 = 1
    result = [fib1, fib2]
    for i in range(2, max):
        result.append(fib1 + fib2)
        fib1 = fib2
        fib2 = result[i]
    return result

def get_nth_fibonacci(n):
    '''Returns the nth Fibonacci number.'''

    return get_fibonacci_sequence(n)[n - 1]

def main():
    print("Would you like to have the sequence or the number?")
    print("Enter 's' for sequence, and anything else for the number.")
    seqOrNum = input("> ")
    if seqOrNum == 's':
        print("Up to which number would you like the sequence up to?")
        max = int(input("> "))
        print("The sequence up to the {}th Fibonacci number:".format(max))
        print(get_fibonacci_sequence(max))
    else:
        print("Which Fibonacci number would you like to get?")
        max = int(input("> "))
        print("The {}th Fibonacci number is:".format(max),
              get_nth_fibonacci(max))

if __name__ == "__main__":
    main()

Example Output:

Would you like to have the sequence or the number?
Enter 's' for sequence, and anything else for the number.
> s
Up to which number would you like the sequence up to?
> 10
The sequence up to the 10th Fibonacci number:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Concerns:

Are my docstrings well-used?
Does it follow conventions?


texts: Random password cracker using brute force

texts:
I created a fun password cracker using literal brute force, searching each character to see if it matches an ASCII character 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. The password is randomly generated and will vary from 100,000 to 250,000 characters long. I use a wrapper timeit function to time the function and the output is a basic print statement using .format():

import random
import time

password = ""
attempted_password = ""
list_of_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in range(0, random.randint(100000, 250000)):
    password += list_of_chars[random.randint(0, 61)]

def timeit(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print "The function {.__name__} took {:.15f} seconds to finish.".format(func, time.time() - start)
        return result
    return wrapper

@timeit
def solve_password(word):
    global attempted_password
    for character in word:
        for entry in list_of_chars:
            if character == entry:
                attempted_password += character
                continue
    return attempted_password

print "The password: {0:}\nLength of password was: {1:}\nIs correct? : {2:}".format(solve_password(password),
                                                                                len(password),
                                                                                attempted_password == password)

An example output (without the password):

The function solve_password took 3.540999889373779 seconds to finish.
The password: *password is here*
Length of password was: 246416
Is correct? : True

So my questions are:

Am I following coding standards for Python 2 (like PEP8)
Is there anyway to improve performance, readability, etc.
Is there any way to make my code more "Pythonic" (like a native Python coder)?


texts: Creating a human-readable list from the values of a map

texts:
I'm creating a human-readable list from the keys of a map object.  I want it to be comma-separated, but include the word "and" at the end before the last element, supplying a given locale for the word "and".

E.g., my map might have the strings:

"AK", "Alaska"
"CA", "California"
"NY", "New York"

I would want as output:

Alaska, California, and New York

for English and

Alaska, California, y New York

for Spanish.

So I have:

public static String getHumanReadableStates(Map<String, String> stateMap) {

    long count = stateMap.values().stream().map(Object::toString).count();
    return stateMap.values().stream().map(Object::toString)
            .limit(count - 1)
            .collect(Collectors.joining(", "))
            .concat(", ")
            .concat(LocaleUtil.getBundleValue("theWordAnd"))
            .concat(" ")
            .concat(Objects.requireNonNull(stateMap.values().stream().reduce((first, second) -> second)
                    .orElse(null)));
}

where LocaleUtil has a method called getBundleValue() to simply get the word "and" from messages.properties.

Is there a simpler way to achieve this?  Or should streams be avoided altogether?


texts:
Given a nested list of strings (which may contain other nested lists), print the contents of the list and the corresponding depth.

Here is my solution:

private static void dumpList(String string, List l) {
    int n = l.size();
    for (int i = 0; i < n; i++) {
        if(l.get(i) instanceof String){
            System.out.println(string+i + " " + l.get(i));
        }
        if(l.get(i) instanceof List){
            dumpList(string+i, (List)l.get(i));
        }
    }
}

Here is main():

public static void main(String[] args) {
    String s = "Foo";
    List l = new ArrayList();
    ArrayList<String> a = new ArrayList<String>();
    ArrayList<String> b = new ArrayList<String>();
    //ArrayList<String> c = new ArrayList<String>();
    a.add("a");
    a.add("b");
    a.add("c");
    b.add("eggs");
    l.add("a string");
    l.add(a);
    l.add("spam");
    l.add("eggs");
    dumpList("Foo", l);
}

My output:

Foo0 a string
Foo10 a
Foo11 b
Foo12 c
Foo2 spam
Foo3 eggs

I am not that much interested in naming of the variables, but of formatting of the output. Should I use StringBuilder instead of the + operator? Should I print it differently?


texts: Maintaining a count with two threads using conditional variables

texts:
This is just a program to show the use of conditional variables when two threads are involved. One thread wants a non-zero value of count, and other thread is responsible for signaling it when the count is non-zero.

Is there something in this code which still needs an improvement? Is there something which could have been done in a better way?

#include <iostream>

/* Declaration of a Mutex variable `mutexA`. */
pthread_mutex_t mutexA;

/* Declaration of a Condition Variable `conditionVariableA`. */
pthread_cond_t  conditionVariableA;

/* `functionA` and `functionB` are the argument functions of the two threads (declared
below) */
void* functionA (void*);
void* functionB (void*);

/* `count` is the variable shared between threads `A` and `B`.
Thread `A` wants it to be non zero. Thread `B` will be responsible for making it
non-zero and then issuing a signal. */
int  count = -100;

int main ()
{
    // Declaration of two threads namely `A`, and `B`.
    pthread_t A, B;

    // Initializing the mutex lock to be shared between the threads.
    pthread_mutex_init (&mutexA, NULL);

    /* The function `pthread_cond_init()` initialises the Condition Variable referenced by
    variable `conditionVariableA` with attributes referenced by variable `attributes`. If
    `attributes` is NULL, the default condition variable attributes are used. */
    pthread_cond_init (&conditionVariableA, NULL);

    /* Definition of two threads namely A and B */
    pthread_create (&A, NULL, functionA, NULL);
    pthread_create (&B, NULL, functionB, NULL);

    pthread_join (A, NULL);
    pthread_join (B, NULL);
}

void* functionA (void* argA)
{
    while (1)
    {
        pthread_mutex_lock (&mutexA);

        if (count <= 0)
        {
            std :: cout << "\ngnitiaW!\n";
            pthread_cond_wait (&conditionVariableA, &mutexA);
        }
        else
        {
            // Do something.
            std :: cout << "\nTime to enjoy!\n";
            return 0;
        }
        pthread_mutex_unlock (&mutexA);
    }
    return 0;
}

void* functionB (void* argB)
{
    while (1)
    {
        pthread_mutex_lock  (&mutexA);

        count++;

        if (count > 0)
        {
            pthread_cond_signal (&conditionVariableA);
            std :: cout << "\nSignaled!\n";
            return 0;
        }
        else
        {
            std :: cout << "\nNot signaled yet!";
        }

        pthread_mutex_unlock (&mutexA);
    }
    return 0;
}


texts: Prime number sieve using difference of two squares

texts:
Here is a working pari/gp implementation of prime number sieve. Is there something that I could change in code to achieve a better running time?

Sieve(g)=
{
A=vector(floor((g-1)/2));
for(n=1,floor((g-1)/2),
   A[n]=2*n+1);
for(x=3,floor(sqrt(g)),
   if(Mod(x,2)==1,i=0,i=1);
   forstep(y=i,x-3,[2],
      A[(x^2-y^2-1)/2]=0));
for(x=ceil(sqrt(g)),ceil((g+9)/6),
   i=ceil(sqrt(x^2-g));
   if(Mod(x+i,2)==0,i=i+1);
   forstep(y=i,x-3,[2],
      A[(x^2-y^2-1)/2]=0));
A=concat(2,A);
for(j=0,floor((g-1)/2),
   if(!(A[j+1]==0),print(A[j+1])))
}


texts: Extracting Multiple Associative arrays in PHP

texts:
public static function find_user_tracks($id)
{
    global $mySQL;
    $sql = "SELECT * FROM `tracks` WHERE account_id = {$id}";
    $result_set =  $mySQL->query($sql);
    $ret = array();
    while($row = $result_set->fetch_assoc())
    {
        $ret[] = $row;
    }
    return $ret;
}

The above code contains the result of a database query. The database looks like this:

So, basically, it will return a set of fields with values and then those values will be used for a certain page:

$row = Track::find_user_tracks($id);
if(!empty($row))
{
    $track_paths = array();
    $track_names = array();
    $track_desc = array();
    $track_ids = array();
    $track_artist = array();
    for($i = 0 ;$i<count($row);$i++)
    {
        $track_paths[] = $row[$i]['track_path'];
        $track_ids[] = $row[$i]['track_id'];
        $track_names[] = $row[$i]['track_name'];
        $track_desc[] = $row[$i]['track_desc'];
        $track_artist[] = $row[$i]['artist'];
    }
    echo "<h1> {$screename}'s Beats</h1>";
}

The $row variable contains the result from the previous queries. I loop over $row to extract every single bit of data like track_id, track_name, etc.

Is there any way to make this cleaner or improve it?


texts: Log monitoring with pythonic tail -f and process killing

texts:
The purpose of this cluster of functions is to tail the log file and kill/restart processes from shell (the latter is not yet implemented).

import sys
import time
import datetime
import os
import re

def read_log(f):
    """
    Basically tail -f
    """
    logfile = open(f)
    logfile.seek(0, os.SEEK_END)
    while True:
        new_line = logfile.readline()
        if new_line:
            yield new_line
        else:
            time.sleep(0.1)

def find_error(line, base_time, line_time):
    """
    Search for ERROR keyword in log line. Return True if found, False if not.
    """
    match = re.search('.*ERROR.*', line)
    if match and line_time < base_time:
        return True
    return False

def parse_time(line):
    """
    Parse string to datetime
    """
    date_regex = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
    date_string = re.search(date_regex, line).group(0)
    return datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

def increase_base_time(line_time):
    """
    Return a datetime that is line_time plus one minute
    """
    return line_time + datetime.timedelta(minutes=1)

def monitor(filename):
    """
    Read from a log file.
    For each line check if log line time is later than base comparison time.
    If so, update the base time and set error count to 0.
    Check for errors in line. Increment error count if any are found.
    Check the total error count. If it's greater than five, restart the logged
    process.
    Check if process has been restarted before. If so, kill the logged process.
    """
    count = 0
    base_time = datetime.datetime.min
    log = read_log(filename)
    restarted = False
    for line in log:
        line_time = parse_time(line)
        if line_time > base_time:
            base_time = increase_base_time(line_time)
            count = 0
        if find_error(line, base_time, line_time):
            count += 1
        if count >= 5:
            if restarted:
                print("Kill the process") # A placeholder, sorry
            else:
                print("Restart the process") # Also a placeholder, sorry
                count = 0
                restarted = True

monitor(sys.argv[1])

There are a lot of if-statement for doing checks. I thought about making this class based, but it really doesn't make sense to do it (functions don't need to share states and it is a rather small program).
Is the number of if's acceptable? How could I refactor the code to make it flow a bit better?

EDIT: As this was brought up, is it necessary that the tailing function would be non blocking? As I understand I wont be doing nothing until a line is yielded. What would be the benefits of going one way or the other?


texts: Using Python to model a single elimination tournament

texts:
I'm learning python and I want to model a single elimination tournament like they use in athletic events like tennis, basketball, etc.  The idea would be to insert some meaningful metrics to determine the winner.  I've already got a database that I plan to connect to to get the metrics, but I am hoping to find a better way to "process" games in the tournament to move the winner to the next round, and eventually find the tournament winner.

So far this is the best I have come up with, but it doesn't scale (at all easily) to 32, 64, 128 entries & so-on.  The "primary key" that I need to retain is the "seed id" (1-16, in this case), which matches the unique identifier in the database, so that I can pull the correct metrics for deciding which entry will win a matchup.  Suggestions?

## this list represents the round 1 seeding order on the tournament sheet
## this doesnt easily scale to 32, 64, 128 entries
teamlist = [1,16,8,9,5,12,4,13,6,11,3,14,7,10,2,15]

#In a single elim tournament with a full field, # of games is # of teams-1
totalgames = len(teamlist) - 1

#Set defaults
gameid = 0
roundid = 0
nextround = []

#simulate all of the games
while gameid < totalgames:
    if gameid in [8,12,14]:  ##this is a manual decision tree, doesn't scale at all
        #if a new round begins, reset the list of the next round
        print "--- starting a new round of games ---"
        teamlist = nextround
        nextround = []
        roundid = 0

    #compare the 1st entry in the list to the 2nd entry in the list
    homeid = teamlist[roundid]
    awayid = teamlist[roundid + 1]

    #the winner of the match become the next entry in the nextround list
    #more realistic metrics could be substituted here, but ID can be used for this example
    if homeid < awayid:
        nextround.append(homeid)
        print str(homeid) + " vs " + str(awayid) + ":  The winner is " + str(homeid)
    else:
        nextround.append(awayid)
        print str(homeid) + " vs " + str(awayid) + ":  The winner is " + str(awayid)

    #increase the gameid and roundid
    gameid += 1
    roundid += 2
    print "next round matchup list: " + str(nextround)

print nextround


texts:
Challenge: The Fibonacci sequence is generated by adding the previous two terms.

  By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8,
  13, 21, 34, 55, 89.

  Consider a Fibonacci sequence whose values do not exceed four million,
  find the sum of the even-valued terms.

My solution:

import java.util.ArrayList;

public class Euler2 {
    public static void main(String[] args) {
        final long START = System.nanoTime(),
            MAX_NUM = 4000000L;
        Long result = 0L;

        ArrayList<Long> sequence = new ArrayList<Long>() {
            { add(1L); add(2L); }
        };

        int i = 0;
        Long nextTerm = sequence.get(i++) + sequence.get(i);
        while (nextTerm <= MAX_NUM) {
            sequence.add(nextTerm);
            nextTerm = sequence.get(i++) + sequence.get(i);
        }

        /* Leveraging the absence of consecutive even numbers
        and the fact that Odd + Even is Odd, and Odd + Odd is even,
        retrieve every third term after an even term until no longer possible
        */
        int j = 1;
        while (j <= i) {
            result += sequence.get(j);
            j += 3;
        }

        System.out.print("Result: " + result +
            ".\nTime used for calculation in nanoseconds: " +
            (System.nanoTime() - START) + "."
        );
    }
}

Sample output:

  Result: 4613732.
  Time used for calculation in nanoseconds: 1651793

Without the cost of readability is there an adjustment that would improve performance?
I considered doing this with Streams but decided it wasn't necessary. Was I correct or would its use offer notable enhancement?


texts:
Using Rails 3.2. I have the following code:

# photo.rb
class Photo < ActiveRecord::Base
  after_create :associate_current_user
  after_save :increase_user_photos_count
  after_destroy :decrease_user_photos_count

  private

  def associate_current_user
    current_user = UserSession.find.user
    self.user_id = current_user.id
  end

  def increase_user_photos_count
    current_user = UserSession.find.user
    User.increment_counter(:photos_count, current_user.id)
  end

  def decrease_user_photos_count
    current_user = UserSession.find.user
    User.decrement_counter(:photos_count, current_user.id)
  end
end

Before a new record is created, it searches for the current_user. This is alright if it's just 1 new record at a time. But if there are 100 records to be created, it's gonna search for the same current_user 100 times. There is definitely performance issue.

How should I refactor this so that the app takes the first query result and reuse it for the next 99 times?
After refactoring, does this affect other users who are also uploading their photos using their accounts?

Note: For some reasons, I can't use the counter_cache.


texts: Generic repository with UoW and simple injector

texts:
I'm implementing a generic repository + UoW pattern with EF6 and simple injector. I feel there is room for improvements. Please let me know if I left out some relevant code, I tried to keep it breif.

Do you see any need for the unit of work to keep track of the repositories (in its _repositories field)? As you can see I'm currently not using it.

Another important thing here is that I want one EF context, LGTContext, per web request. But as far as I understand, it would be the case due to the Lifestyle.Scoped registration lifestyle.

Any other thoughts?

Generic repository:

public abstract class DatabaseRepository<T> : IRepository<T> where T : BaseEntity
{
    protected readonly DbSet<T> DbSet;
    protected readonly LGTContext Context;

    protected DatabaseRepository(IUnitOfWork unitOfWork, LGTContext context)
    {
        Context = context;
        DbSet = Context.Set<T>();

        unitOfWork.Register(this);
    }

    public Task<PagedResult<T>> Find(Expression<Func<T, bool>> predicate, int pageNumber, int pageSize)
    {
        throw new NotImplementedException();
    }

    public virtual async Task<IEnumerable<T>> Find(Expression<Func<T, bool>> predicate)
    {
        return await DbSet.Where(predicate).ToListAsync();
    }

    public virtual async Task<IEnumerable<T>> GetAll()
    {
        return await DbSet.ToListAsync();
    }

    public virtual async Task<T> GetSingle(object id)
    {
        return await DbSet.FindAsync(id);
    }

    public virtual void Add(T entity)
    {
        DbSet.Add(entity);
    }

    public virtual void Delete(T entity)
    {
        if (Context.Entry(entity).State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }
        DbSet.Remove(entity);
    }

    public virtual void Edit(T entity)
    {
        DbSet.Attach(entity);
        Context.Entry(entity).State = EntityState.Modified;
    }
}

Unit of work:

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private readonly Dictionary<Type, IRepository> _repositories = new Dictionary<Type, IRepository>();
    private readonly LGTContext _context;
    private bool _disposed;

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

    public async Task CommitAsync()
    {
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            // todo: handle validation errors...
            throw;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

    public void Register(IRepository repository)
    {
        _repositories.Add(repository.GetType(), repository);
    }
}

Simple injector registration:

container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
container.Register(typeof(IRepository<>),
                        new[] { typeof(DatabaseRepository<>).Assembly }, Lifestyle.Scoped);
container.Register<LGTContext>(Lifestyle.Scoped);

Usage psuedo code:

public SomeController(IUnitOfWork uow, IRepository<SomeEntity> repo)
{
    var entities = await repo.GetAll();
    // modify some entities...
    await uow.CommitAsync();
}


texts:
I have just learned classes and was practicing some examples from the textbook when I came to a screeching halt.

Here's the program I have written, which is complete but not optimal.  What this program does is that it inputs information about the company and then lets you display the data or search for a specific set of data.

This is a self-learning exercise, not homework and not for work either.

#include<iostream>
#include<cstring>
#include <conio.h>
using namespace std;

class company
{
    public:
    char companyname[20],companytype[10],companycode[5];
    int yearlyturnover;

    void displaydata()
    {
        cout<<companyname[20];
        cout<<companytype[10];
        cout<<companycode[5];
        cout<<yearlyturnover;
    }

};

int main()
{
 int count,num,option;

cout<<"How many companies do you want to input?:";
    cin>>num;

for(count=0;count<num;count++)
{
    company com1[count];
    cout<<"\nEnter the name of the company:";
        cin.getline(com1[count].companyname,20);
    cout<<"\nEnter the code of the company";
        cin.getline(com1[count].companycode,5);
    cout<<"\nEnter the Type of company: Public Ltd. or Private Ltd.";
        cin.getline(com1[count].companytype,10);
    cout<<"\nInput the yearly turnover of the company:";
        cin>>com1[count].yearlyturnover;
}

cout<<"\nPress 1 to display the data:";
cout<<"\nPress 2 to search for a company";
    cin>>option;
switch(option)
{

case 1: for(count=0;count<num;count++)
            {
            company com1[count];
            com1[count].displaydata();
            }
        break;

case 2: for(count=0;count<num;count++)
        {
            char input[10];
            company com1[count];
        cout<<"\nPlease enter the company type:";
            cin.getline(input,10);
        if(strcmp(input,com1[count].companytype)==0)
        {
            com1[count].displaydata();
        }

        }
        break;

default:cout<<"\nError: terminating program...";
};

 getch();
}