texts:
I am looking for some suggestions on how to make my code cleaner and simpler. Or put another way: more elegant and idiomatic. Any other comments on quality or anything would be appreciated.

class App extends Component {
      constructor(props){
        super(props);

        this.state = {
            colIds : ["winnie", "bob", "thomas", "george"],
            cols : [
              {name:"Winnnie", headerColor: "#8E6E95", id : "winnie" },
              {name:"Bob",  headerColor: "#39A59C", id :"bob"},
              {name:"Thomas",  headerColor: "#344759", id: "thomas"},
              {name:"George",  headerColor: "#E8741E", id: "george"}
            ],
            cards : [
              {colid: "winnie", task: "buy eggs"},
              {colid: "bob", task: "clean basement"},
              {colid: "thomas", task: "pack"},
              {colid: "george", task: "pay bills"},
            ]
          }

          this.addCard = this.addCard.bind(this);
          this.moveCardRight = this.moveCardRight.bind(this);
          this.moveCardLeft = this.moveCardLeft.bind(this);
      }

      getColCards(colid){
          let cards = this.state.cards.filter( c => c.colid == colid);
          return cards;
      }

      addCard(colid){
        let cardTask = window.prompt("Whats the task you want to add");
        let currentCards = this.state.cards.slice();
        let newCard = {colid: colid, task: cardTask};
        currentCards.push(newCard);
        this.setState({cards: currentCards});

      }
      moveCardRight(card){
        let currentCardCol = card.colid;
        let nextIndex =  this.state.colIds.indexOf(currentCardCol) + 1;

        if(nextIndex > this.state.colIds.length - 1 ){
          return null;
        }
        let currentCards = this.state.cards.slice();
        for(let i = 0; i < currentCards.length; i++){
            if(currentCards[i].task === card.task){
               currentCards[i] = {
                 ...currentCards[i],
                 colid : this.state.colIds[nextIndex]
               }
            }
        }
        this.setState({cards: currentCards});
      }

      moveCardLeft(card){
        let currentCardCol = card.colid;
        let nextIndex =  this.state.colIds.indexOf(currentCardCol) - 1;

        if(nextIndex < 0 ){
          return null;
        }
        let currentCards = this.state.cards.slice();
        for(let i = 0; i < currentCards.length; i++){
            if(currentCards[i].task === card.task){
               currentCards[i] = {
                 ...currentCards[i],
                 colid : this.state.colIds[nextIndex]
               }
            }
        }
        this.setState({cards: currentCards});
      }
      render() {
        let cols =[
                      {name:"Winnnie", headerColor: "#8E6E95"},
                      {name:"Bob",  headerColor: "#39A59C"},
                      {name:"Thomas",  headerColor: "#344759"},
                      {name:"George",  headerColor: "#E8741E"}
        ];
        let colCards = this.state.cols.map(c => {
        let cards = this.getColCards(c.id).map(c =>  {
            return

                     this.moveCardLeft(c)}> {"<   "}
                    {c.task}
                     this.moveCardRight(c)}> {"    >"}

          })

          return  <CardCol  name={c.name}  headerColor={c.headerColor} addCard={this.addCard} id={c.id}>
                     {cards}
                  </CardCol>
        })
        return (

          {colCards}

        );
      }
    }


texts: LESS CSS, including support for shadowboxes

texts:
I'm learning about using LESS and wanted to get anyone's input on if I'm using the concepts, syntax, etc. correctly.I know this might seem subjective and not the correct place to post, so please let me know if there is a more appropriate place to do this.

LESS code

.centered(@position: inline, @width: 100%){
    margin-left: auto;
    margin-right: auto;
    width: @width;
    display: @position;
}

.table-center(@width: 100%){
    width:@width;
    display:table!important;
    text-align:center;
    &:nth-child(1) {
        display:table-cell;
    }
}

.clear-border-radius{
     border-radius: initial;
    -webkit-border-radius: initial;
    -moz-border-radius: initial;
}

.shadowbox-format(@caption-font-size, @button-font-size, @shadowbox-margin) {
    display: block;
    position: absolute;
    min-height: 85px;
    width: 60%;
    margin: @shadowbox-margin;
    left: 20%;

    .shadowbox-caption {
        font-size: @caption-font-size;
        .table-center;
    }

    .shadowbox-button-wrapper {
        width: 35%;
        margin: 26px auto 0;

        & > a {
            .clear-border-radius;
            font-size: @button-font-size;
        }
    }
}

.home-slide-container{
    img{
        .centered(block);
        height:auto;
    }
}
.callout-header{
    text-align:center;
    width: auto;
    margin: 40px auto 0;
    border-bottom: 1px solid #9e9e9e;
    padding: 0 0 30px;
     @media (max-width: @screen-xs-max){
         width: 90%;
     }
          @media (min-width: @screen-sm-min){
         width: 60%;
     }
     span{
         font-size: 24px;
     }

}
 .carousel-shadowbox
 {
         text-transform: uppercase;
         color:#000;
         background-color:rgba(255,255,255,0.4);

     @media (max-width: @screen-xs-max)
     {
         background-color: white;
         opacity:1.0;

          .shadowbox-caption{
            .table-center;
             span{
                font-size: 16px;
                font-weight: 100;
                }
         }
     }
     @media (min-width: @screen-sm-min)
     {
        .shadowbox-format(20px, 16px, -91px auto 0);
     }
     @media (min-width: @screen-md-min)
     {
         .shadowbox-format(22px, 18px, -96px auto 0);
     }
     @media (min-width: @screen-lg-min)
     {
         .shadowbox-format(24px, 20px, -102px auto 0);
     }
}

 .callout{
     position:relative;
     margin-top: 5%;
     img{
         @media (max-width: @screen-xs-max){
             margin: 0 auto;
         }
     }
     .callout-text-container{
         padding:3px;
      @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max)
         {
            bottom:22px;
         }

         min-height: 200px;
         .callout-title{
             padding-top: 5px;
             text-transform: capitalize;
             font-size: 22px;
             display:table;
             width:100%;
             text-align:center;
             margin-bottom: 25px;
             span{
                 display: table-cell;
             }
         }
         .callout-body{
             font-size: 15px;
             padding:8px;
             text-align:justify;
         }
         .button-wrapper{
             padding: 10px;
             a{
                 text-transform: capitalize;
                 border-bottom: 4px solid #cb2b06;
                 background-color: #e6431e;
                .clear-border-radius;
                 font-size: 16px;
             }
         }
     }
 }


texts: Aggregate loans report without using Python standard aggregate or group functions

texts:
I've written the following as a code assignment (Python 2.7). The task is to aggregate the loans csv file from the accounts department by (Network, Product, Month) with the total currency amounts, and counts, without using standard Python aggregate or group functions. I would like advice and suggestions on my current solution in order to learn from it going forward as my code was reviewed already.

I've used Python dict OrderedDict instead of normal Python dictionary to keep the current order of the records. I do realise that using OrderedDict comes at a cost, how else could I keep the order of the records that will be written to the Output Summary CSV.

Input Loans CSV

Output Loans Summary CSV

"""
Created on 20 August 2017

Loans Summary

Validation

@author: Peter Wilson
"""
import re
import csv
import argparse
import collections
from datetime import datetime

def csv_to_dict(loans_csv):
    """Convert loans csv to
    Python dictionary"""
    loans_dict = csv.DictReader(open(loans_csv))
    return loans_dict

def dict_to_agg_dict(loans_dict):
    """Aggregate loans by
    (Network, Product, Month)"""
    agg_dict = collections.OrderedDict()
    for row in loans_dict:
        network = re.sub(r"'", '', row['Network'])
        product = re.sub(r"'", '', row['Product'])
        # assumed month per year to be aggregated
        month = re.findall(r'([A-z]+?-\d{4})', row['Date'])[0]
        # assumed currency rounded to closet rounded number
        currency = float(row['Amount'])
        dict_key = (network, product, month)
        agg_dict.setdefault(dict_key, []).append(currency)
    return agg_dict

def agg_dict_to_lists(agg_dict):
    """Convert aggregated dictionary
    to Python list of lists"""
    summary_list = []
    for key, values in agg_dict.iteritems():
        values_list = list(key)
        currency_sum = sum(values)
        counts = len(values)
        values_list.insert(len(values_list), currency_sum)
        values_list.insert(len(values_list), counts)
        summary_list.append(values_list)
    return summary_list

def output_csv_summary(summary_list, output_csv_folder):
    """Write aggregated results
    into output csv"""
    current_date = datetime.today().strftime("{0}{1}{2}".format("%y", "%m", "%d"))
    csv_name = "{0}_{1}.csv".format("Output", current_date)
    output_csv = "{0}\\{1}".format(output_csv_folder, csv_name)
    print("Writing {0} to {1}".format(csv_name, output_csv_folder))
    csv_header = ["Network", "Product", "Month\Year", "Currency", "Count"]
    with open(output_csv, 'wb') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(csv_header)
        for row in summary_list:
            try:
                csvwriter.writerow(row)
            except UnicodeError as e:
                print(e)

def validate_loans(loans_csv, output_csv_folder):
    """Validate loans summary from
    accounts with system"""
    loans_dict = csv_to_dict(loans_csv)
    agg_dict = dict_to_agg_dict(loans_dict)
    summary_list = agg_dict_to_lists(agg_dict)
    output_csv_summary(summary_list, output_csv_folder)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Validate accounting loans summary against system')
    parser.add_argument('--loans_csv', metavar='path', required=True,
                        help='path to input loans csv')
    parser.add_argument('--output_csv_folder', metavar='path', required=True,
                        help='path to output csv folder')
    args = parser.parse_args()
    validate_loans(loans_csv=args.loans_csv, output_csv_folder=args.output_csv_folder)


texts: wait for the UI thread to complete or cancel the wait

texts:
using System;
using System.Diagnostics;
using System.Threading;

class Program
{
  public static void Main()
  {
     ThreadPool.QueueUserWorkItem(() => {
        Thread.Sleep(10000);
        PressAnyKey.Cancel();
     });
     Console.WriteLine("Press Any Key or don't...");
     PressAnyKey.WaitOne();
  }
}

internal class PressAnyKey
{
  private static Thread inputThread;
  private static AutoResetEvent getInput;
  private static AutoResetEvent gotInput;
  private static CancellationTokenSource cancellationtoken;

  static PressAnyKey()
  {
    // Static Constructor called when WaitOne is called (technically Cancel too, but who cares)
    getInput = new AutoResetEvent(false);
    gotInput = new AutoResetEvent(false);
    inputThread = new Thread(ReaderThread);
    inputThread.IsBackground = true;
    inputThread.Name = "PressAnyKey";
    inputThread.Start();
  }

  private static void ReaderThread()
  {
    while (true)
    {
      // ReaderThread waits until PressAnyKey is called
      getInput.WaitOne();
      // Get here
      // Inner loop used when a caller uses PressAnyKey
      while (!Console.KeyAvailable && !cancellationtoken.IsCancellationRequested)
      {
        Thread.Sleep(50);
      }
      // Release the thread that called PressAnyKey
      gotInput.Set();
    }
  }

  /// <summary>
  /// Signals the thread that called WaitOne should be allowed to continue
  /// </summary>
  public static void Cancel()
  {
    // Trigger the alternate ending condition to the inner loop in ReaderThread
    if(cancellationtoken== null) throw new InvalidOperationException("Must call WaitOne before Cancelling");
    cancellationtoken.Cancel();
  }

  /// <summary>
  /// Wait until a key is pressed or <see cref="Cancel"/> is called by another thread
  /// </summary>
  public static void WaitOne()
  {
    if(cancellationtoken==null || cancellationtoken.IsCancellationRequested) throw new InvalidOperationException("Must cancel a pending wait");
    cancellationtoken = new CancellationTokenSource();
    // Release the reader thread
    getInput.Set();
    // Calling thread will wait here indefiniately
    // until a key is pressed, or Cancel is called
    gotInput.WaitOne();
  }
}


texts: Running async tasks and cancelling after a timeout if necessary - follow up (1)

texts:
The previous question was a really bad design where I had all the logic in the Main method. The only way to test it was to look at the output in the console. I now encapsulated it in an extension method and wrote two unit-tests for it - here I'm not sure about the part using the Stopwatch for checking how long the execution took - do you think this is the right way to do it? I guess the implementation of the extension alone should now be better.

The purpose of this extension is to execute multiple jobs in parallel and cancel the ones that take too much time to complete.

public static void WaitAll(this IEnumerable<Action<CancellationToken>> actions, TimeSpan timeout)
{
    using (var cancellationTokenSource = new CancellationTokenSource())
    {
        var tasks = actions.Select(action => Task.Run(() => action(cancellationTokenSource.Token))).ToArray();
        if (!Task.WaitAll(tasks, timeout))
        {
            cancellationTokenSource.Cancel();

            // Wait for cancellation, if necessary.
            Task.WaitAll(tasks);
        }
    }
}

I also have another overload that does not use the timeout.

public static void WaitAll(this IEnumerable<Action<CancellationToken>> jobs) => WaitAll(jobs, TimeSpan.FromMilliseconds(-1));

And the test class:

public class ActionExtensionsTest
{
   public TestContext TestContext { get; set; }

    [TestMethod]
    public void WaitAll_JobsFinishInTime_NoCancellation()
    {
        var jobs = new TestJob[]
        {
        new TestJob { WorkInSeconds = 6, Log = m => TestContext.WriteLine(m) },
        new TestJob { WorkInSeconds = 2, Log = m => TestContext.WriteLine(m) },
        new TestJob { WorkInSeconds = 4, Log = m => TestContext.WriteLine(m) },
        };

        var sw = Stopwatch.StartNew();
        jobs.Select(j => new Func<CancellationToken, Task>(j.Start)).WaitAll();
        Assert.IsTrue(sw.Elapsed.TotalSeconds < 7);
    }

    [TestMethod]
    [ExpectedException(typeof(AggregateException))]
    public void WaitAll_OneJobTimesout_Canceled()
    {
        var jobs = new TestJob[]
        {
        new TestJob { WorkInSeconds = 6, Log = m => TestContext.WriteLine(m) },
        new TestJob { WorkInSeconds = 2, Log = m => TestContext.WriteLine(m) },
        new TestJob { WorkInSeconds = 4, Log = m => TestContext.WriteLine(m) },
        };

        var sw = Stopwatch.StartNew();
        jobs.Select(j => new Func<CancellationToken, Task>(j.Start)).WaitAll(TimeSpan.FromSeconds(5));
        Assert.IsTrue(sw.Elapsed.TotalSeconds < 6);
    }

    class TestJob
    {
        private static int counter;

        static TestJob() => counter++;

        public string Name => $"{nameof(TestJob)}{counter}";

        public int WorkInSeconds { get; set; }

        public Action<string> Log { get; set; }

        public async Task Start(CancellationToken cancellationToken)
        {
            Log(Name + " started.");
            for (int i = 0; i < WorkInSeconds; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Task.Delay(TimeSpan.FromSeconds(1));
            }
            Log(Name + " finished.");
        }
    }
}


texts:
I'm working on a menu for my poker game console app. I've conceptualized the menu(s) as a class with menu items that have their own position. I would like to get pointers on how I could improve on what I have done as I would like to add a settings menu in the future.
Here's a gif of how the menu works:

Here's my main menu class, just so that you have an example:
    public class MainMenu
    {
        int _currentItemIndex;
        int _selectorOffset;
        IMenuItem[] _menuItems;

        public MainMenu()
        {
            _currentItemIndex = 0;
            _selectorOffset = 15;
            _menuItems = new IMenuItem[] { new StartGameItem(48, 11), new TutorialItem(48, 13), new ExitGameItem(48, 15) };
        }

        public void Open()
        {
            Console.Clear();
            GraphicsHelper.SetConsoleColor();

            bool optionSelected = false;
            Console.CursorVisible = false;
            Console.WriteLine(Resources.MainMenuContent);

            Console.CursorTop = _menuItems[_currentItemIndex].Y;
            GraphicsHelper.DrawSelector(_menuItems[_currentItemIndex].X, _selectorOffset);

            while (!optionSelected)
            {
                if (Console.KeyAvailable)
                {
                    switch (Console.ReadKey(true).Key)
                    {
                        case ConsoleKey.UpArrow:
                            GraphicsHelper.EraseSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
                            _currentItemIndex--;

                            if (_currentItemIndex < 0)
                                _currentItemIndex = _menuItems.Length - 1;

                            break;

                        case ConsoleKey.DownArrow:
                            GraphicsHelper.EraseSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
                            _currentItemIndex++;

                            if (_currentItemIndex > _menuItems.Length - 1)
                                _currentItemIndex = 0;

                            break;

                        case ConsoleKey.Spacebar:
                        case ConsoleKey.Enter:
                            optionSelected = true;
                            break;

                    }

                    Console.CursorTop = _menuItems[_currentItemIndex].Y;
                    GraphicsHelper.DrawSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
                }
            }

            while (_currentItemIndex != -1)
            {
                _menuItems[_currentItemIndex].Select();
                Open();
            }
        }
    }

IMenu code as requested:
    public interface IMenuItem
    {
        int X { get; set; }
        int Y { get; set; }

        void Select();
    }

Graphics helper code:
    // EraseSelector is just a space in the Write method.
    public static void DrawSelector(int x, int dx)
    {
       Console.CursorLeft = x;
       Console.Write(">");

       Console.CursorLeft = x + dx;
       Console.Write("<");

    }

    public static void SetConsoleColor()
    {
       Console.BackgroundColor = ConsoleColor.DarkBlue;
       Console.Clear();
       Console.ForegroundColor = ConsoleColor.Yellow;
    }


texts: Pytest fixture for testing a vertex-parsing function

texts:
I have just started using pytest and I am still getting used to how they do things. It seems like fixtures are at the core of the library, and that they can be used for making small pieces of dummy data that will get reused. I see that there are other methods for handling large dummy data. I have the following test code which tests a module I wrote called generate_kml.

import pytest
import generate_kml as gk
import pandas

@pytest.fixture
def line_record():
    return pandas.Series({gk.DB_VERTICES: "LINESTRING(1.1 1.1,2.2 2.2)"})

def test_convert_wkt_to_coords(line_record):
    expected = pandas.Series({gk.DB_VERTICES: [("1.1", "1.1"), ("2.2", "2.2")]})
    assert gk.convert_wkt_vertices_to_coords(line_record).equals(expected)

I am wondering if this is the way fixtures are meant to be used; to set up small reused data. (I plan to use the line_record multiple times in the test file). Additionally, I am wondering about the readability or redundancy of assigning the expected value to expected. If I directly compared the two Series, the line would exceed PEP8's recommended line length, so I would break it into two lines anyway. If it adds readability here, then would it be good practice to always assign the expected value to a variable called expected (assuming you are comparing values that are expected to be equal)?
Here is the function being tested from generate_kml:

def convert_wkt_vertices_to_coords(vertices_as_wkt):
    def parse_coords(wkt):
        wkt = wkt[wkt.find("(") + 1:wkt.find(")")]
        coords = wkt.split(",")
        coords = [tuple(x.split(" ")) for x in coords]
        return coords
    return vertices_as_wkt.apply(parse_coords)

One more thing here; in convert_wkt_vertices_to_coords I have a nested function. I don't plan on reusing it, but in the past I haven't had a need for nested functions, so it feels a bit off to me. Should I leave it as a nested function or break it out as its own function in the module?


texts: Code that rotates images in a set of divs

texts:
I am rotating images inside some divs.

An image is associated with a link.Eg: image0 is associated with link0, image1 with link1 and so on.

image0 and link0 should display in pos-1

image1/link1 and image2/link2 should rotate on page refresh in pos-2

image3/link3 and image4/link4 should rotate  on page refresh in pos-3

Although currently I want to display only one image in pos-1, at a later stage I may rotate two images as well in pos-1. Similarly I may display only one image in pos-2.

$(function(){
var image = new Array ();
  image[0] = "";
  image[1] = "";
  image[2] = "";
  image[3] = "";
  image[4] = "";

var link = new Array ();
    link[0] = "";
    link[1] = "";
    link[2] = "";
    link[3] = "";
    link[4] = "";

var min = 0;
var max = 1;
var x = Math.floor(Math.random() * (max - min) + min);
$('#pos-1').append(link[x]+image[x]);
min=1;
max=3;
x = Math.floor(Math.random() * (max - min) + min);
$('#pos-2').append(link[x]+image[x]);
min=3;
max=5;
x = Math.floor(Math.random() * (max - min) + min);
$('#pos-3').append(link[x]+image[x]);
  });

Please let me know if this code can be improved to perform better?
Demo: https://jsfiddle.net/y0hga2of/5/


texts: Learning C, basic string reversal function

texts:
I am starting to write some functions while studying how to program in C.  In this small function I take a string as an argument and print it out in reverse order.

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

int main(int argc, char *argv[]) {

    int aLen = argc;
    char *sWord = argv[aLen - 1];
    char *reversed;

    int sLen = strlen(sWord);
    int i = 0;

    reversed = reversed + sLen;    // offset pointer to the length of string
    while (i <= sLen) {
        if (sWord[i] != '\0') {    // check if character is null-terminator
            *reversed = sWord[i];  // if not, let reversed correct address
        }                          // equal letter.
        i++;
        reversed--;
    }
    printf("%s reversed is:%s\n", sWord, reversed);
    return 0;
}

I was hoping to get some tips on best practice or corrections on any errors.


texts: Dirty but Efficient Texture Atlas in Spritekit

texts:
I have spent quite a bit of time trying to optimize the performance of my 2D mining game.  After a lot of research, experimentation, and testing, I finally found something very interesting that improved my performance pretty dramatically when rendering lots of tiles on the screen.

Initially I divided my textures up into texture atlases based on the way that I had seen many examples of texture organization for animations.  I put all the textures for each tile in one directory with a name like dirtimages.atlas, and then I loaded those textures into the game by iterating over the images in the directory and accounting for the number of formats I provided images for (there are different formats for smaller versus larger resolution devices).  I had a folder for each set of textures, so dirtimages.atlas, rockimages.atlas, etc.  This provided very clear organization in the code, and I liked it very much.

Unfortunately when profiling the number of draws of the scene, I was seeing pretty much one draw for every single tile (hundreds of draws).  I was hoping that the draws would not exceed the number of atlases, but for some reason, splitting the images up into different atlases caused the number of draws to increase by a huge amount.

Here is my workaround for this problem.  I consider it a dirty hack, but I think that this approach is the best one for performance.  I do remember seeing a mention somewhere on the internet about putting all of the images in one texture atlas, but I cannot find that link.  I did find this link on stack overflow about efficient texture atlas setups and it recommends pretty much what I have implemented here.

First I load up ALL of the textures into memory like this:

int numFormats = 3;
_tilesFromAtlas = textureAtlas(@"tileimages", @"tile", numFormats);

NSArray* textureAtlas(NSString *name, NSString *prefix, int numFormats) {
    NSMutableArray *atlasImages = [[NSMutableArray alloc]init];
    SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:name];
    if (atlas) {
        int numImages = (int)atlas.textureNames.count;
        for (int i = 1; i <= numImages/numFormats; i++) {
            SKTexture *texture = [atlas textureNamed:[NSString stringWithFormat:@"%@%d", prefix, i]];
            [atlasImages addObject:texture];
        }
    }
    return atlasImages;
}

Now when I am assigning a texture to a sprite in the scene, I have to keep track of the number of images that I have for each different tile. Also, the way I have this set up, they have to have the same number of images:

-(SKTexture *) textureForType:(BlockType)type damageLevel:(int)damageLevel {
    int numImagesEach = 4;
    switch (type) {
        case BlockTypeDirt:
        {
            int amount = (type * numImagesEach) + damageLevel;
            return _tilesFromAtlas[amount];
        }
        case BlockTypeRock:
        {
            int amount = (type * numImagesEach) + damageLevel;
            return _tilesFromAtlas[amount];
        }
        default:
            break;
    }
    return nil;
}

I would love to get feedback on this approach.  I think that it suffers from readability problems, but there is no denying the huge performance increase. After making this change the number of draws is usually somewhere between 1 and 2, and sometimes goes up to 10 or so if I zoom out a ways.


texts:
I am developing code for a problem posted on StackOverflow.
I have written my solution in Java but it is taking too much time to execute for numbers such as 21432154197846387216432.  How could I improve the performance of the following code?

import java.util.Scanner;

public class Main {

    // private static final double N = Double.parseDouble("916548345678631") ;
    // private static final long loopUntil = (int)(Math.sqrt(2 * N));
    // private static double M = 1.0 ;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in).useDelimiter("\n");
        while (scanner.hasNext()) {

            double N = Double.parseDouble(scanner.next());
            long loopUntil = (long) (Math.sqrt(2 * N));
            double M = 1.0;

            int doProcess = doProcess(N, loopUntil, M);
            System.out.println(doProcess);
        }
        scanner.close();
    }

    public static int doProcess(double N, long loopUntil, double M) {
        int result = 0;
        double constantDevisor = 1.0 / 2.0 ;

        // System.out.println("Loop Unttil " + loopUntil);
        while (M <= loopUntil) {
            double val = 0;
            // System.out.println((N / M) +" " + ( M / 2 ) + " " + (1.0/2.0));
            val = (N / M) + (M / 2) + constantDevisor;
            // System.out.println(val);
            if (Math.floor(val) == val) {
                System.out.println("With : " + M);
                result++;
            }
            M++;
        }

        return result;
    }

}


texts: Mapping object values from one object to another

texts:
I have an object called defaultOptions and a function that accepts as an argument an object called newValues meant to override the values in defaultOptions with its own.  The values that are not specified in newValues should remain default.

var configOptions = {
    isActive: false,
    name: "",
    description: "",
    category: "",
    group: "default"
}

    publishOptions: function(newValues){
      $.each(newValues, function(key, value){
        if(configOptions.hasOwnProperty(key)){
          configOptions[key] = value;
        }
        else{
          configOptions[key] = value;
        }
      });
      console.log(configOptions);
    }

For example, if I use this method like so:

var myOptions = {
    name: "option one",
    category: "the best"
}

publishOptions(myOptions)

I would expect configOptions to look like this:

configOptions = {
    isActive: false,
    name: "option one",
    description: "",
    category: "the best",
    group: "default"
}

I'm using jQuery's each method to map the values from newValues to configOptions, but I suspect there is a much more succinct and elegant way to do this.  I would appreciate any suggestions.


texts: Finding a Cartesian product of multiple lists

texts:
I came up with an extension method to find a Cartesian product of multiple IEnumerable sets. I was able to achieve lazy enumeration via yield return, but I didn't think of a way to do it non-recursively. The result ended up being a recursive lazy enumeration iterator method, the first of its kind! At least as far as I've ever written.

The idea of the problem came from a Stack Overflow question where a guy had many sets of characters, and wanted to generate a combination of all of them. Now I'm just interested because it's a fun problem!

I'd appreciate any kind of review, although here's two specific things I'm most interested in:

Can this algorithm can be de-recursed? If so - should it be, and how?
Is there some way it could be generalized even more, beyond what I've done?

public static class MultiCartesianExtension
{
    public static IEnumerable<TInput[]> MultiCartesian<TInput>(this IEnumerable<IEnumerable<TInput>> input)
    {
        return input.MultiCartesian(x => x);
    }

    public static IEnumerable<TOutput> MultiCartesian<TInput, TOutput>(this IEnumerable<IEnumerable<TInput>> input, Func<TInput[], TOutput> selector)
    {
        // Materializing here to avoid multiple enumerations.
        var inputList = input.ToList();
        var buffer = new TInput[inputList.Count];
        var results = MultiCartesianInner(inputList, buffer, 0);
        var transformed = results.Select(selector);
        return transformed;
    }

    private static IEnumerable<TInput[]> MultiCartesianInner<TInput>(IList<IEnumerable<TInput>> input, TInput[] buffer, int depth)
    {
        foreach (var current in input[depth])
        {
            buffer[depth] = current;
            if (depth == buffer.Length - 1)
            {
                // This is to ensure usage safety - the original buffer
                // needs to remain unmodified to ensure a correct sequence.
                var bufferCopy = (TInput[])buffer.Clone();
                yield return bufferCopy;
            }
            else
            {
                // Funky recursion here
                foreach (var a in MultiCartesianInner(input, buffer, depth + 1))
                {
                    yield return a;
                }
            }
        }
    }
}

Usage:

var input = new string[]
{
    "AB",
    "123",
    "@#",
};

foreach (var result in input.MultiCartesian(x => new string(x)))
{
    Console.WriteLine(result);
}

// Results:
// A1@
// A1#
// A2@
// A2#
// A3@
// A3#
// B1@
// B1#
// B2@
// B2#
// B3@
// B3#


texts:
What would you do to improve upon this boilerplate empty stored procedure, being mindful of the delicate balance between length, complexity, performance and clarity?

-- =============================================
-- Author:      The usual suspects
-- Create date: 10/06/2011
-- Description:
--
-- Nice long description about the procedure
--
-- =============================================
CREATE PROCEDURE

[dbo].[My_Stored_Proc]
(
-- exampleParam is an example parameter.
@exampleParam INT = 30
)
AS
BEGIN   -- main
SET NOCOUNT ON
BEGIN TRY
    DECLARE @crlf varchar(2)
    SET @crlf = CHAR(13) + CHAR(10)

    -- *** DO YOUR STUFF HERE ***

END TRY
BEGIN CATCH
    -- Error handler
    DECLARE @ErrorNumber INT
    DECLARE @ErrorSeverity INT
    DECLARE @ErrorState INT
    DECLARE @ErrorProcedure NVARCHAR(4000)
    DECLARE @ErrorLine INT
    DECLARE @ErrorMessage NVARCHAR(4000)

    DECLARE @ErrorDescription NVARCHAR(4000)

    -- retrieve error info
    SELECT
        @ErrorNumber = ERROR_NUMBER(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE(),
        @ErrorProcedure = ERROR_PROCEDURE(),
        @ErrorLine = ERROR_LINE(),
        @ErrorMessage = ERROR_MESSAGE();

    -- build custom error description
    SELECT @ErrorDescription = @crlf + @crlf + 'Base Error:\t[' + CAST(@ErrorNumber AS VARCHAR) + '] ' +
        @ErrorMessage + @crlf + @crlf +
        'exampleParam:\t' + CAST(@exampleParam AS VARCHAR) + @crlf +
        'Application:\t' + APP_NAME() + @crlf +
        'User:\t' + SYSTEM_USER + @crlf +
        'Database:\t' + DB_NAME() + @crlf +
        'Procedure:\t' + @ErrorProcedure + @crlf +
        'Line:\t' + CAST(@ErrorLine AS VARCHAR) + @crlf +
        'Severity:\t' + CAST(@ErrorSeverity AS VARCHAR) + @crlf +
        'State:\t' + CAST(@ErrorState AS VARCHAR);

    RAISERROR(@ErrorDescription, @ErrorSeverity, 1)
    RETURN @@ERROR
END CATCH
END     -- main

For instance, is there a nice way to move that error handler out of the stored proc so the logic can be shared and not duplicated inside each procedure?  Notice it can be nice to include the values of the parameters in that error message (exampleParam above).

Do you agree or disagree with my stance on handling transaction rollbacks in stored procs?  (lack thereof)

Do you have or can you write an example of better boilerplate along with a description of where my approach falls short and why your version might be a better starting point

What about SET XACT_ABORT {ON | OFF}?  Which option for XACT_ABORT would be a best practice?


texts: Decoding binary coded decimal (BCD) value

texts:
I have 3 questions, all of them are concerned with binary coded decimal (BCD) conversion. My coding snippets are listed as follows. But I don't like my algorithm because it takes too long when dealing with tons of data.

Any suggestions to improve the performance? Would you please show me an efficient and fast way to do that?

The value is expressed with 4-bits binary coded decimals (BCD), which was originally stored in a character buffer (for example, pointed by a pointer const unsigned char *).

BCD*2; 1001 0111 0110 0101=9765
"9"  "7"  "6"  "5"

unsigned int BCDn( unsigned int n, const unsigned char * data )
{
    unsigned int uResult = 0;
    unsigned char ucTmp;
    int iTmp1,iTmp2;

    for (unsigned int i=0;i<n;i++)
    {
        ucTmp = data[i];
        iTmp1 = (ucTmp & 0xf0) >> 4;
        iTmp2 = ucTmp & 0x0f;
        uResult += (iTmp1*10+iTmp2) * static_cast<unsigned int>(pow(100.0,static_cast<int>(n-1-i)));
    }

    return uResult;
}

The value is expressed by n binary integer (n* 8-bits). The first bit (MSB) defines
the sign of binary integer; "0" signifies that it's a positive integer, and "1" for negative one. In the case of negative number, the other bits show the complement number that is added 1.

         MSB          LSB
    I*2; 00101101 1001100=19999
    I*2; 10101101 10011100=(-1)*(0101101 10011100
                          =(-1)*(1010010 01100100) (after complement)
                          =-21092

int SINTn(unsigned int n, const unsigned char *data)
{
    int nResult;
    bool bNegative = false;

    if ((data[0] & 0x80)!= 0)
        isNegative = true;

    nResult = data[0] & 0x7f;

    for (unsigned int i=1;i<n;i++)
        nResult = nResult * 0x100 + data[i];

    if (bNegative)
        nResult = nResult - static_cast<int>(pow(2.0,static_cast<int>(n*8-1)));

    return nResult
}

unsigned int UINTn(unsigned int n, const unsigned char *data)
{
    unsigned int uResult = 0;

    for (unsigned int i=0;i<n;i++)
        uResult = uResult * 0x100 + data[i];

    return uResult;
}

R*n.m

The value is expressed by n-bytes (n*8 bits) binary number, the first bit (MSB)
defines the sign of it; "0" means positive and "1" means negative. The number m means
that the binary number should be multiplied by 10-m to get the value.

           MSB                        LSB
    R*4.0: 00000000 00000000 00000111 10110101=1973
    R*4.2: 00000000 00000000 00000111 10110101=1973*10-2=19.73
    R*4.5: 10000000 00000000 00000111 10110101=-1973*10-5= -0.01973
    R*2.0: 10101101 10011100 =-11676

double REALnm(unsigned int n, unsigned int m, const unsigned char * data)
{
    double dResult;
    bool bNegative = false;

    if ((data[0] & 0x80)!= 0)
        isNegative = true;

    dResult = data[0] & 0x7f;

    for (unsigned int i=1;i<n;i++)
        dResult = dResult * 0x100 + data[i];

    if (bNegative) dResult *= -1.0;

    dResult *= pow(10.0, (-1.0) * m);

    return dResult;
}


texts:
In order to practice some Haskell, I tried this kata, where the task is to add some numeric inputs that are delimited by commas or newlines.

I have the below solution in Haskell which passes my tests, but could anyone offer any improvements? It feels a bit messy to me so feedback on how to make it more functional (my experience is pretty much all OO until now) would be great!

Known failings:

This does not try to be smart about invalid syntax so the pattern matching is not exhaustive - would the best solution here be to use a try/either type? This seemed like it would add quite a bit of noise at this stage so for now I have left this. It also does not fail on negative numbers for the same reason.

Code:

module Calculator where

import Data.List.Split

defaultDelimiters = [",", "\n"]

readInt :: String -> Int
readInt = read

splitAtDelims :: ([String], String) -> [String]
splitAtDelims (delims, body) = foldr splitEachOnSubStr [body] delims
    where
        splitOnSubStr = split . dropBlanks . dropDelims . onSublist
        splitEachOnSubStr = concatMap . splitOnSubStr

parseDelim :: String -> String -> (String, String)
parseDelim (']':xs) delim = (delim, xs)
parseDelim (x:xs) delim = parseDelim xs (delim++[x])

parseCustomDelimiters :: [String] -> String -> ([String], String)
parseCustomDelimiters [] (delim:'\n':body) = ([[delim]], body)
parseCustomDelimiters delims ('\n':rest)   = (delims, rest)
parseCustomDelimiters delims ('[':rest)    = parseCustomDelimiters newDelims remainingText
    where
        parsed = parseDelim rest ""
        newDelims = delims ++ [fst parsed]
        remainingText = snd parsed

parse :: String -> ([String], String)
parse ('/':'/':text)    = parseCustomDelimiters [] text
parse body              = (defaultDelimiters, body)

add :: String -> Int
add = sum . filter (< 1000) . map readInt . splitAtDelims . parse


texts:
This is a follow-on qestion from: LRU cache design

Revised Implementation

package lrucache;

import java.util.LinkedHashMap;

public class LRUCacheV2<K, V> extends LinkedHashMap<K, V>{

    private static final int MAX_ENTRIES = 3;
         /**
     * super class constructor arguments are
     * cache size = MAX_ENTRIES
     * load factor = 0.75F
     * access order = true
     */
    public LRUCacheV2(){
        super(MAX_ENTRIES,0.75F,true);
    }

    @Override
    protected boolean removeEldestEntry(java.util.Map.Entry<K, V> entry) {
        return size() > MAX_ENTRIES;
    }

    public static void main(String[] args) {
        LRUCacheV2<String, Integer> cache = new LRUCacheV2<String, Integer>();
        cache.put("abc", 1);
        cache.put("def", 2);
        cache.put("ghi", 3);
        cache.put("jkl", 4);
        cache.put("mno", 5);
        cache.put("abc", 1);
        System.out.println(cache);
    }
}

Output

{jkl=4, mno=5, abc=1}


texts:
I have a php authentication script and everything works fine, but I'm very unsure about the way I programmed it (I hardcoded some things). I was hoping stack could look through this and point out any potential problems. Here's the script:

<?php
require_once 'Bcrypt.php';
class Mysql {
    private $conn;

    function __construct() {
        $this->conn =  new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or
                      die('There was a problem connecting to the database.');
    }

    function verify_Username_and_Pass($un, $pwd) {
        ini_set('display_errors', 'On');
        error_reporting(E_ALL | E_STRICT);
        $query = "SELECT *
                FROM Conference
                WHERE Username = :un";

        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(':un', $un);
        //$stmt->bindParam(':pwd', $pwd);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $hash = $row[0]["Password"];
        $is_correct = Bcrypt::check($pwd, $hash);

        if ($is_correct) {
            // User exist
            $firstName = $row[0]["First Name"];
            $_SESSION["FirstName"] = $firstName;
            return true;
            $stmt->close();
        }
        else {
            // User doesn't exist
            return false;
            $stmt->close();
        }
    }
}
?>

So how does it look?


texts:
The task

is taken from leetcode

  Write a function that takes a string as input and reverse only the
  vowels of a string.

  Example 1:

  Input: "hello"

  Output: "holle"

  Example 2:

  Input: "leetcode"

  Output: "leotcede"

  Note: The vowels does not include the letter "y".

My first solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  const LEN = s.length;
  const str = [...s];
  const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
  const rev = [];
  for (let i = 0; i < LEN; i++) {
    if (vowels.includes(s[i])) { rev.push(s[i]); }
  }
  for (let i = 0; i < LEN; i++) {
    if (vowels.includes(str[i])) { str[i] = rev.pop(); }
  }
  return str.join('');
};

My second solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  if (s.length <= 1) { return s; }
  const sForward = [...s];
  const sBackward = [...s].reverse();
  const LEN = s.length - 1;
  let left = -1, right = -1;
  const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
  const findVowel = start => (x, i) => start < i  && VOWELS.includes(x);
  while(true) {
    left = sForward.findIndex(findVowel(left));
    right = sBackward.findIndex(findVowel(right));
    if (left >= LEN - right || left === -1 || right === -1) { return sForward.join(''); }

    [sForward[left], sForward[LEN - right]] = [sBackward[right], sForward[left]];
  }
  return sForward.join('');
};

My third solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  if (s.length <= 1) { return s; }
  const str = [...s];
  let left = 0;
  let right = s.length - 1;
  const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
  while(left < right) {
    if (VOWELS.includes(str[left]) && VOWELS.includes(str[right])) {
      [str[right], str[left]] = [str[left], str[right]];
      left++;
      right--;
    } else if (VOWELS.includes(str[left])) {
      right--;
    } else {
      left++;
    }
  }
  return str.join('');
};

My fourth solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  if (s.length <= 1) { return s; }
  const str = [...s];
  let left = 0;
  let right = s.length - 1;
  const map = new Map();
  map.set('a', true);
  map.set('e', true);
  map.set('i', true);
  map.set('o', true);
  map.set('u', true);
  map.set('A', true);
  map.set('E', true);
  map.set('I', true);
  map.set('O', true);
  map.set('U', true);
  while(left < right) {
    if (map.get(str[left]) && map.get(str[right])) {
      [str[right], str[left]] = [str[left], str[right]];
      left++;
      right--;
    } else if (map.get(str[left])) {
      right--;
    } else {
      left++;
    }
  }
  return str.join('');
};

My fifth solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
  if (s.length <= 1) { return s; }
  const str = [...s];
  let left = 0;
  let right = s.length - 1;
  const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);

  while(left < right) {
    if (set.has(str[left]) && set.has(str[right])) {
      [str[right], str[left]] = [str[left], str[right]];
      left++;
      right--;
    } else if (set.has(str[left])) {
      right--;
    } else {
      left++;
    }
  }
  return str.join('');
};


texts:
Please review my code:

import java.lang.*;
import java.util.*;
import java.io.*;

class NumberToWords
{
  static public boolean HelperConvertNumberToText(int num, String[] result)
  {
      String [] strones = {
        "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
        "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
        "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
      };

      String [] strtens = {
          "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
          "Seventy", "Eighty", "Ninety", "Hundred"
      };

      result[0] = "";
      int single, tens, hundreds;

      if(num > 1000)
          return false;

      hundreds = num / 100;
      num = num - hundreds * 100;
      if( num < 20)
      {
          tens = 0; // special case
          single = num;
      }
      else
      {
          tens = num / 10;
          num = num - tens * 10;
          single = num;
      }

      if(hundreds > 0)
      {
         result[0] += strones[hundreds-1];
         result[0] += " Hundred ";
      }
      if(tens > 0)
      {
         result[0] += strtens[tens - 1];
         result[0] += " ";
      }
      if(single > 0)
      {
         result[0] += strones[single - 1];
         result[0] += " ";
      }
      return true;
  }

  static public boolean ConvertNumberToText(int num, String[] result)
  {
      String tempString[] = new String[1];
      tempString[0] = "";
      int thousands;
      int temp;
      result[0] = "";
      if(num < 0 || num > 100000)
      {
          System.out.println(num + " \tNot Supported");
          return false;
      }

      if( num == 0)
      {
         System.out.println(num + " \tZero");
         return false;
      }

      if(num < 1000)
      {
          HelperConvertNumberToText(num, tempString);
          result[0] += tempString[0];
      }
      else
      {
          thousands = num / 1000;
          temp = num - thousands * 1000;
          HelperConvertNumberToText(thousands, tempString);
          result[0] += tempString[0];
          result[0] += "Thousand ";
          HelperConvertNumberToText(temp, tempString);
          result[0] += tempString[0];
      }
      return true;
  }

  public static void main(String[] args)
  {
      String [] result = new String[1];
      result[0] = "";
      int  i, num;
      int [] arrNum =
      {
        -1, 0, 5, 10, 15, 19, 20, 21, 25, 33, 49, 50, 72,
        99, 100, 101, 117, 199, 200, 214, 517, 589, 999,
        1000, 1010, 1018, 1200, 9890, 10119, 13535, 57019,
        99999, 100000, 100001
      };

      for (i = 0; i < arrNum.length; i++)
      {
          num = arrNum[i];
          if( ConvertNumberToText(num, result) == true)
             System.out.println(num  + "\t" + result[0]);
      }
  }
}


texts: Main loop for a text-based Blackjack game

texts:
Is there any way to reduce this code? It repeats itself, but I cannot find any way to reduce it because it is only repeating inside one elif. Sorry I'm a beginner my code is quite bad
It repeats here:
           onze(joueurs)
           print("joueur", a + 1, "a", joueurs[a])
           time.sleep(1)
           while sum(joueurs[a]) < 21 or 11 in joueurs[a]:

The code :
while t:
    input("Appuyez sur entrer pour continuer...")
    for a in range(nb):
        while sum(joueurs[a]) < 21 or 11 in joueurs[a]:
            time.sleep(0.5)
            print("main du joueur", a + 1, ":", joueurs[a], "Total :", sum(joueurs[a]))
            if sum(joueurs[a]) > 21 and 11 in joueurs[a]:
                onze(joueurs)
                print("joueur", a + 1, "a", joueurs[a])
            ask = input("Joueur {} voulez vous une carte ?(oui/non)".format(a + 1))
            if ask == "oui":
                askoui(joueurs)
            else:
                asknon()
                t = False
                break
        if sum(joueurs[a]) == 21:
            print("joueur", a + 1, "a BLACKJACK")
            time.sleep(1)
        elif sum(joueurs[a]) > 21 and 11 in joueurs[a]:
            onze(joueurs)
            print("joueur", a + 1, "a", joueurs[a])
            time.sleep(1)
            while sum(joueurs[a]) < 21 or 11 in joueurs[a]:
                time.sleep(0.5)
                print("main du joueur", a + 1, ":", joueurs[a], "Total :", sum(joueurs[a]))
                if sum(joueurs[a]) > 21 and 11 in joueurs[a]:
                    onze(joueurs)
                    print("joueur", a + 1, "a", joueurs[a])
                ask = input("Joueur {} voulez vous une carte ?(oui/non)".format(a + 1))
                if ask == "oui":
                    askoui(joueurs)
                else:
                    asknon()
                    t = False
                    break
            elif sum(joueurs[a]) > 21:
                perdu(joueurs)
                t = False
        elif sum(joueurs[a]) > 21:
            perdu(joueurs)
            t = False


texts:
This program verifies if a matrix is a Sudoku or not. These conditions should be verified:

There are no duplicates in a row, column, or square
The sum of a row, column, or square should be equal to 45

public class SudokuChecker {

static int[][] invalidMatrix={

        {5,5,5,5,5,5,5,5,5},
        {1,2,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5},
        {5,5,5,5,5,5,5,5,5}
    };

static int[][] validMatrix={

    {5,3,4,6,7,8,9,1,2},
    {6,7,2,1,9,5,3,4,8},
    {1,9,8,3,4,2,5,6,7},
    {8,5,9,7,6,1,4,2,3},
    {4,2,6,8,5,3,7,9,1},
    {7,1,3,9,2,4,8,5,6},
    {9,6,1,5,3,7,2,8,4},
    {2,8,7,4,1,9,6,3,5},
    {3,4,5,2,8,6,1,7,9}
    };

static int rSum = 0;
static int cSum = 0;
static int squareSum = 0;

static int[] rArray = new int[9];
static int[] cArray = new int[9];
static int[] squareArray = new int[9];

/*
 * check of there is duplicates
 */

public static boolean checkDuplicate(int[] array){

    Boolean duplicate = false;
    Set<Integer> set= new HashSet<>();
    for(int i : array){
        if(set.contains(i)){
            duplicate = true;
    } else {
        set.add(i);
    }
    }
    return duplicate;
}

/*
 * check if the sum of the element of a row are equals to 45
 */

public static boolean rowSum(int[][] matrix){
    boolean correct = true;
    for(int i =0; i < matrix.length; i++){
        for(int j=0 ; j < matrix[i].length; j++){
            rArray[j] = matrix[i][j];
            rSum += rArray[j];
        }
        if(rSum != 45 || checkDuplicate(rArray) ){
            correct = false;
            break;
        }
        rSum = 0;
    }
    return correct;

}

/*
 * check if the sum of the elements of a col are equals to 45
 */

public static boolean colSum(int[][] matrix){
    boolean correct = true;
    for(int j=0 ; j < matrix.length; j++){
        for(int i=0 ; i < matrix.length ; i++){
            cArray[i] = matrix[i][j];
            cSum += cArray[i];
        }
        if(cSum != 45 || checkDuplicate(cArray)){
            correct = false;
            break;
        }
        cSum = 0;
    }
    return correct;
}

/*
 * check if the sum of the elemnts of a square 3x3 are equals to 45
 */

public static boolean squareSum(int[][] matrix){
    boolean correct = true;
    for(int i=0; i < matrix.length ; i = i + 3){
        for(int j=0; j < matrix.length ; j = j +3){

            squareArray[0] = matrix[i][j];
            squareArray[1] = matrix[i][j+1];
            squareArray[2] = matrix[i][j+2];
            squareArray[3] = matrix[i+1][j];
            squareArray[4] = matrix[i+1][j+1];
            squareArray[5] = matrix[i+1][j+2];
            squareArray[6] = matrix[i+2][j];
            squareArray[7] = matrix[i+2][j+1];
            squareArray[8] = matrix[i+2][j+2];

            squareSum = matrix[i][j] + matrix[i][j+1] + matrix[i][j+2]
                      + matrix[i+1][j] + matrix[i+1][j+1] + matrix[i+1][j+2]
                      + matrix[i+2][j] + matrix[i+2][j+1] + matrix[i+2][j+2] ;
            if(squareSum != 45 || checkDuplicate(squareArray)){
                correct = false;
                break;
            } else{
                squareSum = 0;
            }
        }
    }
    return correct;
}

/*
 *  Test
 */

public static boolean test(int[][] matrix){

    boolean correct = true;
    if (!(rowSum(matrix) && colSum(matrix) && squareSum(matrix))){
        correct = false;
    }
    return correct;

}

public static void main(String[] args) {

    System.out.println(test(invalidMatrix) ? "Sudoku valide" : "Sudoku invalide");
}
}


texts:
I decided to make a Ruby app to search for songs, which uses the tinysong API. Things got really cryptic and weird in the view. I managed to get dynamic tables that adjust to data length, but I feel like there must be a much better way to accomplish this output.

require "rubygems"
require 'json'
require "httparty"

def search(search_terms)
  search_string = search_terms.split(' ').join('+')
  response = HTTParty.get("http://tinysong.com/s/#{search_string}?format=json&key=API_KEY_OMITTED_FOR_REVIEW")
  song_hash = JSON.parse(response.body)
  #puts "#{song_hash}"
end

def view_song_search(song_hash)
  term_width       = %x'tput cols'.to_i # Executes terminal
  total_char_limit = term_width - 9
  field_limit      = total_char_limit / 3

  # Sets width of each column to the width of it's highest data.
  artist_width = album_width = song_width = 0
  song_hash.each do |song|
    if song["ArtistName"].length > artist_width then artist_width = song["ArtistName"].length end
    if song["AlbumName"].length > album_width then album_width = song["AlbumName"].length end
    if song["SongName"].length > song_width then song_width = song["SongName"].length end
  end

  # Sets the minimum column width equal to header width.
  if artist_width < "Artist".length then artist_width = "Artist".length end
  if album_width < "Album".length then album_width = "Album".length end
  if song_width < "Song".length then song_width = "Song".length end

  # If total width is higher than terminal width, reduce total width to fit.
  if artist_width + album_width + song_width > total_char_limit
    artist_width = album_width = song_width = field_limit
  end

  # Where things get cryptic.
  printf("+%s+%s+%s+\n", "-" * (artist_width + 1), "-" * (album_width + 2), "-" * (song_width + 2))
  printf("\e[7m|%-#{artist_width}s | %-#{album_width}s | %-#{song_width}s |\e[0m\n", "Artist", "Album", "Song")
  printf("+%s+%s+%s+\n", "-" * (artist_width + 1), "-" * (album_width + 2), "-" * (song_width + 2))

  song_hash.each do |song|
    # Sets data of each column to not exceed column width.
    if song["ArtistName"].length > artist_width ||
       song["AlbumName"].length > album_width ||
       song["SongName"].length > song_width
      artist_name = (song["ArtistName"])[0...artist_width]
      album_name = (song["AlbumName"])[0...album_width]
      song_name = (song["SongName"])[0...song_width]
    else
      artist_name = song["ArtistName"]
      album_name  = song["AlbumName"]
      song_name   = song["SongName"]
    end

    printf("|%s%s | %s%s | %s%s |\n",artist_name, ' ' * (artist_width - artist_name.length),
                                     album_name, ' ' * (album_width  - album_name.length),
                                     song_name,   ' ' * (song_width   - song_name.length))
    printf("+%s-%s-%s+\n", "-" * (artist_width + 1), "-" * (album_width + 2), "-" * (song_width + 2))
  end
end

puts "Enter your search terms: "
view_song_search(search(gets.chomp))

And here is an example of the output:


texts: REST API with flask structure and implementation approach

texts:
I recently started writing REST API, I wanted to have a proper structure of project and an approach which is more readable and make more sense interms of organising in a logical order. I took advantage of namespace and I have put endpoints of each name space into separate python package.

project
|______init__.py
|____api
| |______init__.py
| |____base
| | |______init__.py
| | |____resources.py
| |____hello
| | |______init__.py
| | |____resources.py
| |____routes.py

project/__init__.py

from flask import Flask

def register_blueprints(app):
    # Since the application instance is now created, register each Blueprint
    # with the Flask application instance (app)
    from project.api import api_blueprint
    from project.api import base_api_blueprint
    app.register_blueprint(api_blueprint)
    app.register_blueprint(base_api_blueprint)

def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile(config_filename)
    register_blueprints(app)
    return app

project/api/__init__.py

from flask import Blueprint

api_blueprint = Blueprint('api', __name__, template_folder='templates')
base_api_blueprint = Blueprint('base_api', __name__)

from . import routes
from .hello import resources
from .base import resources

project/api/routes.py

from flask_restplus import Resource

from . import api_blueprint, base_api_blueprint

base_api = Api(base_api_blueprint, catch_all_404s=True, prefix='/api', version='1.0', title='Sample API',
               description='A sample API',
               )

base_api.namespaces.pop(0)

base_api_ns = base_api.namespace('todos', description='base api namespace.')
hello_api_ns = base_api.namespace('hello', description='Hello World api.')

project/api/base/resources.py

from flask_restplus import Resource

from ..routes import base_api_ns

@base_api_ns.route('/base', endpoint='base-endpoint')
class BaseResource(Resource):
    def get(self):
        return {"from": "base"}

project/api/hello/resources.py

from flask_restplus import Resource

from ..routes import hello_api_ns

@hello_api_ns.route('/world', endpoint='world-endpoint')
class BaseResource(Resource):
    def get(self):
        return {"hello": "world"}

the rest api web app, has api that deals with two different type of tasks base and hello so I have segregated to a separate package and used different name space for each.

having a second API object of api_blueprint would rather make more sense but that seems not work maybe due to a bug in flask restplus.
the swagger finally renders up like this:

Any input in implementation or improvement will be highly appreciated.


texts: Executing query via nested inner class query handler

texts:
Background

I often see blogs/articles split out the implementation of the Query and QueryHandler classes. I had briefly asked a question on Stack Overflow about whether or not a self-executing Query class would be a violation of SOLID design principals (I deleted the question as it was feeling like the wrong place to ask for feedback). My opinion was that a Query class represents a single operation within a system, and that the separation of parameters/execution was unnecessary in most cases...

I understand that in some cases there may be legitimate reasons for doing so (i.e., using Query object AS your view model, not to my taste). One comment on the original question suggested the inability to cleanly apply decorators to a merged Query class in order to enhance query execution and although I had considered the suggestions at the time to be the responsibility of a QueryProcessor, it got me thinking: as modification of one will more often than not result in modification of the other. Perhaps nesting the handler class would be a happy middle ground as shown in the implementation below.

Implementation

/// <summary>
/// Query definition used to retrieve a specific user by their username.
/// </summary>
public sealed class GetUserByUsernameQuery : Query<User>
{
    /// <summary>
    /// The unique user username to locate.
    /// </summary>
    public Username Username { get; }

    /// <summary>
    /// Initializes a new instance of <see cref="GetUserByUsernameQuery"/>.
    /// </summary>
    /// <param name="username">The unique user username to locate.</param>
    public GetUserByUsernameQuery(Username username)
    {
        if (username == null) throw new ArgumentNullException(nameof(username));

        Username = username;
    }

    /// <summary>
    /// Handles processing of a <see cref="GetUserByUsernameQuery "/> instance.
    /// </summary>
    internal sealed class Handler : SqlQueryHandler<GetUserByUsernameQuery, User>
    {
        /// <summary>
        /// Executes the specified <paramref name="query"/> instance.
        /// </summary>
        /// <param name="query">The query instance to process.</param>
        protected override IEnumerable<User> Execute(GetUserByUsernameQuery query)
        {
            using (var connection = OpenConnection())
                return connection.Query<User>("SELECT * FROM [dbo].[GetUserByUsername](@username);", query);
        }
    }
}

NOTE: No comments regarding SELECT *. The Inline Table Function explicitly selects only the required columns for the result set and I see no reason to define the columns again in the code.

I know some people consider inner classes to be evil, however in this case my thinking is that an inner class provides a nice balance between a self-executing Query and full separation between the Query/QueryHandler classes (i.e., easy to edit within a single file).

My rational:

There will only ever be a single handler class per query.
The handler will often have to be modified if the query class were to change.
Allows for decorators etc to be applied to the QueryHandler if required.
The QueryHandler class really cannot exist without the Query class.

Are there any major downsides to going down this path? Any other suggestions on how to achieve balance between the two ends of the spectrum? I would also be interested in feedback on using inline table functions for Dapper queries. I typically place my SQL in embedded resource files or a resource file, but I thought this might be better option?

NOTE: My use case does not require that the Query/QueryHandler ever need to live in different assemblies; thus dependencies are not a concern. And worst case, I could easily refactor if required.


texts: A better implementation of the `execvp` call: the code implements `execvp`

texts:
I'm trying to implement execvp () using execv (). I don't know if the code is the best implementation.
my code:
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>

extern char **environ;

int my_execvp(char *file, char *argv[])
{
  char *p, *colon, *pathseq = getenv("PATH");
  size_t len;

  if(strchr (file, '/'))
    return execv(file, argv);

  if (pathseq == NULL) {
        len = confstr(_CS_PATH, (char *) NULL, 0);
        pathseq = (char *) alloca(1 + len);
        pathseq[0] = ':';
        (void) confstr (_CS_PATH, pathseq + 1, len);
  }
  len = strlen(file) + strlen(pathseq) + 2;

  for(p = pathseq; p && *p; p = colon)
  {
     char b[len];
     colon = strchr(p, ':');
     if(colon)
     {
        memcpy(b, p, (size_t) (colon - p));
        b[colon++-p] = 0;
     }
     else
        strcpy(b, p);
     strcat (b, "/");
     strcat (b, file);
     if(!access(b, F_OK)) {
            execv(b, argv);
            fprintf(stderr, "an error occurred in execv\n");
            abort();
     }
   }
   errno = ENOENT;
     return -1;
}

int main()
{
    /* "ls / -l" */
    char *arg[] = {"ls", "/", "-l", NULL};
    my_execvp (arg[0], arg);

    return 0;
}

And the question I have, is it a good implementation? How could it be improved or write a better implementation?


texts: Algorithms to find statistical information of an array

texts:
I was working on a program that creates an array, then gives statistical information about that array such as std dev, median, mode average etc.

I have written a method for each statistical value, however I am not too sure that they are efficient, particularly the getMode() method.

I would be really happy if you helped me to make these methods memory efficient and fast as possible. Thanks, here are my methods:

private static int getMode(int[] x) {

    int max_mode = 0;
    int count = 0, count_max = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] == x[j]) {
                count++;
            }
        }
        if (count >= count_max) {
            count_max = count;
            max_mode = x[i];
        }
        count = 0;
    }
    return max_mode;
}

private static double getMedian(int[] x) {
    int[] sorted = x;
    sort(sorted);
    double median;
    if (sorted.length % 2 == 0) {
        median = sorted[(sorted.length / 2 - 1 + sorted.length / 2) / 2];
        median += 0.5;
    } else {
        median = sorted[sorted.length / 2];
    }

    return median;

}

private static int[] sort(int[] x) {
    int temp;
    int[] sorted = x;
    for (int i = 1; i < sorted.length; i++) {
        for (int j = 0; j < sorted.length; j++) {
            if (sorted[i] < sorted[j]) {
                temp = sorted[i];
                sorted[i] = sorted[j];
                sorted[j] = temp;
            }
        }
    }
    return sorted;
}

private static double getAverage(int[] x) {
    double sum = 0;
    double avg;
    for (int i = 0; i < x.length; i++) {
        sum += x[i];
    }
    avg = sum / x.length;
    return avg;

}

private static int getSum(int[] x) {
    int sum = 0;
    for (int i = 0; i < x.length; i++) {
        sum += x[i];
    }
    return sum;
}

private static int getMax(int[] x) {
    int tempmax = 0, realmax = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] > x[j]) {
                tempmax = x[i];
            }

        }
        if (tempmax > realmax) {
            realmax = tempmax;
        }
        tempmax = 0;
    }
    return realmax;
}

private static int getMin(int[] x) {
    int templow = 0, reallow = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] < x[j]) {
                templow = x[i];
            }
        }
        if (templow <= reallow) {
            reallow = templow;
        }
        templow = 0;
    }
    return reallow;
}

private static double getStdDev(int[] x) {
    double sum = 0;
    double avg = getAverage(x);
    for (int i = 0; i < x.length; i++) {
        sum += (x[i] - avg) * (x[i] - avg);
    }
    return Math.sqrt(sum / (x.length - 1));
}


texts:
I was said to post this as a new question. I improved my code from:

Little part of the string to integer parser vs Clean Code

However I think that it break SRP as it parses, iterates through string and checks if letters are numeric. Could someone involved in OOP say what does he think of it? I agree that wrapping Index in class was a mistake, but it lost modularity in my opinion. I also see duplication in two IntegerParser's methods however I'm not sure how to remove it. In the end I think this is much less open for adding new functionalities.

Main.java

public static void main(String[] Args)
{
        IntegerParser intparser = new IntegerParser();
        System.out.println(intparser.getFirstNumber( "lolo543" ));
}

IntegerParser.java

package intparser;

public class IntegerParser
{
    private String parsingText;
    private int startIndex;
    private int lastIndex;

    public int getFirstNumber(  String textToParse )
    {
        parsingText = textToParse;
        startIndex = getIndexOfFirstNumericChain(0);
        lastIndex = getIndexOfLastNumberInChain(startIndex);
        if ( startIndex == -1 )
            return -1;
        if ( lastIndex == -1 )
            lastIndex = parsingText.length();
        return Integer.parseInt( parsingText.substring(startIndex, lastIndex) );
    }

    private int getIndexOfFirstNumericChain( int index )
    {
        if ( index < 0 ) return -1;
        for ( int i = index; i < parsingText.length() ; i++ )
            if (numberAt(i)) return i;
        return -1;
    }

    private int getIndexOfLastNumberInChain( int index )
    {
        if ( index < 0 ) return -1;
        for ( int i = index; i < parsingText.length() ; i++ )
            if (!numberAt(i)) return i;
        return -1;
    }

    private boolean numberAt( int index )
    {
        char letter = parsingText.charAt(index);
        if (  letter >= '0' && letter <= '9' )
            return true;
        return false;
    }
}


texts: Same function but use different array data

texts:
I have these two carousels that randomly pick up pictures. [fiddle] Each of them picks up pictures and links from their own different inner array. It works fine as it is, but I was just wondering if there's any part that I can encapsulate/shorten. The only thing I can come up with that doesn't return any error is them sharing the same $(document).ready(function(){ [fiddle].

$('#carousel1').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });

$('#carouselu').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });

var theImages = [
                ['img1','url_1'],
                ['img2','url_2'],
                ['img3','url_3'],
                ['img4','url_4'],
                ['img5','url_5'],   ];

var shuffled = [];

while (theImages.length) {
    shuffled.push(theImages.splice(Math.random() * theImages.length, 1)[0]);
}

$(document).ready(function(){

var imgPath = "/pic/";
var urlPath = "/url/";

    $("#carousel1 .1").each(function(index){
        $(this).prepend('');

    });

});

/* Second rotator */

var theImagesabc = [
                ['imga','url_a'],
                ['imgb','url_b'],
                ['imgc','url_c'],
                ['imgd','url_d'],
                ['imge','url_f']    ];

var shuffledabc = [];

while (theImagesabc.length) {
    shuffledabc.push(theImagesabc.splice(Math.random() * theImagesabc.length, 1)[0]);
}

$(document).ready(function(){

var imgPath = "/pic/";
var urlPath = "/url/";

    $("#carouselu .u").each(function(index){
        $(this).prepend('');

    });

});


texts: Attempt at method to draw diamond (recursive or not ?)

texts:
I'm not so good with recursion, so I've decided to tackle an exercise consisting of drawing this pattern using characters:

      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *

Here is my code so far. What could be improved? Furthermore, is recursion suitable for a task like this or not?

class Main
{
    public static void main (String[] args)
    {
        Main.drawDiamond("*", 0, 5 );
    }

    public static void drawDiamond( String seed, int turn, int centerLevel ){

        if( seed.length() <= 0 ){
            return;
        }

        char[] chars = new char[Math.abs(turn-centerLevel-1)];
        Arrays.fill(chars, ' ' );
        String spaces = new String(chars);

        System.out.print( spaces );

        System.out.println( seed );

        if( turn <= centerLevel ){
            seed += "**";
        } else {
            if( seed.length() >= 3 ) {
                 seed = seed.substring(1,seed.length()-1);
            } else {
                seed = "";
            }
        }

        turn++;

        drawDiamond( seed, turn, centerLevel );
    }
}


texts:
I have few models like this below for diferent tools i manage. I am trying to clean/improve the code... Could you help me?

All the informations comes inside columns B to N, and the column P concatenate it with ";". There are 6 sheets i do the same thing.

Any ideas to have a better performance and cleaner code?

Private Sub bov_mobile()
Sheets("Mobile").Select
Columns("p").Clear
fim = Cells(Rows.count, 1).End(xlUp).Row

For i = 2 To fim
Range("A" & i).Select

    If ActiveCell.Offset(0, 14).Value = "BOV" Or ActiveCell.Offset(0, 14).Value = "BOV BMF" Then
        Range("P" & i).FormulaR1C1 = "=RC[-14]&"";""&RC[-13]&"";""&RC[-12]&"";""&RC[-11]&"";""&RC[-10]&"";""&RC[-9]&"";""&RC[-8]&"";""&RC[-7]&"";""&RC[-6]&"";""&RC[-5]&"";""&RC[-4]&"";""&RC[-3]&"";""&RC[-2]&"";"""
        Range("P" & i).Copy
        Selection.PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
    End If
Next i

    ' ###############  ORDER BY
    Range("p2", Cells(Rows.count, 16).End(xlUp)).Select
    Selection.Sort Key1:=Range("P2"), Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

Range("P2", Cells(Rows.count, 16).End(xlUp)).Copy

Sheets("Mod_Bov").Select
Cells(Rows.count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

End Sub


texts: refactor Python code with lots of None type checks

texts:
When I wrote this it just felt messy due to the null checks.  Any good ideas on how to clean it up would be most appreciated.

 def getItemsInStock(self):
        itemsInStock = []
        items = self.soup.find_all("ul", {'class':re.compile('results.*')})
        getItems = [x for x in items if x.find("div", class_="quantity")]
        if getItems:
            itemsInStock += getItems
        pages = self.combThroughPages()
        if pages:
            for each in pages:
                self.uri = each
                soup = self.createSoup()
                items = soup.find_all("ul", {'class':re.compile('results.*')})
                if items:
                    inStock = [x for x in items if x.find("div", class_="quantity")]
                    if inStock:
                        itemsInStock += inStock
        if itemsInStock:
            return self.__returnItemDetailAsDictionary(itemsInStock)
        else:
            return None


texts:
I am using following code to download a csv file using Web API. Maximum file size will be less than 500mb. How can I improve this code?

[HttpPost, Route("api/files/getfile")]
public HttpResponseMessage GetDataFileResponse(string filePath) {
    try {

        FileStream fileStream = File.OpenRead(filePath);
        long fileLength = new FileInfo(filePath).Length;

        var response = new HttpResponseMessage();
        response.Content = new StreamContent(fileStream);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = "mydata.csv";
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentLength = fileLength;
        return response;
    } catch (Exception e) {
        Console.WriteLine(e);
        throw;
    }
}


texts: Embolden parts of auto-complete suggestions that don't match the query

texts:
I made a function to embolden text that doesn't match a string, but it appears to be very performance-heavy. I am certain that there are much better ways to do this, but with what I tried, I ran into a lot of trouble.

As a side note, one of the ways I know this is performance-heavy, is that when I type a few characters, and backspace them all, Chrome starts taking up more and more memory until it crashes.

Yes! I know this is not StackOverflow, so I'm just asking for some pointers on what the issues are with the code.

function Bolden(value, query) {
    var arr = []
    if (!value) return;
    while (value !== "") { // While the value still has work to be done on it
        if (value.toLowerCase().startsWith(query.toLowerCase())) {
            arr.push("" + value.slice(0, query.length) + "")
            value = value.slice(query.length, value.length)
        }
        else {
            arr.push(value.slice(0, 1))
            value = value.slice(1, value.length)
        }
    }
    return arr.join('')
}


texts:
Given the need to share several big models throughout an application (web application, the models need to persist between requests), I would like to create a unified cache handler to keep them in memory. Creating the models from disk is expensive. There's an abstract model container which handles the cache management. The users of the library need only to extend that abstract handler and specify how to create the model.

Type erasure stood in the way of first attempt, since class Foo<T> { static T foo; } is not allowed. There's no way to distinguish Foo<Bar> from Foo<Baz> at runtime, so you can't have static access to a generic class member. The resulting code is somewhat awkward, since users need to specify which type of model they want. The models are further classified by language, which is handled by an enum type Language.

abstract class AbstractModel<T> {

    private static final Logger log = Logger.getLogger(AbstractModel.class);
    protected static Map<Language, Map<Class<?>, Object>> cache =
         new HashMap<>();

    public final T request(Class<T> c, Language language) throws NoModelException {
        final Map<Class<?>, Object> langCache = AbstractModel.cache.getOrDefault(
                language,
                this.makeCache(c, language)
        );

        final Object o = langCache.getOrDefault(c, this.create(language));
        if (c.isInstance(o)) {
            return c.cast(o);
        } else {
            throw new NoModelException(
                    "Wrong model type '" + o.getClass() +
                    "', expected '" + c.getName() + "'."
            );
        }
    }

    private Map<Class<?>, Object> makeCache(Class<T> c, Language language)
        throws NoModelException {
        final HashMap<Class<?>, Object> newCache = new HashMap<>();
        final T newModel = this.create(language);
        newCache.put(c, newModel);
        return newCache;
    }

    protected abstract T create(Language language)
        throws NoModelException;
}

The provider now extends abstract model:

public class HmmModel extends AbstractModel<HmmDecoder> {
    @Override
    protected HmmDecoder create(Language language) throws NoModelException {
        final HiddenMarkovModel hmm = new HiddenMarkovModel(fromResource);
        return new HmmDecoder(hmm);
    }
}

The user can request a new model thus:

HmmDecoder tagger = new HmmModel().request(HmmDecoder.class, ENGLISH);

You have to instantiate the inheriting classes, because request can't be static for the same reason fields can't be static (it references the generic variable T on its return type.)

I'm not sure this is the most elegant or efficient solution — but it doesn't have to be super-efficent. There's a about two dozen models, no big deal. I'm more aiming for ease of use and a sound implementation. I'm more concerned about storing the models as Object, and the resulting casts (though I think they should be safe.) The nested maps and retrieval from them are also somewhat messy.


texts: Using temporary variables or calling a method directly

texts:
Which of these approaches for a button click is better/faster/more efficient, and why?

Approach One:

Button button = (Button) findViewById(R.id.button_english_splash);

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT)
                .show();
    }
});

Approach Two:

((Button) findViewById(R.id.button_english_splash))
        .setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(v.getContext(), "Clicked!",
                        Toast.LENGTH_SHORT).show();

            }
        });


texts: Procedural generation of an infinite map made up of 1's and 0's

texts:
This is my function to procedural generate an infinite random map of 1's and 0's it only calculates what you can see at the time and when the view moves it calculates the next rows.

Complexity is the size of the view that is on the screen e.g. if complexity = 7 then the view on the screen is a grid 7x7.

It works fine but how can I tidy this up, simplify the code and make it more elegant?

void CreateMap(){
    if(complexity%2==0) {
        complexity--;
    }

    if (randomseed) {
        levelseed=Time.time.ToString();
        Debug.Log ("Random");
    }

    psuedoRandom = new System.Random(levelseed.GetHashCode());
    offsetx=psuedoRandom.Next();
    levellocation=psuedoRandom.Next();
    offsety=psuedoRandom.Next();
    level = new int[complexity,complexity];
    for (int x=0;x<complexity;x++){
        for (int y=0;y<complexity;y++){
            level[x,y]=RandomReturn(x+offsetx,y+offsety);
        }
    }
}

int RandomReturn(int x, int y){
    psuedoRandom = new System.Random(x*y*levellocation.GetHashCode());
    return (psuedoRandom.Next (0,2));
}

An example of moving right

void MoveRight(){
    offsetx++;
    for (int x=0;x<complexity-1;x++){
        for (int y=0;y<complexity;y++){
            level[x,y]=level[x+1,y];
        }
    }

    for (int y=0;y<complexity;y++){
        level[complexity-1,y]=RandomReturn(complexity-1+offsetx,y+offsety);
    }
}


texts:
One of the app is inserting date in UTC format (column CreateDate). When reporting from this table, I used a difference in hours between the inbuilt GetUTCDate() and GetDate() and added the same to the CreateDate column. I was hoping to not worry about the daylight time. Is this approach OK?

SELECT GetUTCDate()
SELECT GetDate()
DECLARE @DifferenceInHoursBetween INT
SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE())
SELECT  USER_ID, CreateDate AS [DateTime IN UTC], DATEADD(HOUR,@DifferenceInHoursBetween,CreateDate) AS [LocalDateTime] FROM EVENTLOG(nolock)

/Tests/

SELECT GetUTCDate() AS [UTCDateTime]
SELECT GetDate() AS [LocalDateTime]
DECLARE @DifferenceInHoursBetween INT
SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE())
SELECT @DifferenceInHoursBetween AS [Difference in Hours]

-- UTCDateTime

2019-01-22 16:34:46.943

--LocalDateTime

2019-01-22 08:34:46.943

-- Difference in hours
-8


texts:
This is a simple word count program I wrote to play around and get familiar with using std::map. Is there anything I can improve upon?

I didn't use CTRL+Z to stop the program because that suspends the process on Linux.

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <iterator>
using std::cout;
using std::cin;
using std::endl;
using std::string;

int main(){
    std::map<string, int> words;
    cout << "Enter some text. Type "***" to end." << endl;

    std::istream_iterator<string> begin(cin);
    std::istream_iterator<string> end;

    while(begin != end){
        if(*begin == string("***"))
            break;
        words[*begin++]++;
    }
    for(std::map<string,int>::iterator iter = words.begin(); iter != words.end(); ++iter)
        cout << std::setw(6) << iter->second << " " << iter->first << endl;

return 0;
}

Sample input:

engie does wut engie wants
pyro mad
engie rek pyro
pyro go cry
deny engie u try
rekt u will get

Output:

 1 cry
 1 deny
 1 does
 4 engie
 1 get
 1 go
 1 mad
 3 pyro
 1 rek
 1 rekt
 1 try
 2 u
 1 wants
 1 will
 1 wut


texts:
Any idea on how to run application continuously? I tried follow suggestions from this link, but to no avail. It might be because of my coding but I don't know how to amend it. Someone suggested that I use Windows Service, but I don't want to use it at this moment because I want to learn basics first like in the above link.

Program.cs

        static int exitFlag = 0;

        private static int m_intErrCounter = 0;
        static int Main(string[] args)
        {
            int retValue = 0;

            while (exitFlag != 0)
            {
                retValue = CounterApp();
            }
            //return retValue;
            return 0;
        }

        public static int CounterApp()
        {
            string machineName = ConfigurationManager.AppSettings["MachineName"];
            string categoryName = ConfigurationManager.AppSettings["CategoryName"];
            string counterName = ConfigurationManager.AppSettings["CounterName"];
            string instanceName = ConfigurationManager.AppSettings["InstanceName"];
            PerformanceCounterCategory pcc;
            PerformanceCounter[] counters;
            m_intErrCounter = 0;

            try
            {
                // Create the appropriate PerformanceCounterCategory object.
                if (machineName.Length > 0 && instanceName.Length > 0)
                {
                    pcc = new PerformanceCounterCategory(categoryName, machineName);
                    counters = pcc.GetCounters(instanceName);
                }
                else
                {
                    pcc = new PerformanceCounterCategory(categoryName);
                    counters = pcc.GetCounters();
                }

            }
            catch (Exception)
            {
                Console.WriteLine("Couldn't found the application");
                Console.ReadKey();
                return 0;
            }

            String strBody = String.Empty;
            if (counters.Length != 0)
            {

                for (int objX = 0; objX < counters.Length; objX++)
                {
                    if ((counters[objX].CounterName == counterName) && (counters[objX].RawValue > 0))
                    {
                        strBody = "Error occured at " + counters[objX].InstanceName.ToString();
                        strBody += " : " + counters[objX].CounterName.ToString() + " thrown " + counters[objX].RawValue.ToString() + " times.";
                        m_intErrCounter++;
                        exitFlag = 1;
                    }
                }
            }
            if (m_intErrCounter > 0)
            {
                SendMail("Notification Email", strBody);
                exitFlag = 1;
            }
            return exitFlag;
        }

        private static void SendMail(String strSubj, String strBody)
        {
            MailSettingsSectionGroup mMailSettings = new MailSettingsSectionGroup();
            string mMailFrom = mMailSettings.Smtp.From;
            string mMailHost = mMailSettings.Smtp.Network.Host;
            int mMailPort = mMailSettings.Smtp.Network.Port;
            string mMailUserName = mMailSettings.Smtp.Network.UserName;
            string mMailPassword = mMailSettings.Smtp.Network.Password;

            string to = ConfigurationManager.AppSettings["To"];

            MailMessage Message = new MailMessage();
            Message.From = new MailAddress(mMailFrom);
            Message.To.Add(new MailAddress(to));

            Message.Subject = strSubj;
            Message.Body = strBody;

            SmtpClient client = new SmtpClient(mMailHost, mMailPort);

            client.EnableSsl = false;
            client.Credentials = new System.Net.NetworkCredential(mMailUserName, mMailPassword);

            client.Send(Message);
            Console.WriteLine("Success Send Message");
        }
    }
}


texts:
The original problem is:

  Define the height of a binary tree to be the number of nodes in the
  longest path from the root to a leaf. The empty tree is considered to
  have height 0. A node is k-balanced if its left and right subtrees
  differ in height by at most k. A tree is k-balanced if all of its
  nodes are k-balanced. The empty tree is considered to be k-balanced.

  For example, the tree below has height 4.

    o
   / \
  o   o
 / \
o   o
   /
  o

  This tree is 2-balanced but not 1-balanced, because the left subtree
  of the root has height 3 and the right subtree of the root has height
  1. Your task is to write a method that takes a balance factor k and a number of nodes n and returns the maximum height of a k-balanced tree
  with n nodes.

One of the answer(right and fast) is:

int fewest_node(int k,int h)
{
    if(h <= 0)
        return 0;
    return 1+fewest_node(k,h-1)+fewest_node(k,h-1-k);
}

int maxHeight2(int k, int n)
{
    for(int h = 1;;h++)
        if(fewest_node(k,h) > n)
            return h - 1;
}

and my solution(terribly slow) is:

int maxHeight(int k, int n)
{
    int i,left,right;
    if(k >= n)
        return n;
    if(n > 2)
    {
        left = maxHeight(k,n-1);
        if(left <= k)
            return left+1;
        else
        {
            i = n - 2;
            left = maxHeight(k,i);
            right = maxHeight(k,n-1-i);
            while((left - right) > k)
            {
                i--;
                left = maxHeight(k,i);
                right = maxHeight(k,n-1-i);
            }
            return left+1;
        }
    }
    else
        return n;
}

My question:

Is my solution really correct? I mean, does it work regardless of its efficiency? Or in other words, is it right logically? (BTW, I think it's right, and I have tested the output when n is less than 30)
Why is my solution so slow? As you can see, I'm a newbie to DSA.


texts: Delete companies with the least number of flights

texts:
I have solved the task of

Delete the companies that made the least number of flights.

the visual table diagram is here. The exercise is here
This is my source code -it's "arrow antipattern" , what is more elegant solution?
the inner most counts num of flights and groups by company, this is used to compare and find the actual minimum, then just select company names and delete.
DELETE FROM company
WHERE  name IN (SELECT name
                FROM   (SELECT name
                        FROM   trip
                               INNER JOIN company
                                       ON trip.company = company.id
                        GROUP  BY name
                        HAVING Count(trip.id) = (SELECT Min(kolv) AS mini
                                                 FROM   (SELECT
                                                Count(trip.id) AS kolv
                                                         FROM   trip
                                                INNER JOIN company
                                                        ON trip.company
                                                           =
                                                           company.id
                                                         GROUP  BY name
                                                         ORDER  BY kolv)k)) o)


texts:
I have an array of thing objects, each of which has an array of categories. I'd like to build a category hash with a category ID for a key and an array of things for a value.

category_hash = Hash.new

things.each { |thing|
  thing.categories.each { |category|
    category_hash[category] = Array.new unless category_hash[category]
    category_hash[category] << thing
  }
}

Purely for education, how can this be shortened?


texts: Making line by line replacements using values from multiple arrays

texts:
I currently have a Python script that parses a file (in this case an XML file) and makes line by line replacements as necessary, depending on the values of multiple arrays. As it stands now the script works great, but feel like it could be a lot better. I'll also need to add few more arrays later on and am worried about performance.

Additionally, the way I currently have it set up doesn't allow for counting and printing the total replacements that have been made. (e.g. "Replaced: xyz -- Made XX replacements") While not an immediate requirement, I'd like to add this functionality in the future.

arrayOne = ["old string one", "new string one"]
arrayTwo = ["old string two", "new string two"]

# Variable 'path' collected from command line input
f = open(path, "r", encoding="utf8")
newFile = open(path.replace(".xml", "-new.xml"), "w", encoding="utf8")

def replace(a,b):
    for data in f:
        for datatype in (arrayOne, arrayTwo):
            data = data.replace(datatype[a], datatype[b])
        newFile.write(data)
    newFile.close()

replace(0,1)

f.close()


texts:
I wrote a procedural version of Hangman (very basic) and would appreciate some feedback on the following points:

Is the basic logic OK? Any obvious improvements?
Any details or matters of style I need to address?
Var vs Const vs Let - I'm probably all over the place with this. My basic approach was "If it needs to be global, use var, if it's not going to change, use Const and if it is going to change but is not global, use Let."

I'm aware that a procedural approach may not be the best, but I wanted to focus on it for this program.

HTML:

<button id="play">Play</button>

JS:

var secretWord;
var playing = false;
var wrongGuesses;
var limit = 4;
var solutionSoFar;

const words = [
    "fish",
    "cat",
    "chicken",
    "freedom",
    "turnip"
];

function displayBoard() {
    console.log( solutionSoFar.join( " " ) );
}

function playAgainDialogue() {
    if ( confirm( "Play again?" ) ) {
        console.log( "" );
        play();
    }
    console.log( "Bye!" );
}

function play() {

    playing = true;

    // Set secret word
    secretWord = words[ Math.floor( Math.random() * words.length ) ];

    wrongGuesses = 0;

    // initialize solution
    const numLetters = secretWord.length;
    solutionSoFar = new Array( numLetters ).fill( "_" );

    // Display instructions
    console.log( "Guess one letter at a time to reveal the secret word." );

    while ( playing ) {
        displayBoard();
        playerTurn();
    }

}

function playerTurn() {

    // Out of turns
    if ( wrongGuesses >= limit ) {
        console.log( "You have used all your guesses. Game Over." );
        playing = false;
        playAgainDialogue();
        return;
    }

    // Player wins
    if ( solutionSoFar.join( "" ) === secretWord ) {
        console.log( "Yay, you guessed it!" );
        playing = false;
        playAgainDialogue();
        return;
    }

    // get player guess
    let remainingGuesses = limit - wrongGuesses;
    let playerGuess = prompt( "Guess a letter. You have " + remainingGuesses + " remaining guesses" ).toLowerCase();
    if ( secretWord.indexOf( playerGuess ) === -1 ) {
        console.log( "That letter in not in the secret word." );
        wrongGuesses += 1;
        return;
    }

    // Successful guess
    console.log( "Well done." );
    solutionSoFar.forEach( function( val, index ) {
        if ( secretWord.split( "" )[ index ] === playerGuess ) {
            solutionSoFar[ index ] = playerGuess;
        }
    } );
}

document.getElementById("play").addEventListener("click", play);


texts:
The purpose of this code is to find the largest palindrome in a string. It works fine when the string is short, but every time I test this code with 1000+ characters in a string, it takes forever to give me the palindrome in it.

PalindromeFinder::PalindromeFinder(){}

string PalindromeFinder::toString(){

stringstream ss;
ss << "largest palindrome seen so far is \"" << this->
           getLargestPalindromeFound();
ss << "\" with size " << this->getSizeOfLargestPalindromeFound();
return ss.str();
}

string PalindromeFinder::getLargestPalindromeFound(){
return this->largestPalindromeFound;
}

int PalindromeFinder::getSizeOfLargestPalindromeFound(){
return this->largestPalindromeFound.length();
}

string str="djclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjssssssevessssssfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjfdjclsodjf";

truncateToLargestPalindrome(str);

void PalindromeFinder::truncateToLargestPalindrome(string& inputString){

string empty="";

inputString.erase(remove_if(inputString.begin(), inputString.end(), ::isspace), inputString.end());

inputString.erase(remove_if(inputString.begin(), inputString.end(), ::ispunct), inputString.end());

inputString.erase(remove_if(inputString.begin(), inputString.end(), ::isdigit), inputString.end());

for(int i = 0; i < inputString.length(); i++){
for (int j = inputString.length(); j>=i; j--) {
    string subStr = inputString.substr(i, j-i);
    if(isPalindrome(subStr) && subStr.length() > empty.length())

        empty = subStr;

}

   }

   }

How can I improve my code so it can handle large strings more quickly?