texts: K&R2 solution to exercise 1-18 (discarding trailing whitespace and empty lines)

texts:
Recently I have started learning C++ and I decided to learn C along the way to improve my understanding of how computers work. For C I am using "The C Programming Language Book" by Brian Kernighan and Dennis Ritchie.

The exercise in question is to print all input lines disregarding trailing whitespace and empty lines.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#define MAX_BLANKS 5

int main()
{
    int c; /*holds current char to be printed*/
    int* wsbuffer; /*buffer to hold possible trailing whitespace*/
    int buffer_size; /*size of wsbuffer*/
    int nws; /*number of whitespaces in buffer*/
    int nonempty; /*0 if current line is empty, 1 else*/
    int i; /*for loop*/
    nonempty  = nws = 0;
    buffer_size = MAX_BLANKS;
    wsbuffer = (int*) malloc(buffer_size*sizeof(int));

    while (EOF != (c=getchar()))
    {
        if (c==' ' || c=='\t')
        {
            ++nws;
            if (nws>buffer_size)
            {
                buffer_size *=2;
                wsbuffer = (int*) realloc(wsbuffer,buffer_size*sizeof(int));
            }
            wsbuffer[nws-1] = c;
        }
        else if (c=='\n')
        {
            if (nonempty==1) {
                putchar(c);
                nws = nonempty = 0;
            }
        }
        else
        {
            nonempty = 1;
            for (i=0;i<nws;++i)
                putchar(wsbuffer[i]);
            nws = 0;
            putchar(c);
        }
    }
    free(wsbuffer);
    return 0;
}

I compiled this using gcc -std=c90 -Wall -Wextra -pedantic to adhere to the ISO protocol used by the book. It compiled fine with no warnings.

I deliberately set MAX_BLANKS to 5 to test the code. I tested a few cases (empty lines, lines with only space, spaces at first etc) and the result seemed okay.

Since memory allocation is not yet covered in the book, I'd particularly like it if someone could take a look and let me know if I have any issues particularly with memory leaking or something. Of course, any other suggestions or improvements would be welcome!


texts: Clever way to build a extension method that ordenate my IQueryable?

texts:
I want to create a ExtensionMethod to ordenate my linq query, called Ordenar. I'll sort it depending what columns is in sortColumns ListDictionary.

I tried some ways, but the best way I arquieve was this :

static class ClienteBusinessExtensions
    {
        public static IQueryable<Model.View_Clientes> Ordernar(this IQueryable<Model.View_Clientes> viewClientes, ListDictionary sortColumns)
        {
            foreach (System.Collections.DictionaryEntry item in sortColumns)
            {
                if (item.Value.ToString()=="ASC")
                {
                    switch (item.Key.ToString())
                    {
                        case "ClienteID":
                            viewClientes = viewClientes.OrderBy(v => v.ClienteID);
                            break;
                        case "Nome":
                            viewClientes = viewClientes.OrderBy(v => v.Nome);
                            break;
                        default:
                            break;
                    }
                }
                else //item.Value.ToString() will be DESC
                {
                    switch (item.Key.ToString())
                    {
                        case "ClienteID":
                            viewClientes = viewClientes.OrderByDescending(v => v.ClienteID);
                            break;
                        case "Nome":
                            viewClientes = viewClientes.OrderByDescending(v => v.Nome);
                            break;
                        case "CpfCnpj":
                            viewClientes = viewClientes.OrderByDescending(v => v.CpfCnpj);
                            break;
                        default:
                            break;
                    }
                }

            }
            return viewClientes;
        }

It is used like this :

var clientesVip = (from vips in db.View_Clientes
                               .Ordernar(sortColumns)
                           select vips);

Are there a clever way to do it? I don't want to use switch statement. I want to sort any field of View_Clientes. It is used in a Asp.NET gridView, when user sort a column.

And View_Clientes entity is :

public partial class View_Clientes
{
    public System.Guid ClienteID { get; set; }
    public string Codcfo { get; set; }
    public string Nome { get; set; }
    public string CpfCnpj { get; set; }
    public string CLI_Origem { get; set; }
}


texts:
I have full working code, but when I run it, it shows these warnings:

given is experimental at grocery.pl line 38.
when is experimental at grocery.pl line 40.
when is experimental at grocery.pl line 62.
when is experimental at grocery.pl line 89.
when is experimental at grocery.pl line 100.

How can I fix these?

use strict;
use warnings;
use List::Util qw(max);
use feature "switch";
my $b;
my $c;
my $p;
my $highest;

print "____________________________STORE THE ITEM_____________________\n";
my %grocery=
(
    "soap"=>{"lux"=>13.00,"enriche"=>11.00},
    "detergent"=>{"surf"=>18.00},
    "cleaner"=>{"domex"=>75.00}
);
foreach my $c(keys %grocery)
{
print "\n";
    print"$c\n";
    foreach my $b(keys %{$grocery{$c}})
    {
        print "$b:$grocery{$c}{$b}\n";
    }
}
my $ch;
do
{
    print "________________MENU_________________\n";
    print "1.ADD ITEM\n";
    print "2.SEARCH\n";
    print "3.DISPLAY\n";
    print "4.FIND THE MAX PRICE\n";
    print "5.EXIT\n";
    print "enter your choice \n";
    $ch=<STDIN>;
    chomp($ch);
    given($ch)
    {
        when(1)
        {
            print "Enter the category you want to add";
            $c=<STDIN>;
            chomp($c);
            print "Enter brand\n";
            $b=<STDIN>;
            chomp($b);
            print "Enter price\n";
            $p=<STDIN>;
            chomp($p);
            if(exists($grocery{$c}))
            {
                $grocery{$c}{$b} = $p;
                print "\n";
            }
            else
            {
                $grocery{$c}={$b,$p};
                print "\n";
            }
        }
        when(2)
        {
            print "Enter the item that you want to search\n";
            $c=<STDIN>;
            chomp($c);
            if(exists($grocery{$c}))
            {
                print "category $c exists\n\n";
                print "Enter brand\n";
                $b=<STDIN>;
                chomp($b);
                if(exists($grocery{$c}{$b}))
                {
                    print "brand $b of category $c exists\n\n";
                    print "-----$c-----\n";
                    print "$b: $grocery{$c}{$b}\n"
                }
                else
                {
                    print "brand $b does not exists\n";
                }
            }
            else
            {
                print "category $c does not exists\n";
            }
        }
        when(3)
        {
            foreach $c (keys %grocery)
            {
                print "$c:\n";
                foreach $b(keys %{$grocery{$c}})
                {
                    print "$b:$grocery{$c}{$b}\n";
                }
            }
        }
        when(4)
        {
            my @all_prices;
            foreach my $c (keys %grocery) {
            push @all_prices, values %{ $grocery{$c} };
        }
        $highest = max @all_prices;
        print "$highest\n";
    }
    }
}while($ch!=5);


texts: minimizing a code for action fired up by scrolling action using waypoint js

texts:
I need an advice on who to write better code. I have a side navigation where there are 4 markers that appear every time I scroll to specific section on the page, the code is working well but it is very long and not flexible, I would like to learn how to write it as modular in which i can reuse it (the library I am using is waypoint js )
HTML code

jQuery script

jQuery(document).ready(function($) {

// waypoint code for navigation marker
    var ourstory = $('#our-story').waypoint({
        handler: function(direction) {
            if (direction == 'down') {
                $(".track-nav-first").addClass("show-our-story");
            }else {
                $(".track-nav-first").removeClass("show-our-story");
            }
        }
    });
    var how = $('#how').waypoint({
        handler: function(direction) {
            if (direction == 'down') {
                $(".track-nav-second").addClass("show-our-story");
            }else {
                $(".track-nav-second").removeClass("show-our-story");
            }
        }
    });
    var how = $('#collection').waypoint({
        handler: function(direction) {
            if (direction == 'down') {
                $(".track-nav-third").addClass("show-our-story");
            }else {
                $(".track-nav-third").removeClass("show-our-story");
            }
        }
    });
    var how = $('#contact').waypoint({
        handler: function(direction) {
            if (direction == 'down') {
                $(".track-nav-fourth").addClass("show-our-story");
            }else {
                $(".track-nav-fourth").removeClass("show-our-story");
            }
        }
    });

});


texts:
The scripts below, I've obtained through tutorials and edited the best I know how. It all works - but I'd like to place them in one, external script. If at all possible, I'd appreciate some help in cleaning up the code too. I've a feeling some of it is redundant.

With the client-side validation script, I have "Name," "Email," "Phone," and "Message" set as input text values in the HTML. If they submit the form with those default values still in place, it gives an error. Also gives one when email is not valid or if phone is not actually a phone number. BUT the phone number is not required. So, the default value of "Phone" could pass through if nothing at all is entered there.

<script type="text/javascript">
$(document).ready(function() {
    $('nav a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();
        var target = this.hash,
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    $(function() {
        $("nav select").change(function() {
            window.location = $(this).find("option:selected").val();
        });
    });
</script>
<script>
$(document).ready(function(){
    // Place ID's of all required fields here.
    required = ["name", "email", "message"];
    // If using an ID other than #email or #error then replace it here
    email = $("#email");
    phone = $("#tel");
    errornotice = $("#error");
    // The text to show up within a field when it is incorrect
    emptyerror = "Required field.";
    emailerror = "Invalid email.";
    nameerror = "Name";
    phoneerror = "Phone";
    messageerror = "Message";
    onlynumber = "Invalid phone.";

    $("#contact").submit(function(){
        //Validate required fields
        for (i=0;i<required.length;i++) {
            var input = $('#'+required[i]);
            if ((input.val() == "") || (input.val() == emptyerror) || (input.val() == nameerror) || (input.val() == messageerror)) {
                input.addClass("needsfilled");
                input.val(emptyerror);
                errornotice.fadeIn(750);
            } else {
                input.removeClass("needsfilled");
            }
        }
        // Validate the e-mail.
        if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
            email.addClass("needsfilled");
            email.val(emailerror);
        }

            if(phone.val() != phoneerror) {
        if (!/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(phone.val())) {
                phone.addClass("needsfilled");
                phone.val(onlynumber);
    }
}

        //if any inputs on the page have the class 'needsfilled' the form will not submit
        if ($(":input").hasClass("needsfilled")) {
            return false;
        } else {
            errornotice.hide();
            return true;
        }
    });

    // Clears any fields in the form when the user clicks on them
    $(":input").focus(function(){
       if ($(this).hasClass("needsfilled") ) {
            $(this).val("");
            $(this).removeClass("needsfilled");
       }
    });
});
</script>
<script>
$(function(){
        $('input, textarea').each(function(){
            var txtval = $(this).val();
            $(this).focus(function(){
                $(this).val('')
            });
            $(this).blur(function(){
                if($(this).val() == ""){
                    $(this).val(txtval);
                }
            });
        });
    });
</script>


texts: Find the maximum profit if given an array of daily stock prices and allowed to buy and sell twice

texts:
I am wondering about the correctness of this method:

We are given a function / algorithm findMaxProfit() that can find the maximum profit when given an array of stock prices, and buy and sell once, with time complexity O(n), additional space complexity O(1). The buy must occur before the sell (meaning no short sell is allowed).

findMaxProfit() will return the maximum profit, and the buy and sell point (as indexes into the array). Example: [3200, 6, 22] meaning max profit is 3200, and buy on day 6, sell on day 22. (day in the description is also 0 index based).

Any buy and sell can occur on the same day, meaning profit = 0.

Now, find the maximum profit if you are allowed to buy and sell at most twice, with the second buy occurring on or after the first sell, and with time complexity O(n), additional space complexity O(1).

I think one assumption is that we buy the same number of shares both times (let's say just 1 share). Otherwise, if the earned money from the first time can be used to buy stocks the second time, then it is not the dollar amount we are concerned with, but the percentage gain overall.

// this function just returns the max profit, no need to return the
// buy / sell point.  In JavaScript ES6

function findMaxProfitBuySellTwice(arr) {
  const [max1, a, b] = findMaxProfit(arr);

  return max1 + Math.max(findMaxProfit(arr.slice(0, a),
                         findMaxProfit(arr.slice(b + 1));
}

the a can be a + 1, while the b + 1 can be b, but with no use. The reason is let's say if you buy on day 6, then from day 5 to day 6, there will be no profit, or else the findMaxProfit() would have included day 5. Likewise, if findMaxProfit() says to sell on day 22, then from day 22 to 23, there is no profit, so we really don't need to start at day 22 but start at day 23.  slice() will return empty array if it is out of bound.

About the correctness of the code, because the Maximum Stock Profit Problem is interchangeable with the Maximum Subarray Problem. In fact, the number returned by the Maximum Stock Profit Problem and the number returned by the Maximum Subarray Problem should actually be exactly the same number.

So if we are asked to find the 2 subarrays that will add up to maximum, we could do the same as above: (1) find the maximum subarray first. (2) now slide this region out, and find the max for the remaining two regions. (3) just add up the max from step (1) and the maximum of the 2 numbers from step (2).

It seems the correctness of doing this to the Maximum Subarray Problem is more obvious: the 2 maximum subarrays are just finding the max first, and then disregard this region, and find the max of the remaining 2 sets of data.

Note that the Maximum Stock Profit Problem and the Maximum Subarray Problem should be able to convert to each other, say, from the stock problem to the subarray problem by taking the difference between the daily prices (resulting an array with size 1 less in general):

function convertStockDataToMaxSubarrayData(arr) {

  var maxSubarrayData = [], i;

  if (arr.length <= 1) return [];

  for (i = 1; i < arr.length; i++) {
    maxSubarrayData.push(arr[i] - arr[i-1]);
  }

  return maxSubarrayData;
}


texts:
I have a code that scrapes list of URL and appends dataframe as below:
from selenium import webdriver
import pandas as pd
from tabulate import tabulate
import os
os.chdir(r"C:\Users\harsh\Google Drive\sportsintel.shop\Files")
cwd = os.getcwd()
print(cwd)

browser = webdriver.Chrome()

browser.get("https://www.oddsportal.com/soccer/england/premier-league/results/")

df = pd.read_html(browser.page_source, header=0)[0]

dateList = []
gameList = []
scoreList = []
home_odds = []
draw_odds = []
away_odds = []

for row in df.itertuples():
    if not isinstance(row[1], str):
        continue
    elif ':' not in row[1]:
        date = row[1].split('-')[0]
        continue
    time = row[1]
    dateList.append(date)
    gameList.append(row[2])
    scoreList.append(row[3])
    home_odds.append(row[4])
    draw_odds.append(row[5])
    away_odds.append(row[6])

result_comp_1 = pd.DataFrame({'date': dateList,
                       'game': gameList,
                       'score': scoreList,
                       'Home': home_odds,
                       'Draw': draw_odds,
                       'Away': away_odds})

print(tabulate(result_comp_1))

browser.get("https://www.oddsportal.com/soccer/england/premier-league/results/#/page/2/")

df = pd.read_html(browser.page_source, header=0)[0]

dateList = []
gameList = []
scoreList = []
home_odds = []
draw_odds = []
away_odds = []

for row in df.itertuples():
    if not isinstance(row[1], str):
        continue
    elif ':' not in row[1]:
        date = row[1].split('-')[0]
        continue
    time = row[1]
    dateList.append(date)
    gameList.append(row[2])
    scoreList.append(row[3])
    home_odds.append(row[4])
    draw_odds.append(row[5])
    away_odds.append(row[6])

result_comp = pd.DataFrame({'date': dateList,
                       'game': gameList,
                       'score': scoreList,
                       'Home': home_odds,
                       'Draw': draw_odds,
                       'Away': away_odds})

new_df =result_comp_1.append(result_comp, ignore_index=True)

Can I make my code better to avoid redundancy?


texts: C++ Wrapper and Correctly Disposing Unmanaged Resources using ArrayHandle

texts:
I have the following class

public class ExrDepthMapExtractor : IDepthMapExtractor
{
    public RawDepthMap GetDepthMap(string filePath)
    {
        return DepthMapExtractorService.ExtractDepthMapAs1DArray(filePath, Callbacks.ProgressCallback);
    }
}

This calls the static C++ API wrapper

public static class DepthMapExtractorService
{
    [DllImport("Blundergat.OpenExr.Adapter.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.I1)]
    private static unsafe extern bool ExtractDepthMapAs1DArray(
        out ItemsSafeHandle vectorHandle,
        out double* points,
        out int width,
        out int height,
        string filePath,
        Callbacks.ProgressFunc progressCallback);

    [DllImport("Blundergat.OpenExr.Adapter.dll", CallingConvention = CallingConvention.Cdecl)]
    private static unsafe extern bool Release(IntPtr itemsHandle);

    public static unsafe RawDepthMap ExtractDepthMapAs1DArray(string filePath,
        Callbacks.ProgressFunc progressCallback)
    {
        using (InternalExtractDepthMapAs1DArrayWrapper(filePath, out RawDepthMap rdm, progressCallback))
        {
            rdm.Source = filePath;
            return rdm;
        }
    }

    private static unsafe ItemsSafeHandle InternalExtractDepthMapAs1DArrayWrapper(
        string filePath, out RawDepthMap rdm, Callbacks.ProgressFunc progressCallback)
    {
        double* pixels;
        int width, height;
        ItemsSafeHandle itemsHandle;

        if (!ExtractDepthMapAs1DArray(out itemsHandle, out pixels, out width, out height, filePath, progressCallback))
            throw new InvalidOperationException();

        var pixelList = new List<double>();
        for (int i = 0; i < width * height; i++)
            pixelList.Add(pixels[i]);

        rdm = new RawDepthMap()
        {
            Source = filePath,
            DepthMapArray = pixelList,
            Height = height,
            Width = width
        };

        return itemsHandle;
    }

    public class ItemsSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        public ItemsSafeHandle() : base(true) { }

        protected override bool ReleaseHandle()
        {
            return Release(handle);
        }
    }
}

In my C++ I Release the ArrayHandle as follows

#include "wrappers.h"

bool ExtractDepthMapAs1DArray(ArrayHandle* arrayHandle,
    double** pixels,
    int* width,
    int* height,
    const char* filePath,
    ProgressFunc progressCallback)
{
    try
    {
        auto v = new std::vector<double>();
        ExrDepthMapExtractor exrExtractor;
        *v = exrExtractor.extractDepthMap(filePath, *width, *height, progressCallback);

        *arrayHandle = reinterpret_cast<ArrayHandle>(v);
        *pixels = v->data();

        if (progressCallback != NULL)
        {
            std::string strFilePath(filePath);
            std::string message = "Extracted depth map from \"" + strFilePath + "\" successfully";
            if (progressCallback != NULL)
                progressCallback(message.c_str());
        }
        return true;
    }
    catch (...)
    {
        return false;
    }
}

bool Release(ArrayHandle arrayHandle)
{
    auto items = reinterpret_cast<std::vector<double>*>(arrayHandle);
    delete items;
    return true;
}

I have not used this before and the implementation was taken from [SO] (https://stackoverflow.com/questions/31417688/passing-a-vector-array-from-unmanaged-c-to-c-sharp), however, the way this is done does not look right to me and MSDN is different. The code seems to work fine with no memory leaks, but am I doing this the right way?


texts: Implementation of callback in database request

texts:
I am a complete beginner in JavaScript / Node.js / Express, but have some experience with php.

I am trying to pass data from a SQLite database to the console. In my previous attempts, console.log() was executed before the database got queried. Now I got it to work in the correct order with what I think is a callback, and I'm getting the data in the console.

Questions:

-Is this an actual callback?

-Is there a better (shorter / easier) way to "do this after that"?

-If I want to execute multiple functions in a certain order, would I want to end up with something like doThis(doThat(thenDoThis(finallyDoThat)));?

-If there's anything else about the code, feel free to review and comment.

// Some test code to get data from database

function getAllChampions(callback){
    db.all("SELECT * FROM champions", function(error, rows){
        if (error) console.log(error);
        return callback(error, rows);
    });
};

function showAllChampions(error, champions){
    if (error) console.log(error);
    else console.log('Champions: ' + JSON.stringify(champions));
};

getAllChampions(showAllChampions);


texts:
OK... last sort of the day and probably the most fun. F# is really awesome.

let rec quickSort list =
    match list with
    | [] -> []
    | [x] -> [x]
    | hd :: _ ->
        quickSort (List.filter (fun x -> x < hd) list) @ hd :: quickSort (List.filter (fun x -> x > hd) list)

[<EntryPoint>]
let main args =
    printfn "%s" (List.fold (fun acc x -> acc + " " + x.ToString()) "" (quickSort [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;]))
    0

let me know How I can improve this code. I am trying to think functionally and want my program to be most efficient, concise and functional.


texts: Shorten code that gathers files from directories

texts:
I have the following method in Ruby that appears to be just one line too long according to Ruby style guides. (Specifically: Rubocop tells me that my method has too many lines.)

Granted, I'm only one over the apparent allowed "limit" but in the interests of seeing if the style guides are realistic, I'm trying to adhere to them. Here is the method:

def spec_context
  spec_repo.map do |path|
    files_to_sort = []

    if File.directory?(path)
      spec_type.each do |type|
        files_to_sort << Dir["#{path}/**/*.#{type}"].sort
      end

      files_to_sort
    else
      []
    end
  end.flatten.uniq
end

The method essentially looks for any paths passed in, checks if there are files in those paths, and, if so, adds those files to an array (files_to_sort). If the path provided does not exist, an empty array is returned.

This is about as good as I can get this method. What I don't see is any way that I can shorten that to the Ruby style guidelines (10 lines) and still keep the contents nicely expressive.

Responding to a comment below, I wasn't clear at all about what spec_repo and spec_type are. Those are methods that get called which currently just return arrays:

def spec_repo
  %w(specs features stories)
end

def spec_type
  %w(spec feature story)
end

(I say "currently" because eventually the logic in those methods will be reading from a configuration setting.)

So the idea is to look over each directory that is listed as a repo and then, for each such directory, loop over each possible file type. (The file extensions being .spec, .feature, or .story.) If any files of the spec_type are found in any of the spec_repo directories, those are stored in the files_to_sort.


texts: Switching between ViewModels using IoC in a MVVM WPF application

texts:
I have a project that uses Caliburn.Micro to implement the MVVM pattern. For IoC, I am using MEF. All the ViewModels are marked with attribute [Export(typeof(IScreen))]. IScreen is defined in Caliburn.Micro.

In my BootStrapper file I have set up MEF like so:

private CompositionContainer container;

protected override void Configure()
{

    //Set up MEF

    container = new CompositionContainer(new AggregateCatalog``AssemblySource.Instance.Select``(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));

    var batch = new CompositionBatch();

    batch.AddExportedValue<IWindowManager>(new WindowManager());
    batch.AddExportedValue<IEventAggregator>(new EventAggregator());
    batch.AddExportedValue(container);
    container.Compose(batch);

    ...
}

Now, I show the first ViewModel using:

protected override void OnStartup(object sender, StartupEventArgs e) => DisplayRootViewFor<ViewModels.Main.MainViewModel>();

All that is fine and dandy. Now, the problem starts when I want to switch from one ViewModel to another.

An example of a ViewModel is:

[PartCreationPolicy(CreationPolicy.NonShared), Export(typeof(IScreen))]
sealed class SampleViewModel: ScreenVMwithUoW<IAddItemUoW>
{
    [ImportingConstructor]
    public SampleViewModel(IAddItemUoW uow, IEventAggregator eventAggregator) : base(uow, eventAggregator)
    {

    }

    ...
}

So far so good.

Let's say I want to open SampleViewModel and close my MainViewModel. How do I do it using MEF?

Here is what I am doing now. I am using ExportFactory of MEF. I have a class that holds a collection of ExportFactory, one for each IScreen.

[Export(typeof(IScreenFactory))]
class ScreenFactory : IScreenFactory
{
    private Dictionary<Type, ExportFactory<IScreen>> _screenDictionary { get;  set; }
    private IEnumerable<ExportFactory<IScreen>> _screenfactoryCollection { get; set; }
    private ExportLifetimeContext<IScreen> _currentScreenLifeTimeCtx { get; set; }

    [ImportingConstructor]
    public ScreenFactory([ImportMany(AllowRecomposition = true)] IEnumerable<ExportFactory<IScreen>> screenList)
    {
        _screenfactoryCollection = screenList;
        _reportfactoryCollection = reportsList;
    }

    public IScreen GetScreen(Type t)
    {
        if (_screenDictionary == null)
        {
            PopulateScreenDictionary(_screenfactoryCollection);
        }

        _currentScreenLifeTimeCtx = _screenDictionary[t].CreateExport();
        return _currentScreenLifeTimeCtx.Value;
    }

    private void PopulateScreenDictionary(IEnumerable<ExportFactory<IScreen>> screenfactories)
    {
        _screenDictionary = screenfactories.ToDictionary(c => c.CreateExport().Value.GetType(), c => c);
    }

    public void DisposeCurrentScreenContext()
    {
       _currentScreenLifeTimeCtx?.Dispose();
    }

    public void Dispose()
    {
        DisposeCurrentScreenContext();
    }
}

Whenever I need a new instance of a ViewModel, I just publish a message using the EventAggregator and the MainViewModel does this:

DeactivateItem(ActiveItem, true);
_vmFactory.DisposeCurrentScreenContext();
ActivateItem(_vmFactory.GetScreen(NextViewModelName));

This CANNOT be the normal way to do so. Also, this adds a huge hit in performance, especially the startup time of the application, when the number of ViewModels increase to about 25-30. That is because of how ExportFactory is messily implemented in the ScreenFactory class.

I would also like to avoid the Service Locator Pattern, if possible. I am also open to using a proper IoC Container instead of MEF, but MEF allows me to add ViewModels with very little effort. Just adding the annotation [Export(typeof(IScreen))] does the job.


texts:
I wrote some functions to compress and decompress a list of ints using Elias gamma encoding:
def _reverseBits(number: int) -> int:
    rev = 0
    while number:
        rev = rev << 1
        if number & 1:
            rev = rev ^ 1 # bitwise ^ 1 is faster than arithmetic + 1
        number = number >> 1
    return rev

def compress(numbers: List[int]) -> int:
    r'''Calculate the elias gamma encoded bitstream representation of the input list of numbers.

    >>> compress([5]) == 0b10100
    True
    >>> compress([15]) == 0b1111000
    True
    >>> compress([5, 15]) == 0b10100010100
    True
    '''
    bitstream = 0
    bitstream_length = 0
    previous_number = 0
    for number in numbers:
        delta = number - previous_number # store deltas, much smaller numbers
        N = delta.bit_length() - 1
        encoded_number = _reverseBits(delta) << N # reversed bitstream won't have leading zeroes problem in int container
        bitstream += encoded_number << bitstream_length
        bitstream_length += (N * 2 + 1)
        previous_number = number
    return bitstream

def decompress(bitstream: int) -> List[int]:
    r'''Convert the elias-encoded bitstream into a list of numbers.

    >>> decompress(0b10100010100)
    [5, 15]
    '''
    numbers = []
    cumulative_sum = 0
    while bitstream:
        N = 1
        while bitstream & 1 == 0: # count Elias leading zeroes
            bitstream = bitstream >> 1
            N += 1
        mask = (1 << N) - 1
        number = _reverseBits(bitstream & mask)
        number = number << N - number.bit_length()
        cumulative_sum += number
        numbers.append(cumulative_sum)
        bitstream = bitstream >> N
    return numbers

But it's very slow on huge input lists
start = 5000
size = int(4e6)
numbers = [i for i in range(start, start + size + 1)]

I started a test with a four-million size input list, all elements sequential, it took 13 minutes to encode and decode on my laptop.
I've thought about parallelising what I already have, but I don't think there's anywhere I can actually work it in.
Please could you help me review my algorithm and see if there are ways to improve or rework it to make my compress and decompress methods faster?
Or potentially, this might be the limit of Elias gamma encoding in Python...

I have also noticed a problem with mine, that memory does not seem to be freed after it finishes. tracemalloc.get_traced_memory() after running it shows a memory usage higher than the encoded int.

Elias gamma encoding encodes numbers like this
+--------+---------------+
| Number |  γ encoding   |
+--------+---------------+
|      1 |             1 |
|      2 |          0 10 |
|      3 |          0 11 |
|      4 |        00 100 |
|      5 |        00 101 |
|      6 |        00 110 |
|      7 |        00 111 |
|    ... |               |
|     15 |      000 1111 |
|     16 |   0000 1 0000 |
|    ... |               |
|     31 |   0000 1 1111 |
|     32 | 00000 10 0000 |

The leading zeroes inform the decoder how many of the following bits are part of the current number. So numbers of the input list are concatenated into a bitstream, and can be unambiguously decoded back into the same list of numbers. [1, 4, 3] encodes to 1 00100 011.
I am storing the bitstream in reverse inside of a python int, reversed so that there's no problems with the leading zeroes of the int container.
Even though the bit sequences in the table look large because of the leading zeroes, my compression only encodes the difference between the current list element and the previous (delta encoding), so that most of the time the number to encode and concatenate is much smaller than the actual list element.
My methods intentionally only work with sorted lists.


texts:
I am new to C. And I just want to know if my code is horrible or not. I tried to make program to delete all comments in C program. It's from "The C Programming Language Second Edition" book, Exercise 1-23.

Here is my solution :

#include <stdio.h>
#define MAXCHAR 1000
int c = 0;
int d = 0;
int newFileText[MAXCHAR];
int longDisable = 0;
int shortDisable = 0;
int i = 0;

//Function declarations
void printArray(int a[], int b);

void myputchar(int a[], int c);

int main(void) {
    while ((c = getchar()) != EOF) {
        if (i > MAXCHAR)i = 0;
        if (c == '/') {
            d = getchar();
            if (d == '/') shortDisable = 1;
            else if (d == '*') longDisable = 1;
        } else if (c == '*') {
            d = getchar();
            if (d == '/') {
                c = getchar();
                if (!(c > 0)) {
                    break;
                }
                longDisable = 0;
            }
        } else if (c == '\n') {
            shortDisable = 0;
        }
        if (shortDisable || longDisable);
        else {
            myputchar(newFileText, c);
            i++;
        }
        /*printf("\nShort disable: %d", shortDisable);
        printf("\nLong disable: %d", longDisable);*/
    }
    printArray(newFileText, i);
    return 0;
}

void printArray(int theArray[], int lengthSoFar) {
    for (int i = 0; i < lengthSoFar; i++) {
        printf("%c", theArray[i]);
    }
}

void myputchar(int a[], int c) {
    int i = 0;
    while (a[i] != '\0') {
        i++;
    }
    a[i] = c;
}


texts: Find the minimum number of operations (concat, add and subtract) for the numbers 1-9 to equal 100

texts:
I am beginning to learn Scala and functional programming, and I came across this puzzle.

This looked like good practice and I have a solution but just want some hints in terms of functional approach to this. I did rip off the evaluate function from Stack Overflow.

I particularly am interested in if the approach of creating 3 function and creating a function in the main solve routine is considered a good approach.

def gchq(): Int = {
  def solve(total: String, currentValue: Int, f: (String, Int) => String): Int = {

    val newtotal: String = f(total, currentValue)

    if (currentValue == 9 && evaluate(newtotal.split("\\s").toList) == 100) {
      print("SOLUTION: ")
      println(newtotal + "/" + currentValue)
      1
    }
    else if (currentValue == 9) 0
    else {
      solve(newtotal, currentValue + 1, concat)
      solve(newtotal, currentValue + 1, minus)
      solve(newtotal, currentValue + 1, plus)
    }
  }

  solve("0", 1, concat)
}

def plus(a: String, b: Int): String = {
  a + " + " + b
}

def minus(a: String, b: Int): String = {
  a + " - " + b
}
def concat(a: String, b: Int): String = {
  "" + a + b
}

//this function is taken off stackoverflow
def evaluate(expression: List[String]): Int = expression match {
  case l :: "+" :: r :: rest => evaluate((l.toInt + r.toInt).toString :: rest)
  case l :: "-" :: r :: rest => evaluate((l.toInt - r.toInt).toString :: rest)
  case value :: Nil => value.toInt
}
gchq()


texts: Count the number of unique elements in a sorted array

texts:
Write a method named numUnique that accepts a sorted array of integers as a parameter and that returns the number of unique values in the array. The array is guaranteed to be in sorted order, which means that duplicates will be grouped together.

I'm mainly concerned with following proper conventions and maximizing readability; both of which I feel I know little about. In the last question I posted, I learned a bit about structuring if-statements. How can I think about these statements so that it's easier for me to write them, as well as easier for others to read them? Is there a sort of PEMDAS of programming logic that would help me understand writing conditional code with precedence? Any feedback is appreciated!

public static int numUnique(int[] array){
    if(array.length > 0){
        int countUnique = 1;
        for(int i = 0; i < array.length - 1; i++){
            if(array[i] != array[i+1]){
                countUnique++;
            }
        }
        return countUnique;
    } else {
        return 0;
    }
}


texts: Vectorizing a complex nested for loop in R (running models on different subsets of a data set, subsetting the data differently for each loop)

texts:
This is my first time posting so hopefully I manage to get my question across in a clear and concise manner. I'm not sure this is the right place but someone on StackOverflow suggested I ask here.

I am running a cross-validation experiment which involves training a model on a subset of a data set and then validating it against the rest of the data set. This is done by randomly subsetting the data into "folds" and then running the model for each fold. This is then replicated in order to produce standard errors. This is the code I have written in R:

reps = 10
folds = 10
rep.Res<-list()

for(i in 1:reps){
  #i=1
  phen2<-phen
  phen2$fold<-sample(1:folds,nrow(phen),replace=T)

  fold.Res<-list()

  for(j in 1:folds){
    #j=1

    print(paste(i," ",j))

    phen3<-phen2
    phen3[which(phen3$fold==j),2]<-NA

    ETA<-list(list(X = geno_centred, model = 'BayesA'))

    model <- BGLR(y = phen3[,2], ETA = ETA, nIter = 20000,
                  burnIn = 1500,  thin=10)

    model.output<-data.frame(ID = phen3[which(phen2$fold == j), 1],
                             PBV = as.numeric(model$yHat[which(phen2$fold == j)]),
                             phen = phen2[which(phen2$fold == j), 2], rep = i, fold = j)

fold.Res[[j]]<-model.output

  }

  rep.Res[[i]]<-do.call(rbind,fold.Res)

}

"phen" is a data frame with a a column of IDs and a column of values. For each replicate, each sample is assigned to a fold randomly. Then, for each fold individuals in the fold are given an NA value, i.e. excluded from the model.

The model is run using the Bayesian Generalised Linear Regression (BGLR) package. Unfortunately, I can't really give a reproducible example. X is a scaled centred genotype matrix of -1's, 0's and 1's (not critical for my problem here). The output of the model is then written out for each fold, and then finally for each replicate.

My question is, is it possible to vectorize these loops? Using 10 folds and 10 reps means that the model runs 100 time, at 20 000 MCMC iterations each time. This causes the system to slow down significantly before it's even half done. I know that there are many possible approaches using basic R or packages in the tidyverse suite, but I am really a bit lost with such a complex loop. I can imagine that I would try to write at least one of the loops into a function enclosing the other loop but I'm not even sure how that would work...

Again, first time posting so please let me know if I need to add anything to my question! Thanks!

Edit: Here are a small, random centred genotype matrix (X in the call to BGLR) and an accompanying phen file.

X (rows are sample IDs matching those in phen, columns are genomic locations (SNPs)):

    A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T
1   1  1  1 -1 -1  0 -1 -1  0  1 -1  0  0  0  0 -1  0  0  1  1
2  -1  1  0 -1  0  0  1 -1  1  0 -1  1 -1  0  0  0 -1 -1 -1 -1
3  -1 -1  1 -1  0  0  1  0  0 -1 -1  0 -1  0  0 -1  1 -1  0 -1
4   0  0 -1  1 -1  0 -1  1  1  1 -1  0  0  0  1  1 -1 -1  0  1
5   1  0  1  1  0  0  1  1  0  0 -1  1  1  1  1 -1 -1  0 -1  0
6   1 -1 -1  0  1 -1  1  1  1 -1  0  0  0 -1  0  1  0 -1 -1  0
7   1 -1 -1  1  1  0 -1  1 -1  1  0 -1  1  1 -1 -1 -1  1 -1  1
8   0  1  0  1 -1 -1  0 -1 -1 -1  1 -1  0  0  0  0  0 -1  0 -1
9  -1  1 -1 -1  1  0  0  0  0  0  1  0 -1 -1 -1  0  1 -1  0 -1
10  0  0 -1  1  0  0 -1  0 -1  1  1  1  0  0  1  1  0 -1  0  0

Phen:

ID  phenotype
1   1000
2   1500
3   1200
4   500
5   700
6   2000
7   1500
8   1000
9   1300
10  900


texts:
I've written a function which can get the environment variable's value. The input parameter would one of the following:

${machine}/bin
${machine/bin}
${machine}/bin${path${OS}}/path

I would need to check the values which start with ${}

I've written a function which is recursive in nature, and I would appreciate it if anyone can review the code for me and tell me what can be done better:

private String replaceWithEnvironmentVariables(String specialChars) {
    String result="";
    boolean flag=true;
    try{
        result = specialChars;
        String temp = "";
        char loopBreaker = '}';
        char dollarCheck = '$';
        char slashCheck = '/';
        int index = result.indexOf("{");
        if (index == -1){
            result = result.replaceAll("[{},$]", "");
            return result;
        }
        for (int i = index; i < result.length(); i++) {
            if(slashCheck==result.charAt(i))
                break;
            temp += result.charAt(i);
            if(dollarCheck==result.charAt(i) || loopBreaker==result.charAt(i)){
                break;
            }
        }
        String sub = temp.replaceAll("[{},$/]", "");
        if(sub==null || sub.length()==0){
            sub="";
            flag=false;
            result = result.replace(temp, sub);
        }
        if(flag){
            String returnSub = getEnvironmentVariableValue(sub);
            result = result.replace(temp, returnSub);
        }
    }catch(NullPointerException nullPointer){
        nullPointer.printStackTrace();
    }catch(Exception except){
        except.printStackTrace();
    }
    return replaceWithEnvironmentVariables(result);
}


texts:
I want to read a vector of eight bytes, convert them into hexadecimal, store them in a std::string and finally write them into a binary file.
I am looking for suggestions and recommendations to improve the efficiency and readability of the code.
#include <vector>
#include <string_view>
#include <iostream>
#include <fstream>
#include <cassert>

std::string hexify(std::vector<unsigned char> const & v) {

std::string str(2 * v.size(), 'x');
auto k = str.begin();

for(auto i{v.begin()}; i < v.end(); ++i) {
    *k++ = "0123456789ABCDEF"[*i >> 4];
    *k++ = "0123456789ABCDEF"[*i & 0x0F];
}
return str;

}

void writeFile(std::string_view str, std::string strToRead) {

assert(str.data() != nullptr);
std::ofstream f(str.data(), std::ios::binary);

if(f.is_open()) {
    f << strToRead;
}
f.close();
}

int main() {

std::vector<unsigned char> const v{'5', '1', '5', '7', '9'};
writeFile("text.bin", hexify(v));
}


texts:
I am just starting out in my Clojure journey and I wonder if anybody can point out my beginners mistakes in my function below that simply reverses a list.  I know that there is already a reverse function so this is purely for learning.

(defn rev
  ([l]
   (if (= (count l) 1) l (rev '() l)))
  ([l orig]
   (if (= (count orig) 0)
     l
     (rev (conj l (first orig)) (rest orig)))))

In my defence, it does work, but what I am finding myself doing a lot in Clojure is overloading the arguments list to take into account when I need a working list like in this example where I conj new items onto.


texts:
This is a teaching sample intended to illustrate use of mutability and list consing in F#.  The structure is intended to be a thread-safe stack structure, which multiple threads can push to/pop from concurrently.  Concerns:

Will this actually be thread safe?
Are the locks necessary?
Is there an immutable way to do the same thing?  I don't think one can use the traditional immutable method here of having the Push/Pop return a new stack instance because different clients will see divergent views of the stack.

The code looks like this:

type ConcurrentStack<'T>() =
    let mutable _stack : List<'T> = []

    member this.Push value =
      lock _stack (fun () ->
         _stack <- value :: _stack)

    member this.TryPop() =
      lock _stack (fun () ->
         match _stack with
         | result :: newStack ->
            _stack <- newStack
            result |> Some
         | [] -> None
      )


texts: Laravel Controller function to return view based on user permission

texts:
I have one route that switches the routes based on the permission the user has. Here is a little example:

public function show(Company $company)
{
    if(auth()->user()->hasPermission('read-companies')) {
        return view('portal.company.showAdmin', compact('company'));
    } elseif (auth()->user()->hasPermission('read-company') && auth()->user()->companies->contains($company)) {
        return view('portal.company.showEntrepreneur', compact('company'));
    } elseif(auth()->user()->hasPermission('read-companies_v') && $company->visible()) {
        return view('portal.company.showTrainee', compact('company'));
    } else {
        abort('403');
    }
}

This basicly returns to 3 views based on the permissions of the user. A lot of my controller functions look like this. Now my question: Is this "One controller/route for multiple actions" approach a bad Idea? What if I want to add a role to the auth()->user()->companies->contains($company) many to many relationship? I would need to add all my controller functions. Is it better to have a function on the user model like IsAbleToShowOnCompany($company)? But than I would have houndreads of functions like that, because, e.g., Companys can create pokes, and I would need to check if the role of the many to many relation to company would allow that.

Do you have any refactor Ideas?

I've heard about service and repository classes, but how can I refactor this into a servivce?


texts: Noughts and Crosses winner declaration in a game of variable square board size

texts:
I have made a tic tac toe for two players and written down some functions to do the decision making about who is the winner. I have gone through some cases while testing but need advice to see if I am in the right track and also if all the winning positions are being taken care of.
I would like to know even if this can be simplified.

Here:
$state = ["&#10008;","-","-","-","-","&#10008;","-","-","-","-","&#10008;","-","-","-","-","&#10008;"]

The function is for grids starting from 3X3 to 7X7.

PHP

function whoIsWinning($state)
{
    $n = sqrt(count($state));
    $rows = $this->isWin($state, $this->genPaths($n, 0,     1,      $n, $n));
    $cols = $this->isWin($state, $this->genPaths($n, 0,     $n,     1,  $n));
    $diUp = $this->isWin($state, $this->genPaths(1, $n-1,  $n-1,   0,  $n));
    $diDn = $this->isWin($state, $this->genPaths(1,  0,     $n+1,   0,  $n));

    if ($rows !== '-') return $rows;
    if ($cols !== '-') return $cols;
    if ($diUp !== '-') return $diUp;
    return $diDn;
}

/**
 * Function to generate the paths to win
 * @param $count
 * @param $start
 * @param $incrementA
 * @param $incrementB
 * @param $lengthToWin
 * @return array
 */
function genPaths($count, $start, $incrementA, $incrementB, $lengthToWin)
{
    $paths = [];
    if($lengthToWin > 3) {
        $lengthToWin = $lengthToWin - 1;
    }
    for ($i = 0; $i < $count; $i++) {
        $path = [];
        for($j = 0; $j < $lengthToWin; $j++) {
            array_push($path, $start + $i * $incrementB + $j * $incrementA);
        }
        array_push($paths, $path);
    }
    return $paths;
}

/**
 * @param $state
 * @param $paths
 * @return string
 */
function isWin($state, $paths)
{
    for ($i = 0; $i < count($paths); $i++) {
        $currentPathResult = $this->isPathWin($state, $paths[$i]);
        if ($currentPathResult != '-')
            return $currentPathResult;
    }
    return '-';
}

/**
 * @param $state
 * @param $path
 * @return string
 */
function isPathWin($state, $path)
{
    $first = $state[$path[0]];
    for ($j = 1; $j < count($path); $j++) {
        $compareToFirst = $state[$path[$j]];
        if ($compareToFirst != $first)
            return '-';
    }
    return $first;
}


texts:
I need to improve performance for query

DECLARE @Take INT, @WhatSearch NVARCHAR(MAX);
SET @WhatSearch = '%' + @WhatSearch + '%';

WITH [PublicNewsFilter] AS
(
    SELECT DISTINCT
        [N].[Title],
        ROW_NUMBER() OVER (ORDER BY [N].[Title]) AS [RowNumber]
    FROM [dbo].[News] [N] WITH(NOLOCK)
    WHERE ([N].[Title] LIKE @WhatSearch) OR ([N].[Description] LIKE @WhatSearch)
)
SELECT [Title]
FROM [PublicNewsFilter]
WHERE [RowNumber] <= @Take
ORDER BY [RowNumber];

Here I'm trying to get only X records ( @Take ) where Title or Description is like search text ( @WhatSearch ).

What do you think about performance and how can I improve it?

Will it more performance to use:

SELECT DISTINCT TOP (@Take) [N].[Title]
FROM [dbo].[News] [N] WITH(NOLOCK)
WHERE ([N].[Title] LIKE @WhatSearch) OR ([N].[Description] LIKE @WhatSearch)


texts: Property to compare in Linq is different by criteria.

texts:
I feel like repeating myself but i don't know how to refactor this.
Linq condition is the same but property to compare is different
(BookingDate ,CheckInDate ,CheckOutDate)

    protected void FilterByDateRange(ref IEnumerable<ViewBooking> pObjListBooking)
    {
        DateTime startDate;
        DateTime endDate;

        startDate = DateTime.ParseExact(txtStartDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture);
        endDate = DateTime.ParseExact(txtEndDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture).AddDays(1);

        switch(ddlOrderBy.Text)
        {
            case "Booking Date":
                pObjListBooking = pObjListBooking.Where(item => item.BookingDate >= startDate && item.BookingDate < endDate);
            break;

            case "Check In Date":
                 pObjListBooking = pObjListBooking.Where(item => item.CheckInDate >= startDate && item.CheckInDate < endDate);
           break;

            case "Check Out Date":
                pObjListBooking = pObjListBooking.Where(item => item.CheckOutDate >= startDate && item.CheckOutDate < endDate);
            break;
        }
    }


texts:
I'm new to algorithms. To be honest I am not really sure if my implementation is right. However, the output is sorted correctly in ascending order so perhaps it's correct. Please feel free to give critiques and suggest how to improve its overall efficiency.

How can improve its performance and readability?
Have I used bad practice?
Did I implement the algorithm correctly?

Main.cpp
#include <vector>
#include <iostream>
using namespace std;
void sort(vector<int> & bar);
void mergeSort(vector<int>&left,vector<int>& right,vector<int>& bars);

int main() {
    vector<int> nums;
    for (size_t i = 0; i < 11; i++)
        nums.push_back(rand() % 1000);

    sort(nums);

    for (size_t i = 0; i < nums.size(); i++)
        cout << nums[i] <<endl;
    system("pause");
    return 1;
}
void sort(vector<int> & bar) {
    if (bar.size() <= 1) return;

    int mid = bar.size() / 2;
    vector<int> left;
    vector<int> right;

    for (size_t j = 0; j < mid;j++)
        left.push_back(bar[j]);
    for (size_t j = 0; j < (bar.size()) - mid; j++)
        right.push_back(bar[mid + j]);

    sort(left);
    sort(right);
    mergeSort(left, right, bar);
}
void mergeSort(vector<int>&left, vector<int>& right, vector<int>& bars)
{
    int nL = left.size();
    int nR = right.size();
    int i = 0, j = 0, k = 0;

    while (j < nL && k < nR)
    {
        if (left[j] < right[k]) {
            bars[i] = left[j];
            j++;
        }
        else {
            bars[i] = right[k];
            k++;
        }
        i++;
    }
    while (j < nL) {
        bars[i] = left[j];
        j++; i++;
    }
    while (k < nR) {
        bars[i] = right[k];
        k++; i++;
    }
}

Output


texts: Calls one column of a dataframe, turns it into an array and plots it

texts:
My code calls 1 column of a dataframe, turns it into an array and plots it.
I want to able to do this for all the columns without having to repeat the code many times.

How can I do this?

#Code to create fake data
df = pd.DataFrame(np.random.rand(10,5), columns=list('abcde'),
     index=list('nopqrstuvw'))
df.columns.name = 'level_0'
df.index.name = 'level_1'

#I load an array of shape (10, 2)
sensors_pos = sio.loadmat('/home/Coord_Slp_2D.mat')['Cor']

# I extract column "a"
df1=df['Total Acc'].round(4)*100
df2=df1.reset_index().pivot('level_1', 'level_0', 'Total Acc')

df3=df2['a'].reset_index() #extracts the column "a"

#Turns column "a" into an array
data=df3['a'].values

#Plots column "a"
fig = plt.figure(figsize = (8,5))
ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False)
plt.title('a')
fig.colorbar(ax)
fig.show()

#------------------------------
#This is where the repetition starts. I will have to do this for each column

 # I extract column "b"

df4=df2['b'].reset_index() #extracts the column "b"

#Turns column "b" into an array
data=df3['b'].values

#Plots column "b"
fig = plt.figure(figsize = (8,5))
ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False)
plt.title('b')
fig.colorbar(ax)
fig.show()


texts: Laravel function to add a supplier, and associated addresses and contacts

texts:
I have a function addSupplier() that adds a supplier. Each supplier has multiple addresses and each address has multiple contacts.

public function addSupplier ($request) {
        // ADDING THE SUPPLIER BASIC INFO
        $supplier_fillable_values = array_merge(
            $request -> except('address_contact_inputs'),
            ['created_by' => $this->getAuthUserId()]
        );
        $new_supplier = Supplier::create($supplier_fillable_values);

        // ADDING THE SUPPLIER ADDRESSES AND THE ADDRESS CONTACTS
        foreach ($request -> address_contact_inputs as $address) {
            // ADD ADDRESS
            $new_supplier_address = $new_supplier -> addresses() -> create([
                'address'       => $address['address'],
                'created_by'    => $this -> getAuthUserId()
            ]);

            // ADD ADDRESS CONTACTS
            foreach ($address['contacts'] as $contact)
                $new_supplier_address -> contacts() -> create([
                    'name'          => $contact['name'],
                    'phone_number'  => $contact['phone_number'],
                    'created_by'    => $this -> getAuthUserId()
                ]);
        }

        return $request -> address_contact_inputs;
    }

Everything works fine but question is: Is this the best practice or I should use events and create an event for:

Storing the supplier basic info
Storing the supplier addresses
Storing contact for each supplier's address


texts: Optimizing the performance of html5 video manipulation

texts:
I've been working on an html5 canvas video player with a lot of fun little extras and ui toys, the main one being a chroma key (green screen) effect that allows the user to key out different colors or ranges of color while the video is playing.

I seem to have hit a snag in the recommended chroma key method. It works, but it is a really heavy process and can tax the cpu to the point where the video will look choppy if the user is running other applications in the background.

Here is the stripped down code I'm using for the chroma key effect:

   <video id="sourceVid" controls="true">
        <source src="http://s3.amazonaws.com/dfc_attachments/public/documents/3185373/AAA.webm" />
    </video>
    <canvas id="hCanvas"></canvas>
    <canvas id="dCanvas"></canvas>

    <script type="text/javascript">
        var doc = document;
        var sourceVid = doc.getElementById("sourceVid");
        var hCanvas = doc.getElementById("hCanvas");
        var dCanvas = doc.getElementById("dCanvas");
        var hContext = hCanvas.getContext("2d");
        var dContext = dCanvas.getContext("2d");

                    sourceVid.addEventListener('loadeddata', function() {
                        hCanvas.setAttribute('width', sourceVid.offsetWidth);
                        dCanvas.setAttribute('width', sourceVid.offsetWidth);
                        hCanvas.setAttribute('height', sourceVid.offsetHeight);
                        dCanvas.setAttribute('height', sourceVid.offsetHeight);
                    }, false);

        sourceVid.addEventListener('play', function() {
            runAnalysis();
        });

        var runAnalysis = function() {
            if (sourceVid.paused || sourceVid.ended) {
                return
            }
            frameFix();
            if (window.requestAnimationFrame) {
                requestAnimationFrame(runAnalysis);
            } else {
                setTimeout(runAnalysis, 0);
            }
        };

        var frameFix = function() {

            hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);

            var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight);

            var length = frame.data.length;
            for (var i = 0; i < length; i++) {
                var r = frame.data[i * 4 + 0];
                var g = frame.data[i * 4 + 1];
                var b = frame.data[i * 4 + 2];

                if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {
                    frame.data[i * 4 + 3] = 0;
                }
            }
            dContext.putImageData(frame, 0, 0);
            return
        };

Live Demo

Hoping to find ways to further optimize this for performance.


texts: Best practice for multiple conditional HTML options with similar code blocks

texts:
So I'm pretty new to HTML/Angular and frontend tech in general. I'll include my code below, but as you'll see there's a LOT of commonality between the switch cases, what I'd like to try do is have this on as few lines as possible, the only difference really is the icons which display something different depending on the switch condition,
   <ng-container>

      {{ header }}

            {{ data.evaluation }}

            {{ data.evaluation }}

            {{ data.evaluation }}

            {{ data.evaluation }}

            {{ data.evaluation }}

            {{ data.evaluation }}

          -

  </ng-container>

Is there a best practice I should be following here because I feel like this is a very cowboy way of doing it?


texts: Merge two lists in Java and sort them using Object property and another condition

texts:
I have two lists List<Person> list1 = new ArrayList(), list2 = new ArrayList(); (Not the same size), of the class Person:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" + "name=" + name + ", age=" + age + '}';
    }

}

I want to create a new list using list1 and list2 sorted by age (descending), but I also another condition that is better explained with an example:

//L1 = from list1, L2 = from list2
//looping trough the new list
Person{name=Alec L1, age=75}
Person{name=Menard L1, age=50} //Bob should be here
Person{name=Bob L2, age=50}

He should, because his age is equal to Menard, Alec is from L1 and two Person from L1 can't be one after another is this kind of situation happens.

A complete list should look like this:

Person{name=Giant L2, age=100}
Person{name=Derp L1, age=50}
Person{name=John L2, age=50}
Person{name=Menard L1, age=44}
Person{name=Lili L2, age=44}
Person{name=Lili L1, age=44}
Person{name=Menard L2, age=44}
Person{name=Bob L1, age=22}
Person{name=Alec L2, age=21}
Person{name=Alec L1, age=21}
Person{name=Herp L2, age=21}
Person{name=Herp L1, age=21}
Person{name=Alice L1, age=12}
Person{name=Little L2, age=5}

Here is my complete code to achieve this result:

    List<Person> list1 = new ArrayList(), list2 = new ArrayList();

    list1.add(new Person("Derp L1", 50));
    list1.add(new Person("Alec L1", 21));
    list1.add(new Person("Herp L1", 21));
    list1.add(new Person("Menard L1", 44));
    list1.add(new Person("Lili L1", 44));
    list1.add(new Person("Alice L1", 12));
    list1.add(new Person("Bob L1", 22));

    Collections.sort(list1, new Comparator<Person>() {
        @Override
        public int compare(final Person object1, final Person object2) {
            return object2.getAge()-object1.getAge();
        }
    });

    list2.add(new Person("Little L2", 5));
    list2.add(new Person("Lili L2", 44));
    list2.add(new Person("Alec L2", 21));
    list2.add(new Person("Herp L2", 21));
    list2.add(new Person("Menard L2", 44));
    list2.add(new Person("Giant L2", 100));
    list2.add(new Person("John L2", 50));

    Collections.sort(list2, new Comparator<Person>() {
        @Override
        public int compare(final Person object1, final Person object2) {
            return object2.getAge()-object1.getAge();
        }
    });
    List<Person> allList = new ArrayList();
    int l1 = 0, l2 = 0;
    for (int i = 0; i < list1.size()+list2.size(); i++)
        if (l1 < list1.size() && l2 < list2.size())
            if (list1.get(l1).getAge() > list2.get(l2).getAge())
                allList.add(list1.get(l1++));
            else if (list1.get(l1).getAge() < list2.get(l2).getAge())
                allList.add(list2.get(l2++));
            else if (allList.size() > 0)
            {
                if (list1.get(l1).getName().contains("L1") == allList.get(allList.size()-1).getName().contains("L1"))
                    allList.add(list2.get(l2++));
                else
                    allList.add(list1.get(l1++));
            }
            else
                allList.add(list1.get(l1++));
        else if (list1.size() == l1)
            allList.add(list2.get(l2++));
        else
            allList.add(list1.get(l1++));

    for (Person person : allList)
        System.out.println(person.toString());

But, is there another way to do it? More elegant code or using some built in Java class?


texts: Validate a string for positive number and normal string

texts:
I have a method in which I am accepting a String clientid and that has below requirements:

clientid can be a positive number greater than zero. But if it is negative number or zero, then throw IllegalArgumentException with a message.
clientid cannot be a null or empty string. But if it is, then throw IllegalArgumentExceptionwith a message.
clientid can be a normal string as well. For example - it can be abcdefgh or any other string.

import static com.google.common.base.Preconditions.checkArgument;

public Builder setClientId(String clientid) {
    checkArgument(!Strings.isNullOrEmpty(clientid), "clientid cannot not be null or an empty string, found '%s'.",
            clientid);
    try {
        final long id = Long.parseLong(clientid);
        checkArgument(id > 0, "clientid must not be negative or zero, found '%s'.", clientid);
    } catch (NumberFormatException e) {}
    this.clientid = clientid;
    return this;
}

I cannot use Guava library greater than 11 so I cannot use Longs.tryParse method here so just using normal ugly way of parsing string. Is there anything I can improve here which is without try catch block? Anything from Apache Commons?


texts:
I'm new to VBA and am trying to write a macro to move data from an exported file to an excel template. The code below works, however I have to add many more ranges of data and am worried it will be hefty to run.

Sub MoveData()

    Dim fileName As String
        Sheets("Cover").Select                                  '
        range("B5").Select
        fileName = Selection.Value
    Dim path As String
        path = "C:\Users\(name)\Documents\(folder)\" & fileName & ".csv"

    Dim currentWB As Workbook
    Set currentWB = ThisWorkbook

    Dim openWB As Workbook
    Set openWB = Workbooks.Open(path)

    Dim openWs As Worksheet
    Set openWs = openWB.Sheets(fileName)

    openWs.range("C2:C51").Copy
    openWB.Close (False)
    currentWB.Worksheets("Bms").Activate
    range("C7:C56").Select
    ActiveSheet.Paste

End Sub

I took the base code from here(the closed section) and modified it to fit my needs. The file I am extracting data from will change, but will always be in the same folder, which is why I set up the path as such. I am moving the data from C2 and downwards to C7-down on the template. C56 is currently the last used cell on the template, however that is subject to change so I would prefer to get rid of the lower bound.

If there is a better way to write this, I would love some input. Since I'm still new at this, if you could explain your code as well, that would be very beneficial.


texts:
To detect int overflow/underflow in C, I use this code. What might be a simpler and more portable way of coding this (that is, fewer conditions)?

Assume 2's complement and don't use wider integers.

int a,b,sum;
sum = a + b;
// out-of-range only possible when the signs are the same.
if ((a < 0) == (b < 0)) {
  if (a < 0) {
    // Underflow here means the result is excessively negative.
    if (sum > b) UnderflowDetected();
  }
  else {
    if (sum < b) OverflowDetected();
  }


texts: Linq query performs poor according to performance analyzer in VS2012

texts:
I've a Linq query that performs poorly:

var minuteValues = ValuesInMemory.Where(o => o.Key.Day == tmpValue.QuoteDate.Day &&
                                  o.Key.Hour == tmpValue.QuoteDate.Hour &&
                                  o.Key.Minute == tmpValue.QuoteDate.Minute &&
                                  o.Key.Second >= 0).Select(p => p.Value).ToList();

Is there a way to do this better?

private readonly ConcurrentDictionary<DateTime, double> ValuesInMemory = new ConcurrentDictionary<DateTime, double>();

ValuesInMemory holds about 6700 records 24/7. Every second records are added and every 2 hours the oldest values are stored in SQL Server. But the average amount of values is 6700.


texts: Working React App to display public Github Repositories of a user

texts:
Description of the App:-

A React app that shows the public Github repositories of a user.
The app shows an input field where we can enter a Github username and a submit button. {It provides users the feedback while getting the data in the background.}
The repositories are shown as a list and for each repo, the following information is displayed: Repository name, the number of stars, and forks.
Each Repository item in the list is made clickable. It opens the repository on Github when clicked.
A reset button is provided to clear the repository list
A username can be provided as a URL parameter while opening the application and automatically show the users repositories

Tech Stack:-
React (hooks),
Redux,
Cypress (For Testing)
Material UI,
AG-Grid
The Github README.md file has all the instructions on how to run the project.
I will appreciate it if the app can be reviewed.
What I am looking for is the following?

Variable, functions, Component Naming Convention.
Commit Messages format.
Good coding practices are followed or not?
Inputs and Feedback if code needs some optimization.
Directory/Folder Structure.

Please feel free to provide comments generously. I am trying to improve my coding skills and this app is a step towards that.
Disclaimer:-  Kindly use the Github link to review the code. That will give a clear idea of the directory structure, readme file, and other important aspects of the app.
GitHub Link
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Login from '../components/Login';
import DisplayRepo from '../components/DisplayRepo';
import PageNotFound from '../components/PageNotFound';
import { Box } from '@material-ui/core';
import { useStyles } from '../styles/components/login.js';

const Approutes = (props) => {
    const classes = useStyles(props);
    return (
        <BrowserRouter>
            <Box className={classes.mainContainer}>
                <Switch>
                    <Route path='/' component={Login} exact={true} />
                    <Route
                        path='/displayuserrepo/:uname'
                        component={DisplayRepo}
                        strict
                        exact={true}
                    />
                    <Route path='/*' component={PageNotFound} strict exact={true} />
                </Switch>
            </Box>
        </BrowserRouter>
    );
};

export default Approutes;


texts: Controller scope inside Directive with Angular

texts:
I decided to write a simple runnable example to try and express my concern:

index.html

      <prize-directive ng-repeat="prize in prizes"></prize-directive>

Inside my shopController I have set a static prize list just for the purpose of keeping it simple.

ShopController.js

angular.module('app.controllers').controller('ShopController',
   ['PrizeService', '$scope', function (PrizeService, $scope) {

    $scope.prizes = [
      {name: 'First Prize', cost: 10,
         image: 'upload/prize/image1.png', note: 'This is a note'},
      {name: 'Second Prize', cost: 20,
         image: 'upload/prize/image2.png', note: 'This is a note'},
      {name: 'Third Prize', cost: 30,
         image: 'upload/prize/image3.png', note: 'This is a note'}
    ];

    $scope.reclaim = function (prize) {
      console.log(prize);
    };
}]);

In the original code I use the PrizeService to load a list of available prizes, but back to my main problem:

PrizeDirective

angular.module('app.directives').directive('prizeDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'js/directives/PrizeDirective.html'
  };
});

HTML:

{{prize.name}}

    Pontos: {{prize.cost}}

{{prize.note}}

<reclaim-directive></reclaim-directive>

Here in the HTML portion of the directive, I'm using a variable name that was defined in the index.html. Although it bothers me, I'm willing to let it go because the variable name was defined inside the ng-repeat code, which is inside the prize-directive directive. But when we go to the reclaim-directive, things get a little bit more heated:

angular.module('app.directives').directive('reclaimDirective', function () {
  return {
    restrict: 'E',
    template: '<button ng-click="reclaim(prize)">Resgatar</button>'
  };
});

Note: I'm actually using the templateUrl here, but again, I'm simplifying it just to show my point.

Now I'm using a function name defined inside ShopController in the Reclaim Directive. Differently from OOP, this is not really an inheritance of an abstract method which even the IDE can tell you that something is wrong and, to me, it seems like a bad practice.

I would love to hear people's thoughts on this approach and if there is anything that I'm missing that could help clean up this code.


texts: Convert decimal to binary and vice-versa in Java

texts:
I'm trying to learn Java, so I'm doing a few exercises from a programmer project idea book. This exercise requires that the program be able to convert a decimal number to binary and vice versa, like so:

Please enter the binary/decimal number to convert:9783569
100101010100100100010001

Please enter the binary/decimal number to convert:100101010100100100010001
9783569

Here's the code I came up with:

import java.util.Scanner;

public class BinaryToDecimalAndBackConverter{

    static String convertDecimalToBinary(String decimal){
            int integer = Integer.valueOf(decimal);
            String result = new String();

            while(integer > 0){
                result+=String.valueOf(integer%2);
                integer/=2;
            }

            result = new StringBuffer(result).reverse().toString();
            return result;
    }
    static int convertBinaryToDecimal(String binary){
            int result = 0;

            for(int reverseCounter = 0; reverseCounter < binary.length(); reverseCounter++){
                char currentChar = binary.charAt(binary.length() - reverseCounter - 1);
                int numericValue = Character.getNumericValue(currentChar);
                result+=Math.pow(2, reverseCounter) * numericValue;
//              System.out.println(Math.pow(2, reverseCounter) * Character.getNumericValue(binary.charAt(binary.length() - reverseCounter - 1)) + " reverseCounter " + reverseCounter);
            }

            return result;
    }
    static String isDecimalOrBinary(String input){
        for(int counter = 0; counter < input.length(); counter++){
            if(input.charAt(counter) != '0' && input.charAt(counter) != '1'){
                return "decimal";
            }
        }

        return "binary";
    }
    public static void main(String[] args){
        Scanner inputScanner = new Scanner(System.in);

        System.out.print("Please enter the binary/decimal number to convert:");
        String input = inputScanner.nextLine();

        switch(isDecimalOrBinary(input)){
            case "decimal":
                System.out.println(convertDecimalToBinary(input));
            break;
            case "binary":
                System.out.println(convertBinaryToDecimal(input));
            break;
        }
    }
}


texts: Checking if an element exists in an array efficiently and return it

texts:
I am writing a function for my node/angular app that will prompt the user with a random question that he was not asked before.

To achieve this I wrote this function:

function setQuestion() {
            var q; // question we will eventually ask the user
            for (q in questions) {
                if (!(q._id in questionsUserAlreadyAnswered)) {
                    /* the user has NOT answered this question yet -> so we can ask him now! */
                    $scope.title = q.description;
                    $scope.questionToAsk = q;
                    return;
                }
            }
            /* if we got here it means the user has already answered ALL the questions */
            $scope.title = 'None';
            $scope.questionToAsk = 'None';
}

Here questions is an array of questions (Strings) and so is questionsUserAlreadyAnswered.

I am wondering if this is efficient enough, since I have many questions in the database and the user possibly answered many of them before, so essentially I iterate over all the questions I asked him.(?) twice.


texts:
I am wondering if the following is a good concideration.
There might be several links on a page with a data-rel attribute that could be static or dynamically added with javascript. Instead of adding an eventlistener to each of those I am thinking about adding an eventlistener to the document. I don't want to use jQuery.

Is the following good, or is there a better do add events to dynamically added ellements?

var api = {
    function addEvent (evnt, el, func) {
        if (el.addEventListener) { // W3C DOM
            el.addEventListener(evnt,func,false);
        } else if (el.attachEvent) { // IE DOM
            el.attachEvent('on' + evnt, func);
        } else { // No much to do
            el[evnt] = func;
        }
    }
  , removeEvent : function removeEvent (evnt, el, func) {
        if (el.removeEventListener) { // W3C DOM
            el.removeEventListener(evnt,func,false);
        } else if (el.detachEvent) { // IE DOM
            el.detachEvent('on' + evnt, func);
        } else { // No much to do
            el.splice(evnt, 1);
        }
    }
  , checkWhatIsClicked: function checkIfDialog (e) {
        var el = e.srcElement || e.target
          , dataCallback = el.getAttribute('data-callback')
          , dataRel = el.getAttribute('data-rel');

        if (dataRel !== null) {
            switch (dataRel) {
                case 'alert':
                    e.preventDefault();

                    dialogBox.alert();
                    break;
                case 'dialogBox':
                    e.preventDefault();

                    dialogBox.dialog();
                    break;
                case 'prompt':
                    e.preventDefault();

                    dialogBox.prompt();
                    break;
            }
        } else if (dataCallback !== null && el.className.indexOf('dialog-answer') > -1) {
            if (typeof window[dataCallback] === 'function') {
                var result = el.getAttribute('data-result');

                window[dataCallback](result, el);
            }

        }
    }
};

api.addEvent('click', window.document, api.checkWhatIsClicked);


texts: Improve my if-statement to prevent double checks

texts:
I write the following version of an if-statement very often. And every time, I hate the way that I make it, but I don't know how to improve it.

For example, I have two ArrayList's. If one of them is not empty, then I convert it to a StringBuilder and send it per mail. The problem is, first I check if one of them is not empty to know if I should send a mail, and then I check it again to know which of them is not empty. Example code:

if(!array1.isEmpty() || !array2.isEmpty()){
   // I need to distinguish the StringBuilder
   StringBuilder array1string = new StringBuilder();
   StringBuilder array2string = new StringBuilder();
   // so one of them is not empty. but which? now I must double check it
   if(!array1.isEmpty()){
      for(String string : array1){
         array1string.append(string);
      }
   }
   if(!array2.isEmpty()){
      for(String string : array2){
         array2string.append(string);
      }
   }
   mail.sendMail("Array1: " + array1string == null?"-":array1string.toString()
      + ", Array2: " + array2string == null?"-":array2string.toString());
}

So is there a way to prevent this double check?


texts: Updating persons in database with newly created addresses

texts:
I have the following code, and I'd like to refactor it to a more functional way:

public void processPersons(List<Person> personList) {
    for (Person person : personList) {
        Integer addressId = createAddress(person);
        if (addressId != null) {
            updateDbStatus(addressId, person);
        }
    }
}

How do I convert the above to a more functional style of programming?


texts:
I have some concerns, like the updateValue function. I was trying to follow the functional paradigm, but I wonder if I could use another approach or something.

My parsing function seems overly complicated, particularly the '[' case seems complicated. Any other comments are appreciated too!

namespace Brainfuck

module Interpreter =
    type public ProgramState =
        { Pointer : int
          Memory : Map<int, int> }

    let private currentValue state = Map.find state.Pointer state.Memory

    let private updateValue state op =
        let updateMemory =
            match Map.tryFind state.Pointer state.Memory with
            | Some(x) ->
                let m = Map.remove state.Pointer state.Memory
                Map.add state.Pointer (op x) m
            | None -> Map.add state.Pointer (op 0) state.Memory
        { state with Memory = updateMemory }

    type private Command =
        | SimpleCommand of char
        | Loop of Command list

    let private parse code =
        let literals = [ '+'; '-'; '>'; '<'; '.'; ',' ] |> Set.ofList

        let rec parsing =
            function
            | x :: xs when x = '[' ->
                let innerLoop, innerRemaining = parsing xs
                let commands, remaining = parsing innerRemaining
                let remainingCommands, after = parsing remaining
                Loop(innerLoop) :: commands @ remainingCommands, after
            | x :: xs when x = ']' -> [], xs
            | x :: xs when Set.contains x literals ->
                let commands, remaining = parsing xs
                SimpleCommand(x) :: commands, remaining
            | x :: xs -> parsing xs
            | [] -> [], []
        code
        |> Seq.toList
        |> parsing
        |> fst

    let private interpretSimpleCommand state command =
        match command with
        | '>' -> { state with Pointer = (state.Pointer + 1) }
        | '<' -> { state with Pointer = (state.Pointer - 1) }
        | '+' -> updateValue state (fun x -> x + 1)
        | '-' -> updateValue state (fun x -> x - 1)
        | '.' ->
            printf "%c" <| (char) (currentValue state)
            state
        | ',' -> updateValue state (fun x -> System.Console.Read())
        | _ -> failwith "invalid command"

    let private compute bytecode =
        let rec cmp state cmd =
            match cmd with
            | SimpleCommand(x) -> interpretSimpleCommand state x
            | Loop(xs) ->
                let nextState = computeProgram state xs
                if currentValue (nextState) = 0 then nextState
                else cmp nextState cmd

        and computeProgram = List.fold cmp
        computeProgram { Pointer = 0
                         Memory = Map.empty<int, int> } bytecode

    let public eval code =
        code
        |> parse
        |> compute


texts: Arduino Sketch for sending sensor turn on/off to computer

texts:
I'm having this Arduino Sketch:

#define maxDigitalPin 7 //musn't be greater than 127

boolean state[] = { false, false, false, false, false, false };
unsigned long nextTime[] = { 0, 0, 0, 0, 0, 0 };

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

  for(int i = 2; i <= maxDigitalPin; i++){
    pinMode(i, INPUT_PULLUP);
  }
}

void loop(){
  for(int i = 2; i <= maxDigitalPin; i++){
    int arrayIndex = i - 2;
    if(digitalRead(i) == LOW && !state[arrayIndex] && millis() > nextTime[arrayIndex]){
      Serial.write(i ^ 128);
      state[arrayIndex] = true;
    }
    else if(state[arrayIndex] && digitalRead(i) == HIGH){
      Serial.write(i);
      state[arrayIndex] = false;
      nextTime[arrayIndex] = millis() + 500;
    }
  }
}

It will send a byte to a computer when a sensor goes on and when it goes back off.

The byte looks like:

SPPP PPPP

S is 1 when the sensor has gone on and 0 when it has gone off. P is the pin.

This code prevents sending the on message for a pin for 500ms after it has gone off. This is intended and really necessary.

My concerns:

Is it possible to reduce the code to only use one array?
I fear this sketch will be slow once it's using more than 7 pins because it's really important that the computer gets informed pretty instantly.

Of course if there is anything else to improve I would like to hear it too.


texts:
I got this code working but it feels clunky. I am wondering if there is a way I can improve it.

(I'm intermingling JavaScript and jQuery). I'm using jquery-1.11.1.min.js hosted on code.jquery.com.

Here is the jsFiddle

JS:

HTML:

        S&amp;P 500

        Nasdaq 100

        SPDR Gold

        iShares Silver

        Nikkei 225

        FTSE

CSS:

Update Here is the final product of the great suggestions below and some additional changes. I also added a 'stretchy' ability that targets the parent container size and when that view able space gets to small to work with it hides the stock information bar.  I did this to reduce clutter for mobile users.

http://jsfiddle.net/franktudor/LZm2f/

and it works like a charm and I hope someone else finds this useful for their website.


texts:
I'm done with this "Guessing word game" but I have a very ugly method named startGuessing().

I tried to make it cleaner and more readable but I couldn't. How I can improve this method?

public class GameHangman {

private static String[] WORDS = {"programming", "fish", "cairo", "arabs", "quraan", "sunnah",
        "editor", "photography", "artist", "software", "write", "read", "gaming",
        "lunch", "participate", "lunch", "dinner", "house", "books", "animals"};

public static void startGame() {

    Scanner input = new Scanner(System.in);

    //Choose a random word
    String word = chooseWord();

    //Start guessing game with chosen word and count missed times
    int missed = startGuessing(word, input);

    //Display result
    System.out.println("The word is " + word + (missed == 0 ? " you are correct" : " you missed " + (missed == 1 ? " one time" : " " + missed + " times")));

    //Ask for another game
    askForAnotherGame(input);
}

private static void askForAnotherGame(Scanner input) {
    System.out.print("Do you want to start another word? Enter y or no>");
    char gameCase = input.nextLine().charAt(0);
    if (gameCase == 'y')
        startGame();
    else
        System.exit(1);
}

private static int startGuessing(String originalWord, Scanner input) {
    StringBuilder replacedWord = new StringBuilder(hideRealWord(originalWord));
    int missing = 0;
    boolean wrongGuessing;
    int wordLength = originalWord.length();

    while (wordLength > 0) {
        System.out.print("(Guess) Enter a letter in word " + replacedWord.toString() + " ");
        char ch = input.nextLine().charAt(0);
        wrongGuessing = true;
        for (int j = 0; j < originalWord.length(); j++) {
            if (originalWord.charAt(j) == ch) {
                replacedWord.setCharAt(j, ch);
                wrongGuessing = false;
                wordLength--;
            }
            if (ch == replacedWord.charAt(j))
                System.out.println(ch  + " Already in the word");
        }
        if (wrongGuessing) {
            System.out.println(ch + " is not in the word");
            missing++;
        }

    }
    return missing;
}

private static String hideRealWord(String originalWord) {
    //System.out.println(originalWord);
    for (int i = 0; i < originalWord.length(); i++) {
        char ASTERISK = '*';
        originalWord = originalWord.replace(originalWord.charAt(i), ASTERISK);
    }
    return originalWord;
}

private static String chooseWord() {
    return WORDS[(int) (Math.random() * WORDS.length)];
    }
}


texts: Design Pattern - Abstract Factory Pattern Implementation in PHP

texts:
Products Class that are like

Table
Chair
etc

Pls review it and give your thoughts and let me know if there are any rooms for improvisation.

Products.php

<?php

abstract class Products
{

}

class Table extends products
{
    public function __construct()
    {
        echo "New Table Created";
    }
}

class Chair extends products
{
    public function __construct()
    {
        echo "New Chair Created";
    }
}

Factory Class That can produce Plastic Furniture, Wooden Furniture

Abstract Factory Class - FurnitureClass

<?php
include "products.php";

abstract class FurnitureFactory
{
    abstract function building();
}

class WoodenFactory extends FurnitureFactory
{
    const TABLE = 1;
    const CHAIRS = 2;

    public function building()
    {
        echo "Building Wooden Furniture";
    }

    public function makeWoodenTable()
    {
        echo "Wooden ";
        return new Table();
    }

    public function makeWoodenChair()
    {
        echo "Wooden ";
        return new Chair();
    }
}

class PlasticFactory extends FurnitureFactory
{
    public function building()
    {
        echo "Building Plastic Furniture";
    }
}

$wfactory = new WoodenFactory();
$wtable = $wfactory->makeWoodenTable();
$wchair - $wfactory->makeWoodenChair();


texts: Is there a way to speed-up the following code?

texts:
Is there a way to speed-up the following R code?

actionVec<-NULL
for(iii in 1:length(resultTable$V1)){
actionVec[iii]<- sum(browse$V2==resultTable$V1[iii] & browse$V4 == i & browse$V5 == ii)}

this is a loop to form a vector for each record (row) in resultTable, containing the number of entries that match the conditions in table browse

this script runs 36 minutes. I suspect that there is a way to make it run much faster. I have experienced a reduction from 15 min to 10 ms (!) on another script when avoiding loops but using vectors. But in this case I can`t find out how to make it.

EDIT1:
variables i and ii come from outer loop and may be two arbitrary integers for this loop.

EDIT2: more complete version

SESSION_NUMBER<-length(resultTable$V1)

for(i in 1:55){ for(ii in 1:21){
if(sum(browse$V4 == i & browse$V5 == ii) > treshold){
actionVec<-NULL
for(iii in 1:SESSION_NUMBER){
actionVec[iii]<- sum(browse$V2==resultTable$V1[iii] & browse$V4 == i & browse$V5 == ii)}
resultTable[,i+1] <- actionVec
}}}


texts:
I should be able to figure this out on my own, but I can't seem to wrap my head around how to optimize this set of logic for interpreting the existence of URL parameters.

<cfif ParameterExists(start) and not ParameterExists(end) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *
    FROM student_profile
    WHERE (Date_Modified BETWEEN '#token# #start#' AND '#token# 23:59:59')
</cfquery>
<cfelseif ParameterExists(end) and not ParameterExists(start) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *
    FROM student_profile
    WHERE (Date_Modified BETWEEN '#token# 00:00:00' AND '#token# #end#')
</cfquery>
<cfelseif ParameterExists(start) and ParameterExists(end) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *
    FROM student_profile
    WHERE (Date_Modified BETWEEN '#token# #start#' AND '#token# #end#')
</cfquery>
<cfelseif ParameterExists(after) and not ParameterExists(start) and not ParameterExists(end)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *
    FROM student_profile
    WHERE (Date_Modified BETWEEN '#token# #after#' AND '#today# 23:59:59')
</cfquery>
<cfelse>
<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *
    FROM student_profile
    WHERE (Date_Modified BETWEEN '#token# 00:00:00' AND '#token# 23:59:59')
</cfquery>
</cfif>

It's a disgusting chunk of code, I know. Its operation is pretty simple, though: run a query with a set of parameters if they exist.

I would like to have some sort of short circuit logic so I can just say:

<cfif (logic to check parameters) >
    <cfquery name="STUDENT" datasource="#STUD_DB#">
        SELECT *
        FROM student_profile
        WHERE (Date_Modified BETWEEN '#startdate# #starttime#' AND '#enddate# #endtime#')
    </cfquery>

This would most likely require me to set default values as well, but I am okay with that.


texts:
This is my first calculator in Java. I just started learning a week ago so any feedback (positive and negative) is welcome. Tell me what's good and what I can improve on.

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {

        // Creates scanner object
        Scanner scanner = new Scanner(System.in);

        // Controls the start and stop of the program
        boolean run = true;

        // Sets and resets the operand and answer variables
        int fnum = 0;
        int snum = 0;
        int answer = 0;

        // While loop that keeps the program running until user exits
        while (run) {

            // Calculator interface
            System.out.println("=====================================");
            System.out.println("           Calculator V1.0         ");
            System.out.println("=====================================");
            System.out.println("1. Addition");
            System.out.println("2. Subtraction");
            System.out.println("3. Multiplication");
            System.out.println("4. Division");
            System.out.println("5. Exit");
            System.out.printf("Please pick an operation(1-5): ");

            // Prompts user to choose an operation
            int operation = scanner.nextInt();

            // Does stuff depending on what integer the user enters
            switch (operation) {
            case 1:
                System.out.printf("Enter first number: ");
                fnum = scanner.nextInt();
                System.out.printf("Enter second number: ");
                snum = scanner.nextInt();
                answer = fnum + snum;
                System.out.println("The answer is: " + answer);
                break;

            case 2:
                System.out.printf("Enter first number: ");
                fnum = scanner.nextInt();
                System.out.printf("Enter second number: ");
                snum = scanner.nextInt();
                answer = fnum - snum;
                System.out.println("The answer is: " + answer);
                break;

            case 3:
                System.out.printf("Enter first number: ");
                fnum= scanner.nextInt();
                System.out.printf("Enter second number: ");
                snum = scanner.nextInt();
                answer = fnum * snum;
                System.out.println("The answer is: " + answer);
                break;

            case 4:
                System.out.printf("Enter first number: ");
                fnum = scanner.nextInt();
                System.out.printf("Enter second number: ");
                snum = scanner.nextInt();
                answer = fnum / snum;
                System.out.println("The answer is: " + answer);
                break;

            case 5:
                System.out.println("Thank you for using the calculator!");
                scanner.close();
                run = false;
                break;

            default:
                System.out.println("Invalid operation!");
                break;
            }
        }
    }
}


texts:
This is my implementation of the stack data type in C language. It is static meaning it does not grow in size. Any suggestions or feedback would be much appreciated.

#include <stdio.h>
#define MAXSTACKLENGTH 6
#define true 1
#define false 0

struct stk{
    char content[MAXSTACKLENGTH];
    int top;
};

typedef struct stk stack;

int size(stack *s)
{
    return s->top;
}

int isEmpty(stack *s)
{
    if (size(s) <= -1)
    {
        return true;
    }
    else if (size(s) > -1)
    {
        return false;
    }
}

int isFull(stack *s) {
    if (size(s) == (MAXSTACKLENGTH-1))
    {
        return true;
    }
    else {
        return false;
    }
}

char peek(stack *s)
{
    if (isEmpty(s) == true)
    {
        printf("Can't peek: Stack is empty!\n");
        return '\0';
    }
    else {
        return s->content[s->top];
    }
}

void push(stack *s, char element)
{
    if (isFull(s) == true)
    {
        printf("Cant push: Stack is full!\n");
    }
    else {
        s->top++;
        s->content[s->top] = element;
    }
}

void pop(stack *s)
{
    if (isEmpty(s) == true) {
        printf("Cant pop: Stack is empty!\n");
    }
    else {
        s->top--;
    }
}

void input_push(stack *s)
{
    char c;
    printf("Enter a character> ");
    scanf(" %c", &c);

    push(s, c);
}

void print_stack(stack *s)
{
    if (isEmpty(s)) {
        printf("Stack is empty!\n");
    }
    else {
        int i = s->top;

        for (i; i > -1; i--)
        {
            printf("%c\n", s->content[i]);
        }

        printf("\n");
    }
}

void pause()
{
    char c;
    printf("Enter any character to continue.\n");
    scanf(" %c", &c);
}

int main()
{
    printf("SimpleStack! v1\n");

    stack mystack;
    mystack.top = -1; //Empty

    int run = true;
    int choice = 0;

    while (run)
    {
        if (isFull(&mystack))
        {
            printf("Warning -> Stack is full\n");
        }
        if (isEmpty(&mystack))
        {
            printf("Warning -> Stack is empty\n");
        }
        printf("1 -> Push\n");
        printf("2 -> Pop\n");
        printf("3 -> Peek\n");
        printf("4 -> Print Stack\n");
        printf("5 -> Exit\n");

        printf("Enter choice> ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                input_push(&mystack);

                break;
            case 2:
                pop(&mystack);

                break;
            case 3:
                printf("%c\n", peek(&mystack));
                pause();
                break;
            case 4:
                print_stack(&mystack);
                pause();
                break;
            case 5:
                printf("Goodbye!\n");
                run = false;

                break;
            default:
                printf("Invalid choice.\n");

                break;
        }

        system("clear");
    }

    return 0;
}