texts: Loading autocomplete text view adapter dynamically using async task in Android

texts:
I am working on an app in which I need to get destination list from server and set it in autocomplete text view. I am using text watcher and on its onTextChanged event I am fetching destinations data using async task. My problem is I am not sure that am I doing it in a right way. Please review my code below

FragmentHotels.java

public class FragmentHotels extends Fragment implements TextWatcher {

    final Handler mHandler=new Handler();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public FragmentHotels() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_hotels, container, false);

        etDestination = (AutoCompleteTextView) rootView.findViewById(R.id.et_destination);

        etDestination.addTextChangedListener(this);

        return rootView;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.i(TAG, "TEXT CHANGED TO: " + s.toString());
        if(!TextUtils.isEmpty(s.toString())) {
            getDestinationsAsync(s.toString());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void getDestinationsAsync(final String term){
        new AsyncTask<Void,Void,Void>(){

            final String t=term;

            final Map<String,String> postParams=new HashMap<>();

            @Override
            protected Void doInBackground(Void... params) {
                Log.i(TAG,"do in background in getDestinationAsync");
                postParams.put("term",t);
                new PostHandler(TAG,2,2000).doPostRequest("http://www.bhagwatiholidays.com/admin/webservice/destination_name.php",
                        postParams,
                        new PostHandler.ResponseCallback() {
                            @Override
                            public void response(int status, String response) {
                                Log.i(TAG,"GOT RESPONSE SUCCESSFULLY");
                                try {
                                    Log.i(TAG,"PARSING JSON");
                                    JSONArray array = new JSONArray(response);
                                    Log.i(TAG,"JSON ARRAY SIZE: "+array.length());
                                    final String[] destinations=new String[array.length()];
                                    for(int i=0;i<array.length();i++){
                                        Log.i(TAG,"LABEL: "+array.getJSONObject(i).getString("label"));
                                        destinations[i]=array.getJSONObject(i).getString("label");
                                    }
                                    Log.i(TAG, "SETTING ADAPTER NOW");
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            FragmentHotels.this.etDestination.setAdapter(new ArrayAdapter<String>(FragmentHotels.this.getActivity(),
                                                    android.R.layout.simple_list_item_1, destinations));
                                        }
                                    });

                                }
                                catch (JSONException e){
                                    e.printStackTrace();
                                }
                            }
                        });
                return null;
            }
        }.execute();
    }

}


texts: Find first non-repetitive char in a string

texts:
I just had an interview for the C#.NET developer position and I was asked to find the first non repetitive char in a given string without using any library functions but just the basic constructs of the language such as fors and ifs.

I presented this solution considering the quick time constraint. I request evaluation of the solution of how truly it serves the question.

public static char findFirstNonRepetitiveChar(string input)
{
    char c = '0';

    for (int i = 0; i < input.Length; i++)
    {
        bool isdistinct = true;
        for (int j = 0; j < input.Length; j++)
        {
            if (input[i] == input[j] && i!=j)
            {
                isdistinct = false;
                break;
            }
        }
        if (isdistinct)
        {
            c = input[i];
            break;
        }
    }
    return c;
}


texts: Finding answers where happy customers commented "thanks"

texts:
To find answers where users expressed their gratitude (by mentioning "thank" in comments),
I put together this SEDE query (latest):

DECLARE @username AS NVARCHAR(60) = ##DisplayName:string? ##;
DECLARE @userId AS INT = ##UserId:int?-1##;

-- SpecialThanks: Special thanks only "Enter 1 for YES, 0 for NO"
DECLARE @SpecialThanks AS INT = ##SpecialThanks:int?0##;

WITH Answers AS (
  SELECT * FROM Posts WHERE PostTypeId = 2
)

SELECT TOP ##Limit:int?100##
  a.Id AS [Post Link],
  c.Id AS [Comment Link],
  c.Text,
  c.CreationDate
FROM Answers a
  INNER JOIN Users u ON a.OwnerUserId = u.Id
  INNER JOIN Comments c ON a.Id = c.PostId AND c.UserId != u.Id
WHERE
  (@username = '' OR u.DisplayName = @username)
  AND (@userId = -1 OR u.Id = @userId)
  AND LOWER(c.Text) LIKE '%thank%'
  AND (
    @SpecialThanks <= 0 OR (
      LOWER(c.Text) LIKE '%excellent%'
      OR LOWER(c.Text) LIKE '%awesome%'
      OR LOWER(c.Text) LIKE '%awesum%'
      OR LOWER(c.Text) LIKE '%awsum%'
      OR LOWER(c.Text) LIKE '%wonderful%'
      OR LOWER(c.Text) LIKE '%fantastic%'
      OR LOWER(c.Text) LIKE '%amazing%'
      OR LOWER(c.Text) LIKE '%great%'
      OR LOWER(c.Text) LIKE '%best%'
      OR LOWER(c.Text) LIKE '%impressive%'
      OR LOWER(c.Text) LIKE '%master%'
      OR LOWER(c.Text) LIKE '%guru%'
      OR LOWER(c.Text) LIKE '%wizard%'
      OR LOWER(c.Text) LIKE '%ninja%'
      OR LOWER(c.Text) LIKE '%grateful%'
      OR LOWER(c.Text) LIKE '%appreciat%'
      OR LOWER(c.Text) LIKE '%by far%'
      OR LOWER(c.Text) LIKE '%!!!%'
    )
  )
ORDER BY c.CreationDate DESC

What do you think? Any improvement ideas?

Mainly I'm wondering if there's a way to eliminate all those duplicated LOWER(c.Text)


texts:
I have a piece of code that get errors from form and display to view:

$errors = $form->getMessages();
$msg = '';
foreach ($errors as $error)
{
    foreach ($error as $err)
    {
        $msg .= $err . '<br/>';
    }
}
$this->view->error_message = $msg;

It look so ugly, but now I don't have any ideas to improve it. Thank for help.


texts: Sampling and Reconstructing a signal in Julia

texts:
I am a newcomer to the Julia world, so I started trying to implement a very simple program:

Sample a signal
Reconstruct it (various ways, just rectangular for now)
Plot it

Everything is fine and 'working' properly, but coming from a OOP (java) and functional (python) background, I'm thinking that the following snippet can be improved to be in a more julia-ish style:

(required packages: DSP, Plots, PyPlot)
# parameters
Ts = 0.02;
n = 0:(100 / Ts);

f0 = 5;

dt = 0.001;
t = 0:dt:10;

# sampling
x = sin.(2 * pi * f0 * Ts * n); # target signal to sample

# reconstruct (need improvement)
rectangular_reconstr(i) = x[floor(Int, i * (length(n) / length(t)) + 1)]
x_recon_sinc = [rectangular_reconstr(e) for e in 1:(length(t)-1)]

I'm concerned about this list comprehension. Essentially, create a function that maps indices from (sampled) -> reconstructed is the whole idea here. If you were to do other kinds of interpolation (via spline, triangular or whatever), you can even access all the elements of the sampled array.

Is there any better alternative than this loop-comprehension version?


texts: Optimizing display of various famous quotes

texts:
If it is possible, I'd like to be able to mash all of my arrays into one array, but still have the same functionality within my function (pick quote, pick creator, set padding).

Pastebin

var quotes = [
    /*48px*/"The true sign of intelligence is not knowledge but imagination.",
    /*48px*/"A people without the knowledge of their past history, origin and culture is like a tree without roots.",
    /*48px*/"Real knowledge is to know the extent of one's ignorance.",
    /*48px*/"Ignorance is the curse of God; knowledge is the wing wherewith we fly to heaven.",
    /*48px*/"Human behavior flows from three main sources: desire, emotion, and knowledge.",
    /*80px*/"If money is your hope for independence you will never have it. The only real security that a man will have in this world is a reserve of knowledge, experience, and ability.",
    /*80px*/"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family.",
    /*48px*/"Knowledge has to be improved, challenged, and increased constantly, or it vanishes.",
    /*112px*/"I'm hungry for knowledge. The whole thing is to learn every day, to get brighter and brighter. That's what this world is about. You look at someone like Gandhi, and he glowed. Martin Luther King glowed. Muhammad Ali glows. I think that's from being bright all the time, and trying to be brighter.",
    /*112px*/"Wisdom is the right use of knowledge. To know is not to be wise. Many men know a great deal, and are all the greater fools for it. There is no fool so great a fool as a knowing fool. But to know how to use knowledge is to have wisdom.",
    /*48px*/"To know, is to know that you know nothing. That is the meaning of true knowledge.",
    /*48px*/"The best advice I ever got was that knowledge is power and to keep reading.",
    /*48px*/"He who knows nothing is closer to the truth than he whose mind is filled with falsehoods and errors.",
    /*48px*/"To know what you know and what you do not know, that is true knowledge.",
    /*80px*/"I was bold in the pursuit of knowledge, never fearing to follow truth and reason to whatever results they led, and bearding every authority which stood in their way."
];
var creators = [
    "Albert Einstein",
    "Marcus Garvey",
    "Confucius",
    "William Shakespeare",
    "Plato",
    "Henry Ford",
    "Kofi Annan",
    "Peter Drucker",
    "Jay-Z",
    "Charles Spurgeon",
    "Socrates",
    "David Bailey",
    "Thomas Jefferson",
    "Confucius",
    "Thomas Jefferson"
];
var margins = [
    "48",
    "48",
    "48",
    "48",
    "48",
    "80",
    "80",
    "48",
    "112",
    "112",
    "48",
    "48",
    "48",
    "48",
    "80"
];
function quote() {
    var rand = Math.floor(Math.random() * quotes.length);
    $("p.quote").fadeOut(300).delay(1000).fadeIn(300);
    $("p.creator").fadeOut(300).delay(1000).fadeIn(300);
    $("p.quote").text(quotes[rand]);
    $("p.creator").text(creators[rand]);
    var marginTop = ($(".quotes .quotes-container").height() - margins[rand]) / 2 + "px";
    $(".quotes .quotes-container .content").attr("style","padding-top:" + marginTop);
};


texts:
I was asked this question in an interview:

  Given a string s consisting of 0, 1 and ?. The question mark can
  be either 0 or 1. Find all possible combinations for the string.

I came up with below code but I wanted to know whether it is the best way to solve the problem?

  public static void main(String[] args) {
    List<String> output = new ArrayList<>();
    addCombinations("0?1?", 0, output);
    System.out.println(output);
  }

  private static void addCombinations(String input, int index, List<String> output) {
    for (int i = index; i < input.length(); ++i) {
      if (input.charAt(i) == '?') {
        addCombinations(input.substring(0, i) + "0" + input.substring(i + 1), i + 1, output);
        addCombinations(input.substring(0, i) + "1" + input.substring(i + 1), i + 1, output);
        return;
      }
    }
    output.add(input);
  }


texts: Conditionally display an Action depending on whether or not a player is connected

texts:
Is there a nicer way to write the maybeWhen portion of displayConnectionAction ? I want to conditionally display an Action depending on whether or not the player is connected.

This bit of code is lifted from a wider system where there are multiple calls like displayConnectionAction (conditional actions built up by a Reader GameState), so I am not after any feedback around things like the Reader being overkill etc, more the implementation of the function displayConnectionAction, the actual code has 12+ functions like this, all generating Maybe Actions based off various bits of logic.

data Action = Action
  { actionLabel :: Text
  , actionUrl :: Text
  , actionPlayer :: Int
  }

data GameState = GameState
  { currentPlayer :: Player
  }

data Player = Player
  { playerId :: Int
  , playerName :: Text
  , playerConnected :: Bool
  }

displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = maybeWhen not <$> isConnected <*> action
  where
    action =
      Just . Action "Connect" "/connect" <$> currentPlayerId

    isConnected =
      asks (playerConnected . currentPlayer)

    currentPlayerId =
      asks (playerId . currentPlayer)

maybeWhen :: (a -> Bool) -> a -> Maybe b -> Maybe b
maybeWhen f a mb =
  if f a then mb else Nothing


texts: C++ Read/write (shared) spinlock implementation

texts:
Here is my implementation of std compatible RWSpinLock using 2 atomics.

I think in cases when spinlock is free, it should take just 1 atomic write operation.

class RWSpinLock{
    std::atomic<int> readers_count{0};
    std::atomic<bool> write_now{false};
public:
    void lock() {
        while (!write_now.exchange(true, std::memory_order_acquire)){
            std::this_thread::yield();
        }

        // wait for readers to exit
        while (readers_count != 0 ){
            std::this_thread::yield();
        }
    }
    void unlock() {
        write_now.store(false, std::memory_order_release);
    }

    void lock_shared() {
        // unique_lock have priority
        while(true) {
            while (write_now) {     // wait for unlock
                std::this_thread::yield();
            }

            readers_count.fetch_add(1, std::memory_order_acquire);

            if (write_now){
                // locked while transaction? Fallback. Go another round
                readers_count.fetch_sub(1, std::memory_order_release);
            } else {
                // all ok
                return;
            }
        }
    }
    void unlock_shared() {
        readers_count.fetch_sub(1, std::memory_order_release);
    }
};

On unique_lock wait for write_now flag, then wait for readers_count.

On shared_lock wait for write_now flag, then increase readers_count. If during incrementation write_now flag becomes true, decrease readers_count and wait again for write_now (this should be relativley rare case).

P.S. I'm not sure though, about memory_order, and overall correctness (but seems fine to me).


texts:
I am attempting to filter JSON into an array of arrays containing a property value based on the product.  The form is as follows:

[{
    "product": "T0013415_",
    "ordered": 48,
    "shipped": 48,
    "year": 2016,
    "month": 6
}, {
    "product": "T0054113_",
    "ordered": 379,
    "shipped": 379,
    "year": 2016,
    "month": 7
},......]

I am first filtering this JSON into an array of arrays of objects seperated by product with:

var firstPassArray = [];
for(var key in _self.productList)
{
    firstPassArray.push(_self.turnoverMonthlyData.filter(function (el) {
        return el.product == _self.productList[key].product;
    }))
}

The result being an array of arrays of objects:

[[Object, Object, ...],[Object, Object, ...],[Object, Object, ...],...]

I am then getting the actual property values into arrays with

var finalPassArray = [];
for (var key2 in firstPassArray)
{
    var insideArray = [];
    for (var index = 0; index < firstPassArray[key2].length ; index++)
    {
        insideArray.push(firstPassArray[key2][index].ordered);
    }
    finalPassArray.push(insideArray);
}

So that my final results looks like

[[48,264,24,67,54],[4567,511,24,18,5],[4,57,6,11,544],[78,98,77,88,77],[454,54,4,6,8]]

Ignoring bad variable names, is there a better way to do this? Like returning a object property value in the filter() method rather than an object?


texts:
I've found a few places where control updates take longer than the redraw cycle.

I started off surrounding them with Suspend and ResumeLayout:

container.SuspendLayout();
updateControls();
container.ResumeLayout(true);

After doing that a few times, I realized it could be refactored into a context:

/// <summary>
/// Context manager to suspend and resume layout engine while performing
/// updates that take longer than a refresh cycle
/// </summary>
/// <example>using (new SuspendLayoutContext(container)
///     DoSlowUpdate(container.Controls);</example>
class SuspendLayoutContext : IDisposable
{
    private readonly Control _control;
    private readonly bool _performLayoutAfter;

    /// <summary>
    /// Constructs the context manager to suspend and resume layout.
    /// </summary>
    /// <param name="container"></param>
    /// <param name="performLayout"></param>
    public SuspendLayoutContext(Control container, bool performLayoutAfter=true)
    {
        _control = container;
        _performLayoutAfter = performLayoutAfter;
        _control.SuspendLayout();
    }

    /// <summary>Calls ResumeLayout on the container.</summary>
    /// <remarks>If you call this manually, you are probably using this class wrong.</remarks>
    public void Dispose()
    {
        _control.ResumeLayout(_performLayoutAfter);
    }
}

Then, the above code would look like

using (new SuspendLayoutContext(container))
{
    updateControls();
}

I then decided I didn't like having to call the constructor every time, so I created an extension method (/// comments elided for brevity):

static class ControlExtensions
{
    public static SuspendLayoutContext SuspendLayoutContext(this Control container, bool performLayoutAfter=true)
    {
        return new SuspendLayoutContext(container, performLayoutAfter);
    }
}

The example then looks like

using (container.SuspendLayoutContext())
{
    updateControls();
}

Questions

Is there any reason not to use an IDisposable context here?  I'm more familiar with python, where I wouldn't hesitate to create new context managers - but the method name Dispose() raises red flags. (In python, it's __exit__.)
I debated between the extension method on Control and a static method on SuspendLayoutContext:

public static SuspendLayoutContext For(Control container, bool performLayoutAfter=true)
{
    return new SuspendLayoutContext(container, performLayoutAfter)
}

While I'm a big fan of fluent interfaces, the extension method felt cleaner.  What alternatives might be better?
I always miss something when I do this, what is it this time?


texts: Sorting object with null values underscore sortBy

texts:
I'm sorting my object by its property ActivityOrder, which will sometimes contain null values if the user has not explicitly stated an order which an activity should appear.

Since null will always appear top most in the sort (unless reversed), it messed up my sort.

The solution I came up with was to sort by the id if activityOrder was null since the ID will always be greater than the activityOrder within our application and then there is some logical order to the sort too.

var data = [{
        "id": 150,
        "name": "Andrew",
        "activityOrder": null
}, {
        "id": 151,
        "name": "Andrew",
        "activityOrder": null
}, {
        "id": 152,
        "name": "Andrew",
        "activityOrder": 1
}];

data = _.sortBy(data, function(o) {
        if (o.activityOrder === null)
            return o.id;
        return o.activityOrder
});

_.each(data, function(x) {
        $('#cnt').append("
" + x.Name + " - Order " + x.activityOrder + "
")
})

I had also tried amending the value if the activityOrder null to 99999999999 and resetting it back to null after doing whatever. I didn't like the idea of this one.

data = _.sortBy(data, function(o) {
        if (o.activityOrder === null)
            o.activityOrder = 99999999999;
        return o.activityOrder
});

//Do whatever

//Reset Activity Order back
_.each(d, function(o) {
        if (o.activityOrder === 99999999999) {
                o.activityOrder = null;
        }
});

How best would you sort an object array by a property which contains null values?


texts:
I would welcome feedback about this script to automate the building of docker images from a set of dockerfiles.

The dockerfiles are provided to the script via stdin.  The images are saved to the first (and only) argument of this script.  In normal use either one or two specific images are removed manually from the machine so that they get rebuilt or all images are removed (using a different script) for them all to be rebuilt.

Example invocation:

$ find dockerfiles -mindepth 1 -maxdepth 1 -type d | dockerfiles-build images

Actual output:

Reading dockerfile directories from std input.  Building can take a long time...
Building golang-build:2017-03-05T22-28GMT from dockerfiles/golang-build
Sending build context to Docker daemon 4.608 kB
<Lots of docker build process text>
Successfully built cc287d22a661
Saving golang-build:2017-03-05T22-28GMT.save.xz from cc287d22a661
Use images/run-golang-build to use the image
Reading next dockerfile...
$

My code (MIT license):

#!/bin/bash

# Script to build and save specific docker containers to the specified directory with the paths to the dockerfile directory arriving on the standard input

set -eu -o pipefail

if [ -z "${1-}" ] || ! [ -d "${1-}" ]; then
    echo "Correct invocation is: $(basename "$0") _out-directory_ <_dockerfile-directory-paths_" >&2
    exit 1
fi

outdir="${1-out}"
timestamp=$(date '+%Y-%m-%dT%H-%M%Z')

echo "Reading dockerfile directories from std input.  Building can take a long time..." >&2

while read dockerfilepath; do
    # Filter out empty input
    if [ -n "$dockerfilepath" ]; then

        # Process the path name
        name="$(basename $(readlink -f "$dockerfilepath"))"

        # Check that image does not already exist
        if ! docker images | grep "$name"; then

            # Get docker to build the image
            echo "Building $name:$timestamp from $dockerfilepath" >&2
            docker build -t "$name":$timestamp "$dockerfilepath"

            # Output the image (but only one if there are duplicates with different tags)
            image="$(docker images | grep "$name" | awk '{print $3}' | sort -u)"
            if [ "$(echo "$image" | wc -w)" -ne "1" ]; then
                echo "Multiple images detected for $name; aborting" >&2
                exit 1
            fi
            echo "Saving $name:$timestamp.save.xz from $image" >&2
            docker save "$image" | xz -z9 > "$outdir/$name:$timestamp.save.xz"

            # output the image specific run script, enforcing a naming convention
            cp "$dockerfilepath"/run* "$outdir/run-$name"
            echo "Use $outdir/run-$name to use the image" >&2
        else
            echo "A $name image already exists; remove it to build it again" >&2
        fi
    else
        echo "Skipping empty path" >&2
    fi
    echo "Reading next dockerfile..." >&2
done

Points of particular interest:

Are there any unsafe filepath manipulations
Are variables treated safely
Could any names break the script
Anything that could lead to the script being unreliable for unsupervised operation
Any general optimisations that you could suggest


texts: Calculate odds of winning (UK) Lottery jackpot

texts:
I am interested in calculating odds of winning UK Lottery. The format is that 6 numbers from 1-59 are drawn. I am interested only (at this stage) in the odds of winning the jackpot (matching six balls). As an aside, I'm interested in the odds for a total balls count of 49, and 59, to see the change in chance of winning.

The mathematical formula for calculating the odds is (where 49 is total balls, 6 is number drawn:

\$\text{Odds of winning} = \dfrac{49!}{(6!*(49-6)!}\$

The main method of my code is to collect input from the user on parameters of the draw.

I have a class called DrawInfo to store information about the draw. I have a simple method to return the Factorial of a number.

I have a method to calculate the odds of winning the jackpot. This is currently all in the one class, as a small, simple app. I do appreciate that DrawInfo could live in its own class.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the total number of balls in the draw: ");
            int totalBalls = int.Parse(Console.ReadLine());

            Console.WriteLine("enter the number of balls drawn: ");
            int ballsDrawn = int.Parse(Console.ReadLine());

            DrawInfo di = new DrawInfo(totalBalls, ballsDrawn);

            int totalWinOdds = FindJackpotWinningOdds(di);
            Console.WriteLine(String.Format("the odds are 1/{0:n0}", totalWinOdds));
            Console.ReadLine();
        }

        static int FindJackpotWinningOdds(DrawInfo di)
        {
            BigInteger totalBallsFactorialSum = Factorial(di.TotalBalls);
            BigInteger ballsDrawnFactorialSum = Factorial(di.BallsDrawn);

            BigInteger JackpotWinningOdds = 0;
            JackpotWinningOdds = totalBallsFactorialSum / ((ballsDrawnFactorialSum * Factorial((di.TotalBalls - di.BallsDrawn))));
            return (int)JackpotWinningOdds;
        }

        static BigInteger Factorial(BigInteger i)
        {
            if (i <= 1)
            {
                return 1;
            }
            return i * Factorial(i - 1);
        }
    }

    public class DrawInfo
    {
        public int TotalBalls { get; set; }
        public int BallsDrawn { get; set; }

        public DrawInfo(int totalBalls, int ballsDrawn)
        {
            this.TotalBalls = totalBalls;
            this.BallsDrawn = ballsDrawn;
        }
    }


texts:
I have the following which searches my graph to see if a vertex is reachable from the first vertex, which everything should be connected to. I do this to ensure there are no disconnected parts.

Unfortunately it is very slow.

Is there something I could do or store to optimize this?

I want to learn about graphs and generated cities so Im not using a real graph library.

private void removeDisconnectedSquares()
{
    for(int i = 0; i < getNumXNodes(); ++i)
    {
        for(int j = 0; j < getNumYNodes(); ++j)
        {
            //removeDisconnectedSquare(i, j);
            visitedNodes.clear();
            if(!isNodeReachableFrom(getNodeAt(i, j), getNodeAt(0, 0)))
            {
                removeVertex(i, j);
            }
        }
    }
}

private boolean isNodeReachableFrom(GraphNode node, GraphNode target)
{
    if(node == null)
    {
        return false;
    }

    if(visitedNodes.contains(node))
    {
        return false;
    }
    else
    {
        visitedNodes.add(node);
    }

    if(node == target)
    {
        return true;
    }

    if(node.contains(target))
    {
        return true;
    }

    for(int i = 0; i < node.getSize(); ++i)
    {
        if(isNodeReachableFrom(node.at(i), target))
        {
            return true;
        }
    }

    return false;
}


texts: Program to take a number from 0 to 9 as input

texts:
I'm trying to make a function that requests a number from 0 to 9 to the user and that is robust. I've been looking at code to guide me and most fail to find any of these situations, usually due to the use of cin:

If the user enters spaces before or after the number, the entry is valid
If you end the input (Ctrl+Z in Windows; Ctrl+D on most Unix) an infinite cycle is produced
If the user typed 2ff the entry is valid
The entry is waiting for us to type something because of a line jump

I've made the following code and I don't think it fails with its purpose. I would like to know your opinion and if you believe in any case where it could fail or if I can improve it.
#include <iostream>
#include <string>

using namespace std;

int input_number()
{

    string data = "";
    while (true)
    {

        cout << "Input: ";
        if (!getline(cin, data))
        {
            return -1;
        }
        if (data.length() != 1 || isspace(data[0]))
        {
            cerr << "Invalid number, try again!" << endl;
            continue;
        }
        try
        {
            return stoi(data);
        }
        catch (const exception &e)
        {
            cerr << "Invalid number, try again!" << endl;
            cin.clear();
        }
    }
}

int main()
{

    cout << input_number() << endl;
}


texts: Java solution to check if a Sudoku solution is valid

texts:
Here's my solution to checking if a Sudoku board is valid. The algorithm checks the following,

Rows add up to 45
Columns add up to 45
Rows have no duplicates
Cols have no duplicates
Every 3X3 sub-grid has no duplicate

Invite comments.

public class Checker {
    private int size;
    private int[][] board;

    public Checker(int size){
        this.size = size;
        board = new int[size][size];
    }

    private boolean rowCheck(){
        int sum = (size*(size+1))/2;
        int count = 0;
        for (int i = 0; i <size ; i++) {
            for (int j = 0; j < size ; j++) {
                count += board[i][j];
            }
            if(count != sum) return false;
            count = 0;
        }
        return true;
    }

    private boolean columnCheck(){
        int sum =0;
        int count = 0;
        for (int i = 0; i <size ; i++) {
            for (int j = 0; j <size ; j++) {
                count += board[j][i];
            }
            if(count != sum) return false;
            count = 0;
        }
        return true;
    }

    private boolean checkRowDuplicates(){
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i <size ; i++) {
            for (int j = 0; j < size ; j++) {
               set.add(board[i][j]);
            }
            if(set.size() != size) return false;
            set = null;

        }
        return true;
    }
    private boolean checkColumnDuplicates(){
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i <size ; i++) {
            for (int j = 0; j < size ; j++) {
                set.add(board[j][i]);
            }
            if(set.size() != size) return false;
            set = null;

        }
        return true;
    }

    private boolean checkSubBoardDuplicates(){

        return (subBoardTraversal(0,3,0,3) && subBoardTraversal(0,3,3,6) && subBoardTraversal(0,3,6,9) && subBoardTraversal(3,6,0,3)
                && subBoardTraversal(3,6,3,6) && subBoardTraversal(3,6,6,9) && subBoardTraversal(6,9,0,3) && subBoardTraversal(6,9,3,6)
                && subBoardTraversal(6,9,6,9));

    }
    private boolean subBoardTraversal(int rowStart, int rowFinish, int colStart, int colFinish){
        HashSet<Integer> set = new HashSet<>();
        for (int i = rowStart; i < rowFinish  ; i++) {
            for (int j =colStart ; j < colFinish; j++) {
                set.add(board[i][j]);
            }
            if(set.size() != 9) return false;

        }
        return true;
    }
    public boolean isValid(){

        return(rowCheck() && columnCheck() && checkRowDuplicates() && checkColumnDuplicates() && checkSubBoardDuplicates());

    }

    public void trace(){
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }
}


texts:
I was playing the game Set online, and thought it would be a good exercise to write an F# script to find all of the sets for me.

The rules of set are as follows:
A SET is 3 cards for which each feature is either common across all 3 cards or is different on each card. The object is to find all the SETs among the cards.

I started learning F# four days ago, so what I'm looking for are obvious/easy/"no duh" improvements. I've started at a low bar of just writing a function to compare a group of three cards, and tell you if those three cards form a set. You can see my first attempt below. It feels a bit clunky, like I'm not really making use of all that F# has to offer.

// Create a record type to represent each card
type Card =
    { Color: string
      Shape: string
      Pattern: string
      Number: int
    }

// Create some functions for comparing elements of a collection
let allEqual l = l |> Seq.pairwise |> Seq.forall (fun (x, y) -> x = y)
let allDifferent l = (l |> Seq.distinct |> Seq.length) = (Seq.length l)

// Combine them
let isSet l = (allEqual l) || (allDifferent l)

// The meat of this script
let compare card1 card2 card3 =
    // Put the cards together for easy iteration
    let cardList = [card1; card2; card3]

    // Check each field of the record to see if it makes a set
    let colorSet   = cardList |> List.map (fun c -> c.Color  ) |> isSet
    let shapeSet   = cardList |> List.map (fun c -> c.Shape  ) |> isSet
    let patternSet = cardList |> List.map (fun c -> c.Pattern) |> isSet
    let numsSet    = cardList |> List.map (fun c -> c.Number ) |> isSet

    // Check that they all make a set
    colorSet && shapeSet && patternSet && numsSet

// Test the functions out
let c1 = {Color = "blue"; Shape = "oval"; Pattern = "stripes"; Number = 3}
let c2 = {Color = "red";  Shape = "diamond"; Pattern = "solid"; Number = 2}
let c3 = {Color = "green";  Shape = "squiggle"; Pattern = "empty"; Number = 2}

let areCardsSet = compare c1 c2 c3
printfn "The cards c1, c2, and c3 are a set? %b" areCardsSet


texts:
Does the implementation look correct? Did I miss something major/minor?

class CircularBuffer

  class BufferEmptyException < StandardError;  end;
  class BufferFullException < StandardError;   end;

  def initialize(size)
    @size = size
    @buffer = []
  end

  def write(data)
    raise CircularBuffer::BufferFullException if @buffer.size >= @size
    @buffer << data if data
  end

  def write!(data)
    if data
      @buffer << data
      @buffer.shift
    end
  end

  def clear
    @buffer = []
  end

  def read
    data = @buffer.shift
    raise CircularBuffer::BufferEmptyException unless data
    data
  end

end


texts: Script scraper for outputting variables and functions to a text file

texts:
I've been programming with Python 2.7 for about six months now and if possible, I'd like some critique to see what I might have done better or what I might be doing wrong.

My objective was to make a script scraper that finds variables and functions, outputting them to a text file along with their line number. It also organizes the output based on type and string length for readability. It works as intended, but I'd like to know if/how I could have wrote it better, cleaner.

import re

def change_line():
        parse_next['line_count'] += 1

def make_readable(list):
        fix_order = {}
        for item in list:
                fix_order[len(item)] = item
        return sort_this(fix_order)

def sort_this(dict):
        fixed = dict.keys()
        fixed.sort()
        newly_ordered = []
        for number in fixed:
                newly_ordered.append(dict[number])
        return newly_ordered

def parse_match(match):
        if '\n' in match:
                parse_next[match]()
        elif 'def' in match:
                parse_next[match] = parse_next['line_count']
                funcs.append(match)
        elif match:
                parse_next[match] = parse_next['line_count']
                varis.append(match)
        else:
                print 'error'

funcs = []
varis = []
txt_file = open('c:\\code\\test.txt', 'r')
output = open('c:\\code\\output.txt', 'w+')
found = re.findall(r'\n|def\s.+|.+ = .+', txt_file.read())

parse_next = {
        '\n': change_line,
        'line_count': 1,
}

for match in found:
        parse_match(match)

funcs = make_readable(funcs)
varis = make_readable(varis)
output.write('\t:Functions:\n\n')

for item in funcs:
        s_fix = item.replace('def ', '',)
        to_write = [s_fix, ' Line:', str(parse_next.get(item)), '\n']
        output.writelines(to_write)

output.write('\n'*2)
output.write('\t:Variables:\n\n')

for item in varis:
        to_write = [item.strip(),' Line:', str(parse_next.get(item)), '\n']
        output.writelines(to_write)

output.close()
txt_file.close()

To run it, you'll need to edit this filepath:

txt_file = open('c:\code\test.txt', 'r')

with code from a script of your choice.

Be harsh if necessary, I'd really like to get better.


texts: Replace tabs in input and variable vs symbolic parameter

texts:
I am learning C and this is an exercise from The C Programmnig Languange by Brian and Ritchie.

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

Here's my try, and I've made \$n\$ a parameter. I would appreciate any feedback and explanation on symbolic parameter.

#include <stdio.h>

#define TABLENGTH 8

void detab(int n);

int main () {

  int c, noOfTabs;
  noOfTabs = 0;

  while ((c = getchar()) != EOF) {

    if (c == '\t') {
      ++noOfTabs;
    } else if (noOfTabs > 0) {
      detab(noOfTabs);
      noOfTabs = 0;
      putchar(c);
    }

  }

  return 0;
}

void detab (int n) {

  while (n > 0) {
    --n;
    int i;
    for (i = 0; i < TABLENGTH; ++i) {
      putchar(' ');
    }
  }

}


texts:
The following contains my little app that detects changes to the clipboard and displays them in the GUI. I did my best using my limited knowledge of Python, but I have a feeling that I can definitely improve the program. It works, but Python's CPU usage shoots up to 20% whenever I run the program - which is due to my use of multiple threads and infinite loops I'm sure.

#! python3

#GUI
import tkinter
#needed for the clipboard event detection
import time
import threading

#listener class that inherits from Thread
class ClipListener(threading.Thread):
    #overriding Thread constructor
    def __init__(self, pause = .5):
        #from documentation: If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
        super().__init__() #calls Thread class constructor first

        #initialize parameters
        self.pause = pause
        self.stopping = False

        #initialize event to communicate with main thread
        self.copyevent = threading.Event()

    #override run method
    def run(self):
        last_value =  tkinter.Tk().clipboard_get() #initialize last_value as

        #continue until self.stopping = true
        while not self.stopping:
            #grab clip_board value
            temp_value = tkinter.Tk().clipboard_get()
            #if last value is not equal to the temp_value, then (obviously) a change has occurred
            if temp_value != last_value:
                #set last value equal to current (temp) value and print
                last_value = temp_value
                print("set")
                #set the event if clipboard has changed
                self.copyevent.set()
            time.sleep(self.pause) #sleep for indicated amount of time (.5 by default)

    #override stop method to work with our paramter 'stopping'
    def stop(self):
        self.stopping = True

#GUI extends Frame, serving as main container for a root window
class GUI(tkinter.Frame):

    #constructor for GUI - intializes with a default height and width if none are given
    def __init__(self, master, ht=600, wt=800):

        #uses the parent class' constructor
        super().__init__(master, height=ht, width=wt)
        self.var = tkinter.StringVar()
        self.var.set("No copied text")
        self.pack_propagate(False) #window will use it's own width and height as parameters instead of child's dimensions
        self.pack()
        self.label = tkinter.Label(self, textvariable=self.var)
        self.label.pack()

    #method to update the label
    def update_label(self, newText):
        self.var.set(newText)
        self.label.pack()

def main():
    #good practice to have a variable to stop the loop
    running = True

    #GUI initialized
    root = tkinter.Tk()
    gui = GUI(root)

    #start thread containing Clipboard Listener
    listener = ClipListener(.100)
    listener.start()

    #loop to keep updating the program without blocking the clipboard checks (since mainloop() is blocking)
    while running:
        #update the gui
        root.update();
        #wait .1 seconds for event to be set to true
        event_set = listener.copyevent.wait(.100)
        #if true then update the label and reset event
        if event_set:
            gui.update_label(root.clipboard_get())
            listener.copyevent.clear()

#only run this program if it is being used as the main program file
if __name__ == "__main__":
    main()


texts:
Problem:
Find the longest sequence consisting only of 0's, and the longest sequence consisting only of 1's?
Solution:
import sys

longestSequenceForOne = None
startIndexForOne = None
longestSequenceForZero = None
startIndexForZero = None

def setLongestSequence(array, longestSequence, startIndex):
    global longestSequenceForOne
    global startIndexForOne
    global longestSequenceForZero
    global startIndexForZero

    if array[startIndex] == 1:
        if longestSequenceForOne == None or longestSequenceForOne < longestSequence:
            longestSequenceForOne = longestSequence
            startIndexForOne = startIndex
    elif array[startIndex] == 0:
        if longestSequenceForZero == None or longestSequenceForZero < longestSequence:
            longestSequenceForZero = longestSequence
            startIndexForZero = startIndex

def findLongestSequence(array, size):
    """
    Find the longest sequence of 0's and 1's
    """
    longestSequence = 1
    beginIndex = None
    index = 1
    startIndex = 0
    sameElementCount = 1

    while (index < size):
        if array[index] == array[index-1]:
            sameElementCount += 1
        elif sameElementCount > longestSequence:
            longestSequence = sameElementCount
            startIndex = index - sameElementCount
            sameElementCount = 1
            setLongestSequence(array, longestSequence, startIndex)
        else:
            sameElementCount = 1
        index += 1
    if sameElementCount > longestSequence:
        longestSequence = sameElementCount
        startIndex = index - sameElementCount
        setLongestSequence(array, longestSequence, startIndex)

if __name__ == '__main__':
    size = int(input())
    if size < 2 or size > 100:
        sys.exit()
    array = [int(x) for x in input().split() if x == '1' or '0']
    if len(array) != size:
        sys.exit()
    findLongestSequence(array, size)
    print(startIndexForZero, longestSequenceForZero)
    print(startIndexForOne, longestSequenceForOne)

Correctness
Input

12
0 1 0 1 1 1 0 1 0 0 0 0

Output

8 4
3 3

Input
17
1 1 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0

Output

9 4
0 2

Questions:

Does the code require better error handling?

Can this code get more pythonic?


texts: Computing the subtotal of all items on their property criteria: qty * price

texts:
I have an array which represent the item purchases of a customer, and computed the items subtotal in this logic:

function getSubtotal(arr) {
  let total = 0.00;
  arr.forEach(function(i) {
    total += (i.qty * i.price)
  });
  return total;  // 1274.21
}

And yes of course I get the correct result, but is there any efficient way to do this in JavaScript?

let data = [
  {
    name : 'Item 1', qty: 2, price: 15.50 // 31
  },
  {
    name : 'Item 2', qty: 17, price: 25.13 // 427.21
  },
  {
    name : 'Item 3', qty: 102, price: 8.00 // 816
  }
];

function getSubtotal(arr) {
  let total = 0.00;
  arr.forEach(function(i) {
    total += (i.qty * i.price)
  });
  return total; // 1274.21
}

document.write(getSubtotal(data));


texts: Ping Pong Pi - A Ping Pong score and serving manager

texts:
I have spent a few hours on this code, but think it could be improved a bit. It requires eSpeak to be installed to run the speech synthesis, but the voice can be toggled on or off using the togglevoice command. This was created for Python 2.7.3.

My major concerns are the fluctuations of the use of global to define global variables, the re-use of the variable n in functions and readability of the d array. It currently works fine on a Raspberry Pi running the latest version of Raspbian.

import os
def talk(n):
    if voice_mode == 1:
        os.system("espeak -ven+m3 '" + n + "' 2>/dev/null")
    else:
        print n

def print_score(n):
    if n == 0:
        other_n = 1
    else:
        other_n = 0
    if d[n][1] == 0:
        score1 = "love"
    else:
        score1 = str(d[n][1])
    if d[other_n][1] == 0:
        score2 = "love"
    else:
        score2 = str(d[other_n][1])
    talk(score1 + " " + score2)

def win(n):
    global first_server
    talk(d[n][0] + " wins the game")
    d[n][2] += 1
    d[0][1] = 0
    d[1][1] = 0
    deuce_mode = 0
    serve_turns = old_serve_turns
    if first_server == 0:
        first_server = 1
        current_server = 1
    else:
        first_server = 0
        current_server = 0
    if d[n][2] == match_points:
        talk(d[n][0] + " wins the match")
        d[0][2] = 0
        d[1][2] = 0

def add_score(n):
    global deuce_mode
    global current_server
    global serve_turns
    d[n][1] += 1
    if n == 0:
        other_n = 1
    else:
        other_n = 0
    if deuce_mode == 0:
        if d[0][1] == d[1][1] and d[0][1] == game_points - 1:
            deuce_mode = 1
            old_serve_turns = serve_turns
            serve_turns = 1
        if current_server == 0:
            print_score(0)
        else:
            print_score(1)
        if d[n][1] == game_points:
            win(n)
    else:
        if d[n][1] == d[other_n][1] + 2:
            if current_server == 0:
                print_score(0)
            else:
                print_score(1)
            win(n)
        else:
            if current_server == 0:
                print_score(0)
            else:
                print_score(1)
    if (d[0][1] + d[1][1]) % serve_turns == 0:
        if current_server == 0:
            current_server = 1
            talk(d[1][0] + " is serving next")
        else:
            current_server = 0
            talk(d[0][0] + " is serving next")

d = []
for i in xrange(2):
    d.append(["", 0, 0])
d[0][0] = "Player 1"
d[1][0] = "Player 2"
game_points = 11
match_points = 2
deuce_mode = 0
voice_mode = 1
serve_turns = 2
old_serve_turns = 2
current_server = 2
first_server = 0

talk("Ready to play")
while True:
    c = raw_input("Command: ").lower()
    if c == "z":
        if current_server != 2:
            add_score(0)
        else:
            talk(d[0][0] + " is serving first")
            current_server = 0
            first_server = 0
    elif c == "x":
        if current_server != 2:
            add_score(1)
        else:
            talk(d[1][0] + " is serving first")
            current_server = 1
            first_server = 1
    elif c == "1name":
        d[0][0] = raw_input("Player 1 name: ")
        talk("Welcome, " + d[0][0])
    elif c == "2name":
        d[1][0] = raw_input("Player 2 name: ")
        talk("Welcome, " + d[1][0])
    elif c == "gm":
        game_points = int(raw_input("Game points: "))
        match_points = int(raw_input("Match points: "))
    elif c == "s":
        serve_turns = int(raw_input("Serve turns: "))
    elif c == "togglevoice":
        if voice_mode == 0:
            voice_mode = 1
        else:
            voice_mode = 0
    elif c == "quit":
        quit()
    else:
        talk("Command not recognised")


texts:
I am making an IOT weather station based on a particle photon that sends data via webhook to one of my other projects. I am very new to c++ and programming in general.

What can I do better with my code? What can be optimised? And what are industry best practices that I can put into place?

Here's my code:

#include <Adafruit_DHT/Adafruit_DHT.h>

#define DHTPIN 2

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
dht.begin();
}

void loop() {

delay(2000);

//Variables
//DHT11 sensor floats
float h = dht.getHumidity();
float t = dht.getTempCelcius();
float f = dht.getTempFarenheit();
float hi = dht.getHeatIndex();
//UV sensor floats
float sensorValue = analogRead(A0);
int UVLevel = 0;

//Error Retry
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println("Failed to read from DHT sensor!");
return;
}

if(sensorValue <=10)
{
     UVLevel = 0;
}
if(sensorValue <= 46 && sensorValue > 10)
{
     UVLevel = 1;
}
if(sensorValue <= 65 && sensorValue > 46)
{
     UVLevel = 2;
}
if(sensorValue <= 83 && sensorValue > 65)
{
     UVLevel = 3;
}
if(sensorValue <= 103 && sensorValue > 83)
{
     UVLevel = 4;
}
if(sensorValue <= 124 && sensorValue > 103)
{
     UVLevel = 5;
}
if(sensorValue <= 142 && sensorValue > 124)
{
     UVLevel = 6;
}
if(sensorValue <= 162 && sensorValue > 142)
{
     UVLevel = 7;
}
if(sensorValue <= 180 && sensorValue > 162)
{
     UVLevel = 8;
}
if(sensorValue <= 200 && sensorValue > 180)
{
     UVLevel = 9;
}
if(sensorValue <= 221 && sensorValue > 200)
{
     UVLevel = 10;
}
if(sensorValue <= 240 && sensorValue > 221)
{
     UVLevel = 11;
}
if(sensorValue > 240)
{
     UVLevel = 12;
}

//Serial Print DHT
Serial.println();
Serial.println();
Serial.print("Humid: ");
Serial.print(h);
Serial.print("%");
Serial.println();
Serial.print("Temp: ");
Serial.print(t);
Serial.print("C ");
Serial.println();
Serial.print("Apparent Temperature: ");
Serial.print(hi);
Serial.println();
Serial.println();

//Serial Print UV
Serial.print("UV Level =");
Serial.print(UVLevel);
Serial.println();

//Publish Data To Particle Cloud
Particle.publish("Humidity", String(h));
Particle.publish("Temperature", String(t));
Particle.publish("Apparent Temperature", String(hi));
Particle.publish("UV Index",String(UVLevel));
delay(5000);
}

For reference these are the sensors I am using:

DHT 11 Temp/Humidity sensor

UV sensor


texts: C++ rudimentary bitmap image edge detection

texts:
What my code does is it reads a 24 bit bitmap image in color, runs a very simple edge detection algorithm and outputs a monochrome 1 bit bitmap with the edges in white. Here is an example of the output.

The basic algorithm is that I am looping through all of the pixels in the 24 bit bitmap two pixels at a time and if the difference between the average values of the two pixels is greater than 10 I set the equivalent pixels in the 1 bit file to white.

To give the code context, the variable "header" is an object that holds all of the information about the 24 bit bitmap file such as the height and width and the pointer to where the header ends and the bitmap that holds the pixel values begins. The "header" object was passed into the constructor of the object that has the ten() function.

The one_bit_bitmap "small" variable does the same thing for the 1 bit bitmap that I am outputting to.

The file format of the 24 bit is there is one byte per color (blue,green,red) per pixel. The format for the 1 bit is that there are two 32 bit pixels just after the header information and setting a bit to 0 points that pixel to the value of the first pixel  while setting it to 1 sets to to the value of the second pixel.

This is a personal project that I started to learn about file formats, C++ pointers and flipping individual bits.

void bmp_binary_edge::ten() {
    char * pointer_ahead = header.getBytesAhead();
    unsigned int width_bytes = header.getWidthBytes();
    unsigned int padding_bytes = header.getPaddingBytes();
    unsigned int height = header.getHeightPixels();
    one_bit_bitmap small = one_bit_bitmap(header);
    char * small_ahead = small.getBytesAhead();
    unsigned int small_position = 0;
    for (unsigned int y = 0; y < height; y++) {
        int small_bit_position = 7;
        for (unsigned int x = 0; x < width_bytes; x += 6) {
            unsigned int starting_position = x + (y * width_bytes) + y * padding_bytes;
            unsigned char blue = (unsigned char) pointer_ahead[starting_position];
            unsigned char green = (unsigned char) pointer_ahead[starting_position + 1];
            unsigned char red = (unsigned char) pointer_ahead[starting_position + 2];
            unsigned char blue2 = (unsigned char) pointer_ahead[starting_position + 3];
            unsigned char green2 = (unsigned char) pointer_ahead[starting_position + 4];
            unsigned char red2 = (unsigned char) pointer_ahead[starting_position + 5];
            unsigned char first_av = (blue + red + green) / 3;
            unsigned char second_av = (blue2 + red2 + green2) / 3;
            int difference = first_av - second_av;
            if (difference < 0) {
                difference *= -1;
            }
            //One
            if (difference > 10) {
                small_ahead[small_position ] ^= (-1 ^ small_ahead[small_position]) & (1 << small_bit_position);
                small_ahead[small_position ] ^= (-1 ^ small_ahead[small_position]) & (1 << (small_bit_position - 1));
            }
            if (small_bit_position == 1) {
                small_position++;
                small_bit_position = 7;
            }
            else {
                small_bit_position -= 2;
            }
        }
        small_position += small.getPaddingBytes();
    }
    small.fileWrite(ext_ten);
    cout << "bmp_binary_edge ten" << endl;
    cout << line_break;
    header.deleteBytes();
}


texts: Using System.Security.Cryptography.ProtectedData, do you see any issue with encryption and encoding?

texts:
The application needs to keep a secret which is known to logged in windows user. User enters secret in windows form's text box which is read by application. This is in form of System.String. Now I have to persist this secret into a XML file. And later able to decipher it back and use it.

Questions:

Do you see any concern with encoding done below?
Is there any concern with using System.String to begin with? I was
considering to use System.Security.SecureString but at some point
down the line the application needs to have base underlying string
in clear text.

I'm using System.Security.Cryptography.ProtectedData to do the encryption.

The code

using System.Security.Cryptography;

static public string Encrypt(string password, string salt)
{
    byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
    byte[] saltBytes = Encoding.Unicode.GetBytes(salt);

    byte[] cipherBytes = ProtectedData.Protect(passwordBytes, saltBytes, DataProtectionScope.CurrentUser);

    return Convert.ToBase64String(cipherBytes);
}

static public string Decrypt(string cipher, string salt)
{
    byte[] cipherBytes = Convert.FromBase64String(cipher);
    byte[] saltBytes = Encoding.Unicode.GetBytes(salt);

    byte[] passwordBytes = ProtectedData.Unprotect(cipherBytes, saltBytes, DataProtectionScope.CurrentUser);

    return Encoding.Unicode.GetString(passwordBytes);
}

Typical usage

[TestMethod()]
public void EncryptDecryptTest()
{
    string password = "Gussme!";
    string salt = new Random().Next().ToString();

    string cipher = Authenticator.Encrypt(password, salt);
    Assert.IsFalse(cipher.Contains(password), "Unable to encrypt");
    Assert.IsFalse(cipher.Contains(salt), "Unable to encrypt");

    string decipher = Authenticator.Decrypt(cipher, salt);
    Assert.AreEqual(password, decipher);
}


texts:
I have write this code that read a txt file and re-write it whith the timestamp sorted.

This is the result (top image is input, bottom is output)

MY QUESTION IS:
Anyone do you have a suggestion to optimize this code? Because this text is a little example,my code would work with txt more longer than it. (For example 50K-60K line)

Regards

static void Main(string[] args)
{

    string[] str;

    //Define regex string for MEX ETCS
    string messageETCS = @"(\d){4}-(\d){2}-(\d){2}.*(?:\r?\n(?!\d{4}-\d{2}-\d).*)*";
    Regex regMEXETCS = new Regex(messageETCS);

    string regexDate = @"\d{4}-\d{2}-\d{2}";
    Regex regDateETCS = new Regex(regexDate);

    // Open the text file using a stream reader.
    using (StreamReader sr = new StreamReader(@"C:\input.txt"))
    {
        // Read the stream to a string, and write the string to the console.
        String logContent = sr.ReadToEnd();

        //run regex
        List<String> MasterList = new List<String>(logContent.Length);
        Match matchResults = regMEXETCS.Match(logContent);
        Match onlyDate = regDateETCS.Match(logContent);
        str = Regex.Split(logContent, @"\d{4}-\d{2}-\d{2}", RegexOptions.None);

        while (matchResults.Success)
        {

            for (int j = 1; j < str.Length;j++ ) {

            string t = str[j].TrimEnd();
            MasterList.Add(t);
            matchResults = matchResults.NextMatch();
            }
        }

        String date1 = onlyDate.ToString();
        MasterList.Sort();
        using (TextWriter tw = new StreamWriter(@"C:\output.txt"))
        {
            for (int i = 0; i < MasterList.Count; i++)
            {
                tw.WriteLine(date1 + MasterList[i]);
            }
        }
    }
}


texts:
I think the snippet is too nested having too many blocks. It needs to be refactored to make the logic more readable.

The try exception is the first level block
Timeout::timeout is the next level block
Some loop-like blocks inside it

How can I make it more readable?

  def https_request(server_url, header, content)
    begin
      Timeout::timeout(@@TIMEOUT_PERIOD) do
        hack_ssl_options
        uri = URI.parse(server_url)
        https = Net::HTTP.new(uri.host,uri.port)
        https.use_ssl = true
        options_mask = OpenSSL::SSL::OP_NO_SSLv2 + OpenSSL::SSL::OP_NO_SSLv3 + OpenSSL::SSL::OP_NO_COMPRESSION
        https.ssl_options = options_mask
        https.verify_mode = OpenSSL::SSL::VERIFY_NONE
        req = Net::HTTP::Post.new(uri.path, initheader = header)
        req.body = content
        headers = req.each_header.inject({}) { |h,(key, value)| h[key] = value ; h }
        resp = https.request(req)
        response_headers = resp.each_header.inject({}) { |h,(key, value)| h[key] = value ; h }
        return { code: resp.code,
                 header: response_headers,
                 body: resp.body }
      end
    rescue Timeout::Error
      return { code: @@timeout_error_code,
               header: nil,
               body: @@timeout_error_msg }
    rescue Exception => e
      return { code: @@unknown_error_code,
               header: nil,
               body: @@unknown_error_msg }
    end
  end


texts:
I'm writing a little Downloader that will look through directories online and download the content. The first prototype of my program is a success, now I just want to refine it and learn some more C#. The task is this:

Take this string:

http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/

and create the substring between the last two /

Result: All%20Ends%20In%20Silence

I find my current code brutish and probably not a clean, C# way of solving the problem:

    string GetDirectoryName(string directory)
    {
        int lastIndex  = directory.LastIndexOf("/");
        int count = directory.Count<char>(elem => elem == '/') - 1;

        int startIndex = 0;
        while (count > 0)
        {
            startIndex = directory.IndexOf("/", startIndex) + 1;
            --count;
        }

        return directory.Substring(startIndex, lastIndex - startIndex).Replace("%20", " ");
    }

Please advise me how I could make this code cleaner, clearer and following the C# methodology of programming.


texts: Custom template system with introspection in Perl

texts:
I know I never have to reinvent the wheel, but I did, because I need speed performance, also I need this features:

introspection or metaprogramming
actuate like api backend
private variables interpolation
embedded perl code inside template like text template
avoid in the minimal no core modules
work with eval in environment secure (Eval::Closure)
have block or macros to procces behavior like subroutines when you used block html and code perl

Template::Toolkit, has almost all features listed above but is slow

Is this code good?

package Myapp::Template;
use strict;
use warnings;

use Eval::Closure;
use B qw( perlstring );
use Carp qw( confess );

sub new {
    my $class = shift;
    return bless {}, $class;
}

sub parser {
   my ($self, $html_file, $hash ) = @_;

   my @delims =  qw( [% %] );
   my $regexp = join('|', map quotemeta($_), @delims);

   my @code;
   push @code, 'sub {';
   push @code, 'my $OUT = q();';
   map { push @code,  'my $'.$_.' = "'.$hash->{$_}.'"; ' } (keys %{$hash} );

   my @parts  = split /($regexp)/, $html_file;
   my $mode = 'text';
   while (@parts) {

     my $next = shift @parts;

     if ($next eq $delims[0]) {
       $mode = ($mode eq 'text') ? 'code' : confess("Impossible state");
       next;
     }
     if ($next eq $delims[1]) {
       $mode = ($mode eq 'code') ? 'text' : confess("Impossible state");
       next;
     }

     if ($mode eq 'text') {
       $code[-1] .= sprintf('$OUT .= %s;', perlstring($next));
     }
     elsif ($next =~ /\A=/) {
       $next =~ s/(\(\)|\(\s+?\))/\($self->{id_plugin}\)/g if exists $self->{id_plugin};
       $code[-1] .= sprintf('$OUT .= do { %s };', unpack("x1A*", $next), );
     }
     elsif ($next =~ /\A\sBLOCK/) {
       my $theblock = "sub " . unpack("x6A*", $next) . ' { my $OUT; ';
       $code[-1] .= sprintf(" %s;", $theblock);
     }
     elsif ($next =~ /\A\sPROCESS/) {
       my $runsub =  unpack("x8A*", $next);
       $code[-1] .= sprintf('$OUT .= %s;',  $runsub . "();");
     }
     elsif ($next =~ /\A\sEND/) {
       my $theblock = 'return $OUT; } ';
       $code[-1] .= sprintf(" %s;", $theblock);
     }
     else {
       $code[-1] .= sprintf(" %s;", $next);
     }

   }

   push @code, '$OUT;';
   push @code, '}';

   my ($thecode) = \@code;
   return eval_closure( source => $thecode )->();

}

sub get_blocks {
  my $self = shift;
  my $html_file = shift;
  my $thisblock = shift;
  my $id_plugin = shift;

  if (!defined $thisblock){
    my @blocks = $html_file =~ /(?>BLOCK\s+)(\w+)/g;
    return join "
", (@blocks);
  }
  else{

    $self->{id_plugin} = $id_plugin;
    my @blockprocess;
    my @main_block;

    my $check_block = sub {
      my $the_block = shift;

      for (split /\n/, $html_file) {

           if (/(?>BLOCK\s+)($the_block)/../(END)/){
             push @blockprocess, $1 if $_ =~ /(?>PROCESS\s+)(\w+)/;
             push @main_block, $_;
           }

      }

    };

    $check_block->($thisblock);
    map{ $check_block->($_) } @blockprocess;

    push @main_block, "[% PROCESS $thisblock %]";
    my $allbkocks = join "", @main_block;
    return  $self->parser($allbkocks);
  }

}

1;

Example html with block and process

 [% BLOCK function_sub %]

example

 [% use Module::Runtime;
 my $var = 'this is not printing here';
 %]
bla

 [%= $var; #print %]
 [% END %]

       [% PROCESS function_sub %]


texts:
I wrote my first jQuery plugin. It counts characters in a similar way to what StackExchange uses for comment entries. You can see it in action with this fiddle.

I feel that it's messy, but I can't explain why. One of the default options is defined outside the defaults hash because it uses a self-reference, and the method for flashing the text seems out of place. I'm also a little worried about how it handles form submission, and its prevention when the minimum number of characters is not met.

I'm not very fluent with jQuery so I expect this to be atrocious. I would love to hear some feedback as to why, or how it could be improved.

The form is submitted via ajax, using Rails' unobtrusive JS.

(function ($) {
    "use strict";

    $.fn.counter = function (options) {
        var defaults = {
            minimumSize: 15,
            minimumWarning: " more to go...",
            maximumSize: 25,
            maximumWarning: " characters remaining...",
            warningSize: 20,
            targetClass: '.help-block'
        };

        defaults.defaultText = "Enter at least " + defaults.minimumSize + " characters.";
        options = $.extend(defaults, options);

        function count(elem) {
            var size = elem.val().length, target = elem.siblings(options.targetClass);
            if (size === 0) {
                target.html(options.defaultText);
            } else if (size < options.minimumSize) {
                target.html((options.minimumSize - size) + options.minimumWarning);
            } else if (size >= options.minimumSize && size < options.warningSize) {
                target.html('&nbsp;');
            } else if (size >= options.warningSize && size < options.maximumSize) {
                target.html((options.maximumSize - size) + options.maximumWarning);
            } else if (size >= options.maximumSize) {
                elem.val(elem.val().substring(0, options.maximumSize));
                target.html("0" + options.maximumWarning);
            }
        }

        this.each(function () {
            var elem = $(this);
            count(elem);
            elem.keyup(function () {
                count(elem);
            });
            elem.closest('form').submit(function () {
                if (elem.val().length < options.minimumSize) {
                    $(this).find(options.targetClass).fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
                    return false;
                }
            });
            return elem;
        });
    };
})(jQuery);


texts:
This is an auction function for a game where you can bid on houses on the website.

You set a limit, and if posts limit below current bet or below your limit, it will raise the bid from current plus 1, until the limit is met. If your bid is over a player's limit, it updates it with your limit.

Let's say the current limit for house #55 is 500 and was submitted by player CykaBlyat and then Andrej comes and submit a limit of 800 it will update latest limit plus one (so bid will be 501) and keep raising with 1 until someone submit a limit higher than 800. And so on.

Is it safe? Is there something I have missed? Something I can do better? A cleaner way?

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Fetch some info about the house
$house_query = "SELECT h.id AS houseID, h.name AS houseName, h.rent, h.size, h.numofdoors, h.beds, h.owner, h.paid, p.name
            FROM houses h
            LEFT JOIN players p ON p.id = h.owner
            WHERE h.id = ?";

$stmt = $db->prepare($house_query);
$stmt->execute(array($id));
$row = $stmt->fetch();

// Is house on auction
$auctions = "SELECT *
            FROM house_auctions ha
            LEFT JOIN players p ON p.id = ha.player_id
            WHERE ha.house_id = $id";

$stmt = $db->prepare($auctions);
$stmt->execute(array($id));
$auction = $stmt->fetch();

if (count($_POST) > 0) {

$limit = trim($_POST['limit']);
$char = trim($_POST['character']);

// Get balance
$balance = $db->prepare("SELECT balance FROM players WHERE id = ?");
$balance->execute(array($char));

if ($limit <= $auction['bid'])
    $errors[] = "Your limit for the bid is lower than the current bid.";

else if ($limit == $auction['bid'])
    $errors[] = "Limit is same as current bid.";

// Check their balance
else if ($limit + $row['rent'] > $balance->fetchColumn())
    $errors[] = "You do not have enough gold.";

else if ($limit < $auction['limit']) {
    $bid = $limit + 1;
    $limit2 = $auction['limit'];
    $pid = $auction['player_id'];
}
else if ($limit > $auction['limit']) {
    $bid = $auction['limit'] + 1;
    $limit2 = $limit;
    $pid = $char;
} else {
   $bid = $auction['limit'] + $limit + 1;
   $limit2 = $limit;
   $pid = $char;
}
// Let's update!
if (empty($errors)) {
    echo "NO ERRORS =)";

    $stmt = $db->prepare("UPDATE house_auctions SET house_id = :house_id, player_id = :player_id, bid = :bid, `limit` = :limit, endtime = :endtime");
    $stmt->execute(array(':house_id'=>$id, ':player_id'=>$pid, ':bid'=>$bid, ':limit'=>$limit2,':endtime'=>time()));

}
}

// If there were any errors, show them
if (!empty($errors)) {
foreach ($errors as $cur_error)
echo '
'.$cur_error.'
';
}


texts: Finding the number of times a query string appears in a vector of strings c++

texts:
I wrote some code that iterates over some queries and counts the number of times each query appears in a vector of words. My first iteration iterated through all the words in the vector for each query which is wasteful. I improved it and come up with this.

unordered_map<string, int> matchingStrings(vector<string>& strings, vector<string>& queries) {
    sort(strings.begin(), strings.end());
    sort(queries.begin(), queries.end());
    unordered_map<string,int> counts;
    auto s = strings.begin();
    bool notfound;
    int count = 0;
    for (auto& q : queries) {
        count = 0;
        auto temp = s;
        notfound = false;
        while (q.compare(*s)) {
            if (s != strings.end()-1) {
                s++;
            }
            else {
                counts[q] = count;
                notfound = true;
                s = temp;
                break;
            }
        }
        if (notfound) continue;
        while (!q.compare(*s)) {
            count++;
            if (s != strings.end()-1) {
                s++;
            }
            else {
                break;
            }
        }
        counts[q] = count;
    }
    return counts;
}

It works on my test cases, so I think it has some place here on code review. I would like to know how I can tidy this up? also! In the case where the query is not found we go back to the string the non-present query started at. Is there a way to get around this?

By "tidy this up" I mean, avoiding code repetition and maybe some alternative ideas? Possibly some modern c++ tools even?


texts: Inserting non-empty form values into database

texts:
I have a form that I submit and returns me about 500 rows. Before inserting into table I check the strings are not null. This means it loops all the strings.

Is there a better way that it doesn't have to check all the values?

Only wheel_winner will be an empty string, and emp_id will always have a number.

<form>
<cfoutput>

    <input type="text"  name="wheel_winner#CurrentRow#" id="sum" value="">
     #emp_namefirst#
    <input type="hidden" name="emp_id#CurrentRow#" value="#emp_id#">

</cfoutput>
<cfoutput>
        <input type="Hidden" name="ResCount" value="#GetEmployees.RecordCount#">
</cfoutput>
</form>

<cfloop from="1" to="#ResCount#" index="j">
    <cfset  emp_id  = #Trim(form["emp_id" & j])#>
    <cfset  WHEEL_WINNER    = #Trim(form["WHEEL_WINNER" & j])#>

<cfif WHEEL_WINNER neq "" and emp_id neq "" >
        <cfquery datasource="test" >
            INSERT INTO stamps (emp_id, wheel_winner )
            VALUES (<cfqueryPARAM value = "#emp_id#" CFSQLType = 'CF_SQL_INTEGER'>,
            <cfqueryPARAM value = "#wheel_winner#" CFSQLType = 'CF_SQL_INTEGER'>)
        </cfquery>
</cfif>

</cfloop>


texts: Determining if a possible new entry already exists in a dataset

texts:
For example, if I have the following data table layout:

dt.Columns.Add("ticketid", typeof(Int32));
dt.Columns.Add("createtime", typeof(DateTime));
dt.Columns.Add("creator", typeof(string));
dt.Columns.Add("ticketText", typeof(string));

If I want to add a new entry I need to make sure that there exists none already that has the same primary key (ticketid, createtime, creator).

The check is as follows:

if (
    dt.Rows.Count <= 0 ||
    (
        dt.Rows.Count > 0 &&
                    null == dt.AsEnumerable().Where
                        (
                            r => r.Field<int>("ticketid") == newEntry.TicketId
                                && DateTime.Equals(r.Field<DateTime>("createtime"), newEntry.CreateTime)
                                && r.creator == newEntry.Creator
                         )
                         .FirstOrDefault()
   ))

The code does what it is meant for, BUT my problem is that it is SLOW. In my case I need to read 2 million entries from the file and put them into the database as fast as possible at which this code fails (as soon as I use the code the runtime goes from just 1 minute to over 30 minutes). Is there any faster way to do this?

Site-note: the datatable is read from a file and the above is a check to make sure the data is ok before it is bulk inserted into the db.

Example with happenings:

if (
    dt.Rows.Count <= 0 ||
    (
        dt.Rows.Count > 0 &&
                    null == dt.AsEnumerable().Where
                        (
                            r => r.Field<int>("ticketid") == newEntry.TicketId
                                && DateTime.Equals(r.Field<DateTime>("createtime"), newEntry.CreateTime)
                                && r.creator == newEntry.Creator
                         )
                         .FirstOrDefault()
   ))
{
    // No duplicate found so insert the data into the data table
   dt.Rows.Add(new object[] {newEntry.TicketId, newEntry.CreateTime, newEntry.Creator});
}


texts:
I coded a little URL encoding tool to exercise the JAVA MVC pattern with SWING.
Can somebody give me feedback if this is the right way to implement the MVC pattern?

package model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class MainModel
{
    public String convertText(String text)
    {
        try
        {
            return URLEncoder.encode(text, "UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            return "Could not be converted.";
        }
    }
}

package view;

import java.awt.Color;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class MainView extends JFrame
{
    private static final long serialVersionUID = 1L;

    private JButton convertButton;

    private JTextArea textArea;

    public MainView()
    {
        setBounds(50, 50, 300, 400);

        JPanel panel = new JPanel();

        textArea = new JTextArea(10, 10);
        panel.add(new JScrollPane(textArea));

        convertButton = new JButton("Convert");
        panel.add(convertButton);

        add(panel);

        getContentPane().setBackground(Color.white);
        setVisible(true);
    }

    public String getText()
    {
        return textArea.getText();
    }

    public void setText(String text)
    {
        this.textArea.setText(text);
    }

    public void addConvertListener(ActionListener listener)
    {
        convertButton.addActionListener(listener);
    }

}

package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import model.MainModel;
import view.MainView;

public class MainController
{
    MainView view;
    MainModel model;

    public MainController(MainView view, MainModel model)
    {
        super();
        this.view = view;
        this.model = model;

        view.addConvertListener(new ConvertActionListener());
    }

    class ConvertActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            view.setText(model.convertText(view.getText()));
        }
    }
}


texts:
I'm new in Golang and haven't done concurrency in a bit. I would love to hear your opinion on my Dining problem Go solution. Description here, with a tl;dr below:

Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.

Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can only take the fork on their right or the one on their left as they become available and they cannot start eating before getting both forks.

Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.

The problem is how to design a discipline of behavior (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.

package main

import "fmt"
import "sync"
import "time"

const NumPhilosophers = 5
var phi [NumPhilosophers]int
var forks [NumPhilosophers]sync.Mutex

func startPhilosopher(number int, c chan string){
    left, right := (number+1)%NumPhilosophers, number
    min, max := left,right
    if min > max {
        min, max = max, min
    }

    for i := 0; i < 4; i++ {
        c <-"Thinking " + time.Now().Round(0).String()
        forks[min].Lock()
        forks[max].Lock()

        c <- "Eating " + time.Now().Round(0).String()

        forks[max].Unlock()
        forks[min].Unlock()
    }
    close(c)
}

func main() {
    var ch [NumPhilosophers]chan string
    for i := 0; i < NumPhilosophers; i++ {
        phi[i] = i
        ch[i] = make(chan string)
        go startPhilosopher(i, ch[i])
    }

    for a := 0; a < NumPhilosophers; a++ {
        fmt.Println(a)
        for i := range ch[a] {
            fmt.Println(i)
        }
    }
}


texts:
I've implemented a barreir in C++ close to one showed here. In the project code it's used only with two threads and seems to work. A synthetic test didn't expose any flaws too. But I suspect that on some machines it segfaults and/or falls through wait() call.
How do you think, can it fall through wait or is any race scenario possible with it?
Used mainly on Windows machines, if it matters.

class Barrier
{
public:
    explicit Barrier(uint16_t iCount) : maxThreads(iCount), count(iCount) {}

    void wait(std::chrono::milliseconds = std::chrono::milliseconds(0));

private:
    void notifyAll();

private:
    std::mutex mutex;
    std::condition_variable cv;
    uint16_t maxThreads;
    uint16_t count;
    bool generation = true;
};

inline void Barrier::wait(const std::chrono::milliseconds timeWait)
{
    std::unique_lock<std::mutex> ulock(mutex);
    auto gen = generation;
    const auto waitCondition = [this, gen]{ return (gen != generation); };
    if (0 == --count) notifyAll();
    else {
        if (timeWait == std::chrono::milliseconds(0)) cv.wait(ulock, waitCondition);
        else {
            const auto timedOut = !cv.wait_for(ulock, timeWait, waitCondition);
            if (timedOut) ++count;
        }
    }
}

inline void Barrier::notifyAll()
{
    generation = !generation;
    count = maxThreads;
    cv.notify_all();
}

P.S. I know that generation is poor naming for this particular variable. Here it's intended to express similarity to the same name variable from abovementioned SO question code.


texts:
I have two .on() functions for separate dynamically added elements, they are:

$('body').on('click', 'img', function() {
   modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
});
$('body').on('click', 'img', function() {
   closeM();
});

The second function, I have shortened to

$("body").on("click", "#close", closeM);

In looking at the jQuery documentation for .on(), I saw that I can do something like:

$("body").on({
  click: function(){
  },
  mouseenter: function() {
  }
});

I was wondering if I could either do something like that with my previous two functions, or if there was any other way of shortening/combining them.


texts:
I have function that convert binary number to unary number based on a Markov algorithm. In what ways can I improve the code?

The algorithm goes as follows:

Replace all 0l with 0l

  "|0" -> "0||"

Replace all l0 with 0ll

  "1" -> "0|"

Major Step 3: Remove the 0

  "0" -> ""

    public List BinaryToUnary(List value)
    {
        var temp = new List();
        var temp2 = new List();
        var temp3 = new List();
        string hold = "";
        int count = 1;

        TxtToDisPlay = "Major Step 1: replace All 1 with 0l userInput " + string.Join("", value) + "\n\n";

        foreach (var x in value)
        {
            if (x.Equals("1"))
            {
                temp.Add("0l");
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + x + " = " + "0l" + "\n";
            }
            else
            {
                temp.Add(x);
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + x + " = " + x + "\n";
            }
            count++;
        }
        TxtToDisPlay = TxtToDisPlay + "\n\nMajor Step 2: Replace all l0 with 0ll  userInput = " + string.Join("", temp) + " \n\n";

        foreach (var x in string.Join("", temp))
        {
            hold = hold + x;
            if (hold.Equals("l0"))
            {
                temp2.Add("0ll");
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + hold + " = " + "0ll" + "\n";
                hold = "";
            }
            if (hold.Equals("0"))
            {
                temp2.Add(hold);
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + hold + " = " + hold + "\n";
                hold = "";
            }
            count++;
        }
        if (hold.Equals("l"))
        {
            temp2.Add("l");
        }

        hold = "";

        foreach (var y in string.Join("", temp2))
        {
            if (temp2.Count == 1)
            {
                temp3.Add("l");
                break;
            }

            hold = hold + y;
            if (hold.Equals("l0"))
            {
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + hold + " = " + "0ll" + "\n";
                temp3.Add("0ll");
                hold = "";
            }
            if (hold.Equals("0") || hold.Equals("ll"))
            {
                if (hold.Equals("ll"))
                {
                    TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + hold + " = " + hold + "\n";
                    temp3.Add("l");
                    hold = "l";
                }
                else
                {
                    TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + hold + " = " + hold + "\n";
                    temp3.Add(hold);
                    hold = "";
                }

            }
        }
        if (value.Count == 3 && hold.Equals("l"))
        {
            temp3.Add("l");
            temp3.Add("l");
        }
        else if (value.Count == 3 || hold.Equals("l"))
        {
            temp3.Add("l");

        }

        TxtToDisPlay = TxtToDisPlay + "\n\nMajor Step 3 : get rid of the 0 from  userInput = " + string.Join("", temp3) + " \n\n";
        var answer = new List();
        foreach (var x in temp3)
        {
            if (x.Contains("0ll"))
            {
                foreach (var y in x.Where(y => y.Equals('l')))
                {
                    answer.Add("l");
                    TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + "x = l so " + "Add l To new Array result = " + string.Join("", answer) + "\n";
                }
            }
            else if (x.Contains("l"))
            {
                TxtToDisPlay = TxtToDisPlay + "Step " + count + ": " + "Add l To new Array result = " + string.Join("", answer) + "\n";
                answer.Add(x);
            }
            count++;
        }

        return answer;
        }


texts:
I used Spring MVC arch, and I need to be informed about correct names of methods and exceptions throwing.

/**
 * @author Eugene G. Ustimenko
 * @date Jan 19, 2015
 */
@Service
@Qualifier ("entityService")
public class BaseEntityService < T extends BaseEntity > implements     IBaseEntityService < T > {

  @Autowired
  private IBaseEntityDao<T> dao;

  @Transactional
  @Override
  public T create (T entity) throws ServiceException {

    try {
      return dao.create(entity);
    }
    catch (final Exception ex) {
      throw new ServiceException("Create entity operation error " +     ex.getMessage(), ex);
    }
  }

  @Transactional
  @Override
  public T update (T entity) throws ServiceException {

    try {
      return dao.update(entity);
    }
    catch (final Exception ex) {
      throw new ServiceException("Update entity operation error " +     ex.getMessage(), ex);
    }
  }

  @Transactional
  @Override
  public void remove (Long id) throws ServiceException {

    try {
      dao.remove(id);
    }
    catch (final Exception ex) {
      throw new ServiceException("Remove entity operation error " +     ex.getMessage(), ex);
    }
  }

  @Override
  public List < T > getAll () throws ServiceException {

    try {
      return dao.getAll();
    }
    catch (final Exception ex) {
      throw new ServiceException("Get list of entities operation error "     + ex.getMessage(), ex);
    }
  }

  @Override
  public T get (Long id) throws ServiceException {

    try {
      return dao.get(id);
    }
    catch (final Exception ex) {
      throw new ServiceException("Get entity by identifier operation error" + ex.getMessage(), ex);
    }
  }

}


texts:
I have a program that monitors real-time air waves and demodulates them into useable data. The program runs fine and with very little issues over time. The only thing I am really interested in is whether the calls to memcpy can be handled differently.

I have tried using valgrind and this code does not seem to be leaking memory.

static output_buffer o_buffers[MAX_OUTPUT_BUFF_COUNT]; //MAX_OUTPUT_BUFF_COUNT = 100
static int o_buffer_count = 0;

struct output_buffer
{
    int16_t buf[MAXIMUM_BUF_LENGTH]; //= 262144
    int len;
};

static void rtlsdr_data_callback(unsigned char *buf, uint32_t len, void *ctx)
{
    if (do_exit)
        return;
    rtl_dev *dev_ctx = (rtl_dev *)ctx;

    demod_state *d = &dev_ctx->demod;

    rotate_90(buf, len);

    int16_t buf16[MAXIMUM_BUF_LENGTH];

    //normalize the data
    for (int i = 0; i < (int)len; i++)
        buf16[i] = (int16_t)buf[i] - 127;

    //create a new output buffer
    output_buffer o;
    memcpy(o.buf, buf16, 2 * len);
    o.len = len;

    if (do_exit)
        return;

    //notify the demodulation thread
    pthread_rwlock_wrlock(&d->rw);
    o_buffers[o_buffer_count] = o;
    o_buffer_count++;
    pthread_rwlock_unlock(&d->rw);
}

static void *demod_thread_fn(void *arg)
{
    rtl_dev *ctx = (rtl_dev *)arg;

    demod_state *d = &ctx->demod;

    int fbuf_cnt = 0;
    float fbuf[MAX_DEMOD_BUFFERSIZE];
    int16_t *sp;

    d->lowpassed[0] = 0;

    while (!do_exit)
    {
        if (do_exit)
        {

            return 0;
        }
        if (!o_buffer_count)
        {
            continue;
        }

        //copy the buffers and reset the counter.. TODO: make quicker, watch for leaks
        pthread_rwlock_wrlock(&d->rw);
        int old_buffer_count = o_buffer_count;
        output_buffer *old_buffers = (output_buffer *)malloc(sizeof(output_buffer) * MAX_OUTPUT_BUFF_COUNT);
        memcpy(old_buffers, o_buffers, sizeof(output_buffer) * MAX_OUTPUT_BUFF_COUNT);

        o_buffer_count = 0;
        pthread_rwlock_unlock(&d->rw);

        for (int i = 0; i < old_buffer_count; i++)
        {
            output_buffer o = old_buffers[i];

            memcpy(d->lowpassed, o.buf, 2 * o.len);
            d->lp_len = o.len;
            //do work with the data...
        }
        free(old_buffers);
    }

    return 0;
}

Now the actual program is quite large so a working sample will be very hard to create.

However, some notes:

pthread_rwlock_wrlock(&d->rw); is referencing a pthread_rwlock_t rw;
rtlsdr_data_callback is called as soon as a buffer is ready. This method needs to exit as quick as possible to prevent data loss.
demod_thread_fn is not as important for performance as we are on another thread not responding to real-time airwaves however the block pthread_rwlock_wrlock(&d->rw); to pthread_rwlock_unlock(&d->rw); will consequently block the rtlsdr_data_callback
The "air-waves" are simple FLEX pager waves and transmissions may be within milliseconds.


texts: Finding the node with the smallest maximum distance to all the other nodes

texts:
This code is supposed to find, in a graph, the node with the smallest maximum distance to all the other nodes. The problem from Quora is :

  How do I find the node that has the least maximum distance to all the
  other nodes in a tree? "So you're thinking about moving into an
  unknown city. You have been given a map of the city and want to get a
  house by the street corner that has the least maximum distance to all
  the other street corners. (Think the street corners as nodes, and the
  way between them as edges.)"

For instance, in this example graph:

2 is the node that has the least maximum distance to all other nodes. I found out that the complexity is \$O(n*(n*m))\$, and that works great when I have less than 5000 nodes. What could I possibly fix to make this solution handle nodes >100 000? Should I use, for instance, iteration instead of recursion?

I have done some "minor" tweaks, replacing all cout and cin With printf and scanf, and decreased the execution time by 40ms.

#include <cstudio>
#include <queue>
#include <vector>
int biggest_dist(int n, int v, const vector< vector<int> >& graph)
{ //This function finds the diameter of thegraph
int INF = 2 * graph.size(); // Bigger than any other length
vector<int> dist(n, INF);

dist[v] = 0;
queue<int> next;
next.push(v);

int bdist = 0; //biggest distance
while (!next.empty()) {
    int pos = next.front();
    next.pop();
    bdist = dist[pos];

    for (int i = 0; i < graph[pos].size(); ++i) {
        int nghbr = graph[pos][i];
        if (dist[nghbr] > dist[pos] + 1) {
            dist[nghbr] = dist[pos] + 1;
            next.push(nghbr);
        }
    }
}

return bdist;
}

int main()
{
int N; scanf("%i", &N);
int minst;
vector< vector<int> > graph(N);
vector<int> noder;
for (int i = 0; i < N - 1; ++i) {
    int a, b;
    scanf("%d %d", &a, &b);

    graph[a].push_back(b);
    graph[b].push_back(a);
}

int answer = 0;
int dis = biggest_dist(N, 0,graph);
int maxdist;
for (int j = 0; j < N-1; ++j)
{
    maxdist = biggest_dist(N,j, graph);
    if (maxdist < dis)
    {
        dis = maxdist;
        answer = j;
    }
}
printf("%d", answer);

return 0;
}


texts:
I am fairly new to C++ programming and I, so far, love it. I just have been trying to make sure what I am doing is fast, unique, readable, and efficient. Is there anyway I can improve this code, or is there ways I can improve my coding convention (in C++)? Here I wrote a program that generates a 20 random vectors of binary digits (20 to test "randomness").

#include <stdbool.h>
#include <cstdlib>
#include <iostream>
#include <ctime>

void returnarray(bool* array, int size)
{
    for (int i = 0; i < size; i++)
    {
        std::cout << array[i];
    }
    std::cout << "\n";
}

bool* assignzero(int size)
{
    bool* b = new bool[size];
    for (int i = 0; i < size; i++)
    {
        b[i] = false;
    }

    return b;
}

void generate()
{
    int p = 9;
    int t = rand() % p;
    bool* b = assignzero(p);

    for (int x = 0; x < t; x++)
    {
        b[rand() % p] = true;
    }

    returnarray(b, p);
}

int main()
{
    long inc;
    srand(time(0));
    while (inc < 20)
    {
        generate();
        inc += 1;
    }
}


texts:
There is a way in Scala to selectively change a field while making a copy of the immutable object:

case class Phone(areaCode: String, number: String) // declare type
val original = Phone("832","123-4567") // instantiate
val changed = original.copy(areaCode = "425") // get an updated copy

While in C# it looks like a real pain as usual. One need to create copy ctor and modifiers:

public class Phone
{
    Phone(Phone source)
        : this(source.AreaCode, source.Number)
    {
    }

    public Phone(string areaCode, string number)
    {
        AreaCode = areaCode;
        Number = number;
    }

    public string AreaCode { get; private set; }
    public string Number { get; private set; }

    public Phone WithAreaCode(string value) =>
        new Phone(this) { AreaCode = value };

    public Phone WithNumber(string value) =>
        new Phone(this) { Number = value };
}

We are probably supposed to charge per line…

Here is what I use to mitigate the problem. The immutable type is as easy as it could be:

public class Phone
{
    public Phone(string areaCode, string number)
    { AreaCode = areaCode; Number = number; }

    public string AreaCode { get; }
    public string Number { get; }
}

But there is an extension method to do the trick:

var original = new Phone("832", "123-4567");
var changed = original.With(p => p.AreaCode, "425");

which is defined as:

public static class Cloneable
{
    public static TSource With<TSource, TProperty>(this TSource source, Expression<Func<TSource, TProperty>> selector, TProperty value) =>
        source.With(new Binding(selector.Target(), value));

    static TSource With<TSource>(this TSource source, Binding change) =>
        (TSource)Activator.CreateInstance(typeof(TSource), source.Parameters(change));

    static object[] Parameters<TSource>(this TSource source, Binding change)
    {
        var values = source.Values().Update(change)
            .ToDictionary(b => b.Name, b => b.Value, StringComparer.OrdinalIgnoreCase);

        return typeof(TSource).GetConstructors().Single().GetParameters()
            .Select(p => values[p.Name])
            .ToArray();
    }

    static IEnumerable<Binding> Values<TSource>(this TSource source) =>
        typeof(TSource).GetProperties()
            .Select(p => new Binding(p.Name, p.GetValue(source)));

    static IEnumerable<Binding> Update(this IEnumerable<Binding> values, Binding change) =>
        values.Select(b => b.Name == change.Name ? change : b);

    static string Target<TSource, TProperty>(this Expression<Func<TSource, TProperty>> selector) =>
        selector.Body is MemberExpression member && member.Member is PropertyInfo property
            ? property.Name
            : throw new ArgumentException();

    class Binding
    {
        public Binding(string name, object value)
        { Name = name; Value = value; }

        public string Name { get; }
        public object Value { get; }
    }
}


texts:
In my first iterative algorithm, I do this

for (auto &widget : controls.getWidgets())
{
    if (!widget->visible) continue;

    widget->draw();

    for (auto &widget_component : widget->components)
    {
        if (!widget_component->visible) continue;

        widget_component->draw();

        for (auto &ww : widget_component->components)
        {
            if (!ww->visible) continue;

            ww->draw();
        }
    }
}

Now, I see the flaw in this algorithm because of the repetition of code.

I try to write a recursive function call to handle this thing.

void swcApplication::recursiveDisplay(swcWidget *next)
{
    if (next == nullptr) return;

    if ((next->parent != nullptr) &&
        !next->parent->visible) return;

    if (next->visible)
        next->draw();

    for (auto &i : next->components)
    {
        recursiveDisplay(i);
    }
}

void display()
{
    for (auto &widget : controls.getWidgets())
    {
        recursiveDisplay(widget);
    }
}

Display first the parent before all other children, if parent is not visible, then don't draw its children

Is the above phrase satisfy by this algorithm (As far as I can see, it is)? Is this optimal? I don't know what drawbacks might occur here because I just write in a few seconds.

If you didn't find anything wrong here, now, how can I put it back in iterative way? I know iteration is better.

Update

I didn't use any z attribute here and instead I go for painter's algorithm.

The flaw I am referring in my iteration version is that, it is limited to draw widgets depends on how deep I will code for iteration.


texts:
I have a dictionary of dictionary such as d below, and I would like to get the list of all keys but not on the first level (i.e. ABC, DEF) but the one at the second level (i.e 0 and 1 for ABC ; 1 and 2 for DEF...)

I got this small code that does the job by reading all the dictionaries and by saving the keys (of second level):

d = {
    'ABC' : {'0' : [(1,0.5), (2, 0.25)], '1' : [(1,0.4), (3,0.35)]},
    'DEF' : {'1' : [(1,0.5), (4, 0.15)], '2' : [(2,0.3), (3,0.25)]},
    'GHI' : {'0' : [(3,0.2), (4, 0.05)], '2' : [(2,0.2), (2,0.25)]},
}

keys2 = []
for small_d in d.itervalues():
    keys2.extend(small_d.keys())

print set(keys2)
# set(['1', '0', '2'])

But I'm sure there is a more pythonic way to do it (and more efficient), any ideas?


texts:
This is a simple implementation of text prediction using a list of keywords and UITextChecker.

This is working correctly, but I think I could have implemented better. My goal is to use a protocol oriented approach.

protocol KeywordSuggester {
    func suggestion(word: String) -> String?
    func loadKeywords() -> Set<String>
}

class EmojiKeywordSuggester: KeywordSuggester {
    var keywords: Set<String> = []
    let language = "en_US"
    private let textChecker = UITextChecker()

    init() {
        self.keywords = self.loadKeywords()
    }

    func suggestion(word: String) -> String? {
        var completions = (textChecker.completionsForPartialWordRange(word.fullRange, inString: word, language: language) ?? []) as! [String]
        let guesses = (textChecker.guessesForWordRange(word.fullRange, inString: word, language: language) ?? []) as! [String]

        completions.appendContentsOf(guesses)
        completions = completions.filter(self.keywords.contains)

        guard completions.count > 0 else { return nil }
        return completions[0]
    }

    func loadKeywords() -> Set<String> {
        //TODO: load CSV from file
        return ["happy", "smile", "nature", "mushroom", "eye", "poop", "icecream", "food", "grin", "face"]
    }
}