texts: ImportExcel for Dataset with Multiple tables

texts:
I need to be able to create an Excel document with multiple tabs for a dataset with multiple results\data tables. I have a stored procedure with 3 selects in them, fairly simple ones pulling data from the sys tables in SQL Server.

Below is my script where I am assuming there will be 5 tables, if there are more then it will be missed and if there are less and then the other tabs will be empty.

What's the best way to loop through the dataset and create the Excel document?

$SQLServer = '.\SQLEXPRESS';
$Database = 'AdventureWorks';
$sqlCommand = "SELECT 'Tables' AS DataSetName, * FROM sys.tables

SELECT 'Columns' AS DataSetName, * FROM sys.columns";

$connectionString = "Server=$SQLServer;Database=$Database;Integrated
Security=true"
$connection = New-Object
System.Data.SqlClient.SqlConnection($connectionString)
$command = New-Object System.Data.Sqlclient.Sqlcommand($sqlCommand,
$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) > null
$connection.Close()

foreach($table in $dataset.Tables)
{
    Write-Host $table.TableName
    if ($($table.TableName) -eq 'table'){$Table1 = $table}
    if ($($table.TableName) -eq 'table1'){$Table2 = $table}
    if ($($table.TableName) -eq 'table2'){$Table3 = $table}
    if ($($table.TableName) -eq 'table3'){$Table4 = $table}
    if ($($table.TableName) -eq 'table4'){$Table5 = $table}
}

$DataToGather = @{
    table = {$Table1}
    table1 = {$Table2}
    table2 = {$Table3}
    table3 = {$Table4}
    table4 = {$Table5}
}

Export-MultipleExcelSheets -Show -AutoSize 'C:\Temp\Test.xlsx' $DataToGather

$DataToGather.Clear()


texts: Finding a substring within a string using regular expressions

texts:
I'm new to Java and is trying to find a substring within a string using regular Expressions. I was just wondering if there are any alternative ways to achieve the same goal, or in a more elegant or efficient manner.

while (true) {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter your regex:");

    Pattern pattern
            = Pattern.compile(br.readLine());

    System.out.println("\nEnter input string to search:");
    Matcher matcher
            = pattern.matcher(br.readLine());

    boolean found = false;
    while (matcher.find()) {
        System.out.format("I found the text"
                + " \"%s\" starting at "
                + "index %d and ending at index %d.%n",
                matcher.group(),
                matcher.start(),
                matcher.end());
        found = true;
    }
    if (!found) {
        System.out.println("No match found.");
    }
}


texts:
[Test]
public void Post_ReturnsCorrectModel()
{
    var post = new Post
    {
        Slug = "continuing-to-an-outer-loop",
        Title = "Continuing to an outer loop",
        Summary = "When you have a nested loop, sometimes",
        Content = "When you have a nested loop, sometimes",
        PublishedAt = DateTime.Now.AddDays(7),
        Tags = new Collection<Tag> { new Tag { Name = "Programming" } }
    };

    repository.Setup(expression => expression.Find("continuing-to-an-outer-loop"))
              .Returns(post);

    var viewResult = (ViewResult) controller.Post("continuing-to-an-outer-loop");
    var actual = viewResult.Model as PostViewModel;

    Assert.NotNull(actual);

    Assert.AreEqual(actual.Slug, post.Slug);
    Assert.AreEqual(actual.Title, post.Title);
    Assert.AreEqual(actual.Summary, post.Summary);
    Assert.AreEqual(actual.Content, post.Content);
    Assert.AreEqual(actual.PublishedAt, post.PublishedAt);
    Assert.AreEqual(actual.Tags, post.Tags);
}

Hopefully the purpose of this test is already clear but to further clarify - the repository exposes a Post object that is mapped to a PostViewModel. I then proceed to assert that the action method returns the correct model.

The action method looks like this:

public ActionResult Post(string slug)
{
    Post post =
        repository.Find(slug);

    if (post == null || post.Draft)
    {
        return HttpNotFound();
    }

    return View("Post", post.MapTo<PostViewModel>());
}

Could you please review this test? My particular areas of concern are as follows:

Is the test well named?  (I adopted the name from  here).
Must I assert that each property is equal as I have above? I feel as though I can make a reasonable assumption that if one property is equal then the rest will be too.
Here I am modelling the post object based on a real blog post. I do not think that the value of each property really matters and that I could very well have used arbitrary strings. Are there any best practices regarding which test data to use?
Would it be reasonable to extract the post object to another class and expose it using a factory of sorts? This will reduce the ceremony of my test and keep things DRY. Are there any best practices regarding this?


texts: Is this approach correct when testing an Angular controller?

texts:
I'd like someone to review these tests to make sure I'm along the right lines in Angular testing.

Note - They do all pass (great) but I feel like I'm struggling to understand the finer points of Angular testing.

Any thoughts?

var headerControllers = angular.module('header.controllers', []);
headerControllers.controller('headerController', ['$scope', 'headerService', function($scope, headerService){

this.headerService = headerService;
this.headerTitle = headerService.headerTitle;
this.show = false;

$scope.$watch('header.headerService.headerTitle', function (newVal, oldVal, scope) {
    if(newVal) {
        $scope.header.headerTitle = headerService.headerTitle;
        $scope.header.show = true;
    } else {
        $scope.header.show = false;
    }
});
$scope.header = this;
}]);

Above is the controller to be tested and below are the tests:

describe( "Unit Test:  Header Bar Controller", function() {

var scope, headerService, headerBarController;
var title = "Test header title";

beforeEach( module('Header.controllers'));
beforeEach( module('Header.services') );
beforeEach( inject( function( $injector, $rootScope, $controller, _headerService_ ) {

    scope = $rootScope.$new();

    headerService = $injector.get( 'headerService' );
    headerService.setTitle( title );

    headerBarController = $controller( 'HeaderController',
    {
       $scope: scope,
       headerService: headerService
    });

}));

it( "should have the controller defined", function() {
    expect( headerBarController ).not.toBe( undefined );
});

it( "should receive and load the header-service", function() {
    expect( headerService ).not.toBe( undefined );
    expect( headerBarController.headerService ).toBe( headerService );
});

it( "should have a header title set to the value received from the header-service", function() {
    expect( headerBarController.headerTitle ).toBe( title );
});

it( "should have an initial show value of false", function() {
    expect( headerBarController.show ).toBe( false );
});

it( "should set the header object show value to true when the title is changed", function() {

    headerService.headerTitle = title;
    scope.$apply();

    expect( scope.header.show ).toBe( true );
});

it( "should have header object show value of false if title is not set", function() {

    expect( scope.header.show ).toBe( false );
});

});


texts: Spring service for playing Rock Paper Scissors

texts:
I had created a service which does the actual play of Rock Paper Scissors.

Below is the service which takes a PlayRequest and updates the State of Player objects given by the PlayerService.

So the consumer of the API knows about winner, loser or tie by doing a GET on a Player.

One of the things I feel wrong NOW is that the method play takes a PlayerRequest but uses it only for two lines, all other work is done from the injected dependencies.

Would appreciate any comments related to State as well as SOLID principles.

@Service
public class GameplayService {

  private PlayerService playerService;

  private GameSessionService gameSessionService;

  public GameplayService(GameSessionService gameSessionService, PlayerService playerService) {
    this.gameSessionService = gameSessionService;
    this.playerService = playerService;
  }

  public void play(PlayRequest playRequest) throws RPSException {
    GameSession currentSession = gameSessionService.sessions().get(playRequest.getInviteCode());
    Player player = playerService.changePlayerState(playRequest.getPlayerName(), State.PLAYING);
    currentSession.changeStateTo(GameSession.State.PLAYING);
    try {
      Turn turn = new Turn(player, Enum.valueOf(Move.class, playRequest.getMove()));
      if (currentSession.rounds().isEmpty()) {
        createNewRound(turn, currentSession);
      } else if (!currentSession.rounds().isEmpty()) {
        Round latestRound = currentSession.latestRound();
        if (OVER.equals(latestRound.getState())) {
          createNewRound(turn, currentSession);
        } else if (PLAYING.equals(latestRound.getState())) {
          latestRound.pushLatestTurn(turn);
        }
      }
      Round latestRoundAfterAllUpdates = currentSession.latestRound();
      Optional<Result> resultOptional = latestRoundAfterAllUpdates.getResult();
      if (resultOptional.isPresent()) {
        currentSession.changeStateTo(GameSession.State.WAITING);
        Result result = resultOptional.get();
        if (result.isTie()) {
          currentSession.setTie(true);
        } else {
          currentSession.setWinner(result.getWinner());
        }
        currentSession.getFirstPlayer().changeStateTo(State.WAITING);
        currentSession.getSecondPlayer().changeStateTo(State.WAITING);
      }
    } catch (InvalidOperationException e) {
      throw new RPSException(e.getMessage());
    }
  }

  private void createNewRound(Turn turn, GameSession gameSession) {
    gameSession.addRound(new Round(turn));
  }

}


texts:
Python has that range:

>>> range(10, -20, -3)
[10, 7, 4, 1, -2, -5, -8, -11, -14, -17]

I have this C++ implementation of exactly the same facility:

range.h:

/*
 * File:    range.h
 * Author:  Rodion "rodde" Efremov
 * Version: (Nov 30, 2015)
 */

#ifndef RANGE_H
#define RANGE_H
#include <stdexcept>

namespace coderodde {

    template<typename Int = int>
    class range {
    private:
        Int m_start;
        Int m_end;
        Int m_step;

        class range_iterator {
        private:
            Int    m_value;
            Int    m_step;
            size_t m_count;

        public:
            range_iterator(Int value,
                           Int step,
                           size_t count) : m_value{value},
                                           m_step{step},
                                           m_count{count} {}

            int  operator*() { return m_value; }
            bool operator!=(range_iterator& other) { return m_count != other.m_count; }
            void operator++() { m_value += m_step; ++m_count; }
        };

    public:
        range(Int start, Int end, Int step) : m_start{start},
                                              m_end{end},
                                              m_step{step} {}

        range(Int start, Int end) : range(start, end, 1) {}

        range_iterator begin() { return range_iterator(m_start, m_step, 0); }

        range_iterator end() {
            if (m_step == 0) throw std::runtime_error("The step is zero.");

            if (m_start <= m_end)
            {
                if (m_step < 0)
                {
                    return range_iterator(0, 0, 0);
                }

                return range_iterator(m_start, m_step,
                                     (m_end - m_start) / m_step +
                                   (((m_end - m_start) % m_step) ? 1 : 0));
            }
            else
            {
                if (m_step > 0)
                {
                    return range_iterator(0, 0, 0);
                }

                m_step = -m_step;
                return range_iterator(m_start, m_step,
                                     (m_start - m_end) / m_step +
                                   (((m_start - m_end) % m_step) ? 1 : 0));
            }
        }
    };
}

#endif  /* RANGE_H */

With demo main.cpp:

#include <iostream>
#include "range.h"

using std::cin;
using std::cout;
using std::endl;
using coderodde::range;

int main(int argc, char* argv[])
{
    while (true)
    {
        int start = 0;
        int end   = 0;
        int step  = 0;

        cout << ">> ";

        if (not (cin >> start >> end >> step))
        {
            break;
        }

        try
        {
            for (auto i : range<>(start, end, step))
            {
                cout << i << endl;
            }
        }
        catch (std::runtime_error& err)
        {
            cout << "Error: " << err.what() << endl;
        }
    }

    cout << "Bye!" << endl;
}

I tried hard to make my range act exactly the same way is in Python (2.7). For instance, if step is 0, an exception is thrown.

I do not have much experience in C++, so any critique is much appreciated.


texts: PHP Custom $_GET checker function performance

texts:
I'm trying to follow the DRY programming philosophy and I am tired of running isset() and an if not empty statements for each time I want to check a $_GET[] variable.

I am working on a page that receives up to 4-5 GET parameters in the URL, so I wrote the following function to reduce repetitive code:

function getset( $get, $default, $empty=FALSE ) {
   // checks if a GET parameter is set
   if ( isset($_GET[$get]) ) {
      // optionally allows empty values
      if ($empty) { return $_GET[$get]; }
      // check if value is not empty
      else {
         if ( $_GET[$get] != '' ) { return $_GET[$get]; }
         // otherwise return default value
         else { return $default; }
      }
   }
   // if param not set then return default value
   else { return $default; }
}

// set the variables
$foo = getset('foo', 'abc');
$bar = getset('bar', 'xyz', TRUE)

// localhost/?foo    => returns 'abc'
// localhost/?foo=x  => returns 'x'
// localhost/?bar    => returns TRUE / ''

I am wondering if my function is proper, efficient and safe compared to the alternative:

// default values
$foo = 'abc';
$bar = '';

// set $foo from $_GET value
if ( isset($_GET['foo']) && $_GET['foo'] != '' ) {
    $foo = $_GET['foo'];
}
// set $bar from $_GET value
if ( isset($_GET['bar']) ) {
    $bar = $_GET['bar'];
}

I am open to suggestions for improving/refining my code.


texts:
Now I am doing Project Euler number 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

This is my code, which runs in 0 milliseconds:

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int sumNums = 0;

    for(int i = 0; i < 1000; i++)
    {
        if (i % 3 == 0 || i % 5 == 0) { sumNums += i; }
    }

    s.Stop();

    Console.WriteLine(sumNums);
    Console.WriteLine(s.ElapsedMilliseconds);
}

I also have this version, which also runs in 0 milliseconds.  In fact, running both methods in the same timer together results in 0 milliseconds:
static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int sumNums = 0;

    for (int i = 0; i < 1000; i += 3)
    {
        sumNums += i;
    }

    for (int i = 0; i < 1000; i += 5)
    {
        sumNums += i % 3 == 0 ? 0 : i;
    }

    s.Stop();

    Console.WriteLine(sumNums);
    Console.WriteLine(s.ElapsedMilliseconds);
}

What could be improved, and which version is better?


texts: Handling data from an HTML table using jQuery

texts:
I have the following table:

    Corredor
    Id Corrdor
        <input type="text" value="dfdfgdf23231fg" class="validate" name="idcorreo" />

    Nombre
        <input type="text" value="rertretert" class="validate" name="nombre" />

    Email
        <input type="text" value="vikrambanand@gmail.com" class="validate" name="email" />

    Empressa
        <input type="text" value="dfdfdf" class="validate" name="Empressa" />

    Pagina Web
        <input type="text" value="dfdfdf" class="validate" name="paginaWeb" />

    Telefono
        <input type="text" value="34454355" class="validate" name="telephon" />

    Cellular
        <input type="text" value="2323" class="validate" name="cellular" />

        <input type="button" id="updateBtn" value="Update" name="Update" style="float:left" />

To handle this, I have the following jQuery code:

 $(document).on('click', '#updateBtn', function () {
    var locations = [],
        rows = [],
        content = {};
    $('.rowUpdate').each(function (i) {
        var feed = [];

        $(this).find('td').each(function (j, v) {
            var label = $(this).html();
            if (j == 0) feed = feed + label;
            if (j != 0) {

                var input = $("input", this),
                    name = input.attr("name").substring(0, input.attr("name").length),
                    value = input.val();
                //alert(value);
                content[name] = value;
                //alert(JSON.stringify(content));
            }
            if (j == 7) {
                feed = feed + '=' + JSON.stringify(content);
            }
        });
        alert(feed);
        rows.push(feed);
    });

});

Can there be a better script to handle this? What I am trying to do is to save the content of the row in a form of string in the array row.


texts: Creating a PowerShell Streamer Function w/youtube-dl, ffmpeg & ffplay

texts:
My question is in regards to combining youtube-dl, ffmpeg, ffplay and PowerShell to handle video URLs.

Some examples I've seen have piped a binary stream from youtube-dl to an external player using the Windows Command Prompt as demonstrated:

youtube-dl --output - "https://youtube.com/mygroovycontent" | mpc-hc.exe /play /close -

This works fine in Command Prompt as it does not mangle the binary stream. If you try and run the same command in PowerShell it doesn't handle the binary stream so well and modifies the output, making it unreadable to the external player.

In light of this I've written the following PowerShell function to get around this issue. It tries to mirror a similar function I've written in Bash (see this).

The reason I've handled youtube-dl, ffmpeg and ffplay separately is that defining the ffmpeg binary location in youtube-dl as an external program creates some issues when passing it in PowerShell.

I was hoping that someone could take a look at my script and provide some feedback on what I have done here and if it can be improved upon or if a better implementation is already available.

Function streamer
{

Param
(
[string] $streamURL
)

Begin
{
}

Process
{
$streamDir = "$env:TEMP\YTD.d"

$ytdBin = "Z:\PortableApps\CommandLineApps\youtube-dl\youtube-dl.exe"
$streamExtractor = &$ytdBin --no-warnings --get-url $streamURL

$ffmpegBin = "Z:\PortableApps\CommandLineApps\ffmpeg-20170702-c885356-win64-static\bin\ffmpeg.exe"
$ffplayBin = "Z:\PortableApps\CommandLineApps\ffmpeg-20170702-c885356-win64-static\bin\ffplay.exe"

if
(
-not (Test-Path -Path $streamDir -PathType Any)
)

{
New-Item $streamDir -type directory -ErrorAction SilentlyContinue
}

Start-Process -FilePath $ffmpegBin -ArgumentList "-loglevel quiet -i $streamExtractor -c copy $streamDir\streamContainer.m2ts" -NoNewWindow -ErrorAction SilentlyContinue

Do
{
Start-Sleep -Seconds 1
}

Until
(
(Get-Item $streamDir\streamContainer.m2ts -ErrorAction SilentlyContinue).Length -gt 256kb
)

&$ffplayBin -loglevel quiet $streamDir\streamContainer.m2ts

if
(
(Test-Path -Path $streamDir -PathType Any) -eq $true -and (Get-Process -Name ffplay -ErrorAction SilentlyContinue) -eq $null
)

{

Do
{
Stop-Process -Name ffmpeg -ErrorAction SilentlyContinue
}

Until
(
(Get-Process -Name ffmpeg -ErrorAction SilentlyContinue) -eq $null
)

Remove-Item $streamDir -Recurse -ErrorAction SilentlyContinue
}
}

End
{
}

}

streamer -streamURL https://www.youtube.com/watch?v=9uFXw7vKz14


texts:
As pyglet has no in-built method to return a vertex list of circle, I had to build one myself. This is a critical piece of code that I will use very frequently. I need it to be of very fine performance.

Here's what I've written:

""" Pyglet utilities. Designed to ease drawing of primitives with Pyglet. """

# Dependencies
import pyglet
from math import sin, cos, pi

# Constants
TAU = 2 * pi

def circle(x, y, r, n, c, b):
    """ Adds a vertex list of circle polygon to batch and returns it. """
    rad = TAU / n # getting 360 / n in radians
    index = list(chain.from_iterable( (0, x-1, x)  for x in range(2, n+1) ))
    index.extend( (0, 1, n) ) # end of fan
    p = x, y # adding center of fan
    for i in range(1, n+1):
        d = rad * i
        p += int(r * cos(d)) + x, int(r * sin(d)) + y
    p += x+r, y # adding end of fan
    return b.add_indexed(n+2, pyglet.gl.GL_TRIANGLES, None, index, ('v2i', p), ('c3B', (c+c[-3:])))

This is a test that draws a circle of increasing quality:

import pyglet
from utilities import circle

# Constants
WIN = 900, 900, 'TEST', False, 'tool' # x, y, caption, resizable, style
CENTER = WIN[0] // 2, WIN[1] // 2
RADIUS = 450
SPEED = 0.3 # in seconds

# Color constants
WHITE = (255, 255, 255) # for center
RED = (255, 0, 0)       # for points

# Variables
win = pyglet.window.Window(*WIN)
win.set_location(510, 90)
batch = pyglet.graphics.Batch()
n = 3 # starting with triangle

def on_step(dt):
    """ Logic performed every frame. """
    global batch, n
    batch = pyglet.graphics.Batch()
    circle(CENTER[0], CENTER[1], RADIUS, n, WHITE+RED*n, batch)
    n += 1

@win.event
def on_draw():
    """ Drawing perfomed every frame. """
    win.clear()
    batch.draw()

pyglet.clock.schedule_interval(on_step, SPEED)
pyglet.app.run()

This is a test that adds more and more circles to the batch:

import pyglet
from utilities import circle
from random import randrange

# Constants
WIN = 900, 900, 'TEST', False, 'tool', False, True, False # vsync off to unlimit fps
RADIUS = 30
CORNERS = 20

# Color constants
WHITE = (255, 255, 255) # for center
RED = (255, 0, 0)       # for points

# Variables
win = pyglet.window.Window(*WIN)
win.set_location(510, 90)
batch = pyglet.graphics.Batch()

def on_step(dt):
    """ Logic performed every frame. """
    global counter
    x = randrange(RADIUS, WIN[0] - RADIUS)
    y = randrange(RADIUS, WIN[1] - RADIUS)
    circle(x, y, RADIUS, CORNERS, WHITE+RED*CORNERS, batch)

@win.event
def on_draw():
    """ Drawing perfomed every frame. """
    win.clear()
    batch.draw()

pyglet.clock.schedule(on_step)
pyglet.app.run()

I would be glad if you would help to make my method faster, more readable and better overall.

And by the way, this is another version that uses GL_TRIANGLE_FAN and doesn't work because I don't know how to cut off one circle from another. You can try it out:

def circle2(x, y, r, n, c, b):
    """ Adds a vertex list of circle polygon to batch and returns it. """
    rad = TAU / n # getting 360 / n in radians
    p = x, y # adding center of fan
    for i in range(n):
        d = rad * i
        p += int(r * cos(d)) + x, int(r * sin(d)) + y
    p += x+r, y # adding end of fan
    return b.add(n+2, pyglet.gl.GL_TRIANGLE_FAN, None, ('v2i', p), ('c3B', (c)))

but use

# Additional specification of the last gradient
circle(x, y, RADIUS, CORNERS, WHITE+RED*CORNERS+RED, batch)

instead.

Oh, and my math:


texts:
I have a case where I match data from DB by the various filters. Until the match is updated in the DB, I don't want to accept requests for matching with the same criteria, as this could produce duplicate matches. Therefore I "lock", but selectively using AsyncLock from AsyncEx library.
I've checked the correctness of the implementation with logging and it seems do do things right, but Is my implementation correct and without dead-lock risk? This is in the web app, so the AsyncLock in static ConcurrentDictionary will be long-lived. Should it matter?

public class Handler
{
    /// <summary>
    /// Container of objects that we lock over for matching the data.
    /// </summary>
    private static readonly ConcurrentDictionary<string, AsyncLock> LockMap = new ConcurrentDictionary<string, AsyncLock>();

    public async Task<MyResult> Handle(Command command, CancellationToken cancellationToken)
    {
        string lockKey = $"{command.SomeValue1}_{command.SomeValue2}";

        using (await LockMap.GetOrAdd(lockKey, _ => new AsyncLock()).LockAsync())
        {
            var allocations = await repository.GetDataAsync(command.SomeValue1, command.SomeValue2);
            var result = Process(allocations);
            return await repository.UpdateAsync(result);
        }
    }
}


texts: Given two strings, a and b, determine the minimum number of character deletions required to make a and b anagrams

texts:
I'm trying to figure out how my code could be improved. I solved a HackerRank problem from the Cracking the Coding Interview section, and am thinking that it should be able to be solved a simpler than what I did.

The problem is as follows:

  Strings: Making Anagrams

  Alice is taking a cryptography class and finding anagrams to be very
  useful. We consider two strings to be anagrams of each other if the
  first string's letters can be rearranged to form the second string. In
  other words, both strings must contain the same exact letters in the
  same exact frequency For example, bacdc and dcbac are anagrams,
  but bacdc and dcbad are not.

  Alice decides on an encryption scheme involving two large strings
  where encryption is dependent on the minimum number of character
  deletions required to make the two strings anagrams. Can you help her
  find this number?

  Given two strings, a and b, that may or may not be of the same
  length, determine the minimum number of character deletions required
  to make a and b anagrams. Any characters can be deleted from
  either of the strings.

  Input Format

  The first line contains a single string, a. The second line contains
  a single string, b.

  Constraints

  \$1 \le |a|,|b| \le 10^4\$
  It is guaranteed that a and b consist of lowercase English alphabetic letters (i.e., a through z).

  Output Format

  Pring a single integer denoting the number of characters you must
  delete to make the two strings anagrams of each other.

  Sample Input

cde
abc

  Sample Output

4

  Explanation

  We delete the following characters from our two strings to turn them
  into anagrams of each other:

  Remove d and e from cde to get c.
  Remove a and b from abc to get c.

  We must delete 4 characters to make both strings anagrams, so we print
  4 on a new line.

My Implementation

I am using C++, and since strings are immutable, what I decided to do was to create two int arrays (vectors, actually) that hold the ASCII value of the chars in each string. Then I would sort the vectors. Then I would iterate through the arrays together, counting the number of elements that don't exist in the other.

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int calcDeletions(vector<int> a, vector<int> b) {

    int deletions = 0;
    int ai = 0;
    int bi = 0;

    // step through arrays until the end of one is reached
    while (ai < a.size() && bi < b.size()) {
        if (a[ai] < b[bi]) {
            deletions++;
            ai++;
        }
        else if (a[ai] > b[bi]) {
            deletions++;
            bi++;
        }
        else {
            ai++;
            bi++;
        }
    }

    // carry over left-overs
    deletions += (a.size() - ai);
    deletions += (b.size() - bi);

    return deletions;
}

int number_needed(string a, string b) {
    vector<int> aInt;
    vector<int> bInt;

    // create two int vectors to store ascii val of strings
    for (int i = 0; i < a.length(); i++) {
        aInt.push_back((int)a.at(i));
    }
    for (int i = 0; i < b.length(); i++) {
        bInt.push_back((int)b.at(i));
    }

    // sort vectors
    sort(aInt.begin(), aInt.end());
    sort(bInt.begin(), bInt.end());

    // call calcDeletions function with the longer vector passed as first arg
    if (aInt.size() > bInt.size()) {
        return calcDeletions(aInt, bInt);
    }
    else {
        return calcDeletions(bInt, aInt);
    }
}

int main() {
    string a;
    cin >> a;
    string b;
    cin >> b;

    cout << number_needed(a, b) << endl;
    return 0;
}

What is a better, more efficient way of solving this problem?


texts: Ruby Beginner - Fuzzy matching / string manipulation

texts:
There is no intended end use for this. It is for learning and development only.

I got carried away following an example and ended up with a miniaturised vehicle registration system. You can bulk generate records, each of which is given a unique registration number in keeping with British registration format. I've written a script that compares and lists all registration numbers that fall afoul of the criteria.

It does work, but it is incredibly slow. (over an hour to check 1 mil records).
I am looking for critique on the logic and any optimisation I may have missed.

Example string:    AA99AAA

Example criteria:  A?9?AAA

 def full_search(offensive_list)
    p 'Full check:'
    p "Comparing #{$all_vehicles.count} records against #{offensive_list.count} banned combinations"
    p 'This will take a few minutes'
    vrm_array, example_array = [], []
    vrm_list = $all_vehicles.keys.sort
    vrm_list.each do |vrm|
        vrm_array << vrm.split("") #We split each reg into an array of characters
    end
    offensive_list.each do |example|
        example.strip!
        example_array << example.split("") #and the same with our banned combinations
    end

        vrm_array.each do |vrm|
            example_array.each do |example| #itterate through vrms x examples
                @formatted_vrm = vrm.dup
                if example.length == vrm.length
                    example.each_index do |index|
                        if example[index] == "?" #for each wildcard we add a wildcard to the vrm for comparison
                            @formatted_vrm[index] = "?"
                        end
                    end
                    if @formatted_vrm == example then offensive_found(vrm, example) end
                end
            end
        end
end

def offensive_found(vrm, example)
    built_vrm = ""
    built_example = ""
    if vrm.class == Array #clean up formatting so we can store it
    vrm.each do |character|
            built_vrm << character
        end
        example.each do |character|
            built_example << character
        end
    else
        built_example = example #clearly redundant, but it works so...
        built_vrm = vrm
    end

    if $bad_vrms[built_example] # if we already have a record
        prev_matched = $bad_vrms[built_example] #just add to the array
        prev_matched << built_vrm
        $bad_vrms.store(built_example, prev_matched)
    else
        new_match = [built_vrm]        # or create a new hash key
        $bad_vrms.store(built_example, new_match)
    end
    #p "#{built_vrm} - matched with #{built_example}"
end

If you'd prefer you can clone the full thing on github. https://github.com/Niall47/RubySomDemo


texts: Prime factorization of numbers up to 1000

texts:
I was reading Mathematics: A Very Short Introduction and it mentioned prime factorization. Being a curious person I had to write my own implementation in Perl.

This program outputs the prime factorization of the numbers between 0 and 1001.

I don't like listing all of my subroutines before everything else, but I'm not sure what would be a better alternative.

Also, I remember seeing somewhere a non-bruteforce way of discovering whether a number is a prime. Does anyone have any ideas? I'm a beginner/intermediate Perl programmer and would appreciate suggestions on improving my technique.

#!/usr/bin/perl
use strict;
use warnings;
use 5.010;

#This array will contian the results of the factorization
our @result;

sub factorize {
  my($num,$factorsRef) = @_;

  # If the only factor is 1, it is a prime number
  # return the number itself since primes don't
  # factorize in the known universe
  if(${$factorsRef}[0] == 1) {
    push @result, $num;
    return;
  }

  if($num % ${$factorsRef}[0] == 0) {
    push @result, ${$factorsRef}[0];
    my $divResult = $num/${$factorsRef}[0];

    # If the result of the division is a prime
    # we have reached the end of the process
    if(isPrime($divResult)) {
      push @result, ($divResult);

    # If it is not a prime, go down to the
    # next level
    } else {
      factorize($divResult,$factorsRef);
    }

  # If the number is no longer divisible by the
  # current factor, take the factor out so that
  # the function can use te next factor
  } else {
    shift @{$factorsRef};
    factorize($num,$factorsRef);
  }
}

sub getPrimeFactors {
  my $num = shift;
  my $counter = 1;
  my @primeFactors;

  if(isPrime($num)) {
    push @primeFactors, 1;
    return \@primeFactors;
  }

  while($counter++ <= ($num / 2)) {
    next unless $num % $counter == 0;
    push @primeFactors, $counter if(isPrime($counter));
  }
  return \@primeFactors;
}

sub isPrime {
  my $num = shift;
  my $limit = $num/2;
  for(my $i=2; $i<=$limit ;$i++) {
    if ($num%$i == 0) { return 0;}
  }
  return 1;
}

sub printResults {
  my $num = shift;
  print $num . ' = ' . shift @result;
  print " x $_" for @result;
  print "\n";
}

# Where everything happens
for(1..1000) {
  my $num = $_;
  factorize($num,getPrimeFactors($num));
  printResults($num);

  @result = ();
}

Sample output:

983 = 983
984 = 2 x 2 x 2 x 3 x 41
985 = 5 x 197
986 = 2 x 17 x 29
987 = 3 x 7 x 47
988 = 2 x 2 x 13 x 19
989 = 23 x 43
990 = 2 x 3 x 3 x 5 x 11
991 = 991
992 = 2 x 2 x 2 x 2 x 2 x 31
993 = 3 x 331
994 = 2 x 7 x 71
995 = 5 x 199
996 = 2 x 2 x 3 x 83
997 = 997
998 = 2 x 499
999 = 3 x 3 x 3 x 37
1000 = 2 x 2 x 2 x 5 x 5 x 5


texts:
I've started learning PHP for university-related projects today. I tried implementing a basic blog/forum. Here's the full source code.

It has the following features/design-decisions:

There are posts, which have the following fields: title, author, date and contents.
Posts have comments, which have the following fields: author, date, contents.
There is a basic login system: users can register/login with an username and password.
JSON files are used for data storage instead of a MySQL database.

There is a JSON file for posts, posts.json, which contains posts and comments.
There is a JSON file for users, which contains usernames and password hashes.

I'm looking for a full code review: I've only read the PHP manual today and while I understand most of its features I have no idea what the best practices are and how things should be implemented.

I will list below some of my main concerns with the code/design.

I have a core.php file which is included with require in every other PHP file.

It links the stylesheet at the beginning (and it could also import JS files):

    <link rel="stylesheet" type="text/css" href="./CSS/style.css">

Is this the correct way of adding the same  to every file?

Every time I want to access the user database or the posts database, I call these functions:

function getUsersDB() { return new UsersDB(); }
function getPostsDB() { return new PostsDB(); }

However, creating a new UsersDB or PostsDB instance forces a read from the .json file. I need to access these databases in multiple PHP files.

Is there a way to "cache" these UsersDB and PostsDB instances? Something similar to C++'s static, that can be shared between all PHP scripts?

When I have to generate something between HTML tags, I just call print like this:

print("");
print($mPost["author"]);
print("");

Is there an easier/better way of generating open/close tags? Should I create a function that takes a lambda like:

function doBetweenStrong($lambda)
{
    print("");
    // execute $lambda here
    print("");
}

Every page of my website has the same menu and "login status" bar. I simply call Builder::printCommon(); at the beginning of every page. Is this the best way to do it?

I keep track of the current logged-in user in $_SESSION.

class Credentials
{
    static public function isLoggedIn()
    {
        if(!isset($_SESSION["currentUser"])) return false;
        if($_SESSION["currentUser"] == "") return false;
        return true;
    }

    static public function login($mUser)
    {
        $_SESSION["currentUser"] = $mUser;
    }

    static public function logout()
    {
        unset($_SESSION["currentUser"]);
    }

    static public function getCurrentUserName()
    {
        return $_SESSION["currentUser"];
    }
}

Is this safe? What is the correct way to keep track of the currently logged-in user?

I find it hard to show the user error/success messages (for example, after registration, or after login, or after posting something). The current solution is creating a new page like registerSuccess.php or registerFailure.php.

Should I create a general message.php and pass the desired message to it using $_SESSION?

Paths. Is there a reliable way to get the server's root folder?

I'm currently using ./, ../ and ../../ to get the files I want from scripts. What if I want to move a script in the future? I would have to change all paths manually.

What if I include a script into another? Wouldn't the paths be resolved incorrectly?


texts: Place integers into a vector, sum each adjacent pair, refill vector with only the sums of each pair i.e remove all the original data from the vector

texts:
Is there a quicker/better way of doing this, mine works great for small vectors but if i get a vector with an arbitrarily large size this would probably take forever to run. Thanks.(P.S. its been a while since I've written any code so please excuse me for any sloppiness).

/*Fill a vector with integers,
sum each pair of adjacent elements,
and remove the pair of elements and place sum in the vector*/

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;
    std::cout << "Please enter a list of integers:\n";

    int num1;
    while (std::cin >> num1)
        numbers.push_back(num1);

    // starting from back of the container with integer k representing last element
    // i representing the second to last
    for (int i = numbers.size() - 2, k = numbers.size() - 1; i > -1; i-=2, k-=2) {
        numbers[i] += numbers[k];
        numbers.erase(numbers.begin() + k);
    }
}


texts: My binary search algorithm implementation in JavaScript

texts:
I have implemented binary search algorithm in JavaScript:

var myArray = [],
    searchNum = undefined;

// below function is used to capture the
// commandline parameters for array and the
// number to be searched
(function(){
    process.argv.forEach(function (val, index, array) {
        var idx = 0, ar = undefined;

        try{

            // get the commandline argument for
            // array values
            if(index === 2){
                myArray = myArray.concat(val.split(",").map(function(num){
                    return parseInt(num);
                }));
            }

            // third index is the number to be searched.
            if(index === 3){
                searchNum = parseInt(val)
            }

        }catch(e){
            console.log(e)
        }

    });
})();

console.log(" SEARCH NUMBER ",searchNum," in array ",myArray);

console.log(binary_search(myArray,searchNum,0,myArray.length));

function binary_search(numberArray, numberToSearch, lowIndex, maxIndex){
    var totalLength = maxIndex - lowIndex;

    var midIndex = parseInt(totalLength/2),
        str = "";

    /*
        If Lower Index is equal to Higher Index,
        that means number is not found and hence there is
        a collision in pointers and hence return
        as 'Can't be found'
    */
    if(lowIndex === maxIndex){
        return "can't be found";
    }

    /*
        setting the actual middle index
        by adding the computed middle index with lower index.
    */
    midIndex = lowIndex + midIndex;

    // if number found
    if(numberArray[midIndex] === numberToSearch){

        str = " Number "+numberToSearch+" found at position "+midIndex;

        return str;

    // if number in middle index is less than the number to be searched
    // set the lower Index to new value i.e. a index position next higher to
    // middle Index
    }else if(numberArray[midIndex] < numberToSearch){

        lowIndex = midIndex + 1;

    // number to be searched is less than the number present at middle Index
    // set new maxIndex value i.e. index which is previous position to the
    // middle index
    }else if(numberArray[midIndex] > numberToSearch){

        maxIndex = midIndex;

    }else{

        return "can't be found";

    }

    return binary_search(numberArray, numberToSearch, lowIndex, maxIndex);
} // end of method binary_search

When I run the above code the output is as follows,

E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>node binarySearch.js 12,34,56,78,90 24
 SEARCH NUMBER  24  in array  [ 12, 34, 56, 78, 90 ]
can't be found

E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>node binarySearch.js 12,34,56,78,90 34
 SEARCH NUMBER  34  in array  [ 12, 34, 56, 78, 90 ]
 Number 34 found at position 1

Can you please review my code and please suggest me if there is any room for
further improvement.


texts: Learning Javascript - Is this a messy implementation of a Javascript Slider?

texts:
I've been learning JS for a few months now and I've just finished creating a small image slider for a website. The sliders functionality is as follows:

Continuously cycle through images and loop back to the start
Allow the user to click through to a certain section
When clicked, the cycle timer must reset and the loop must continue from that point

cycle through a corresponding DOM element (in this case it's a testimonial quote)

I'm mainly looking for pointers on how to make my code more efficient or if I've used bad practice. Any help would be appreciated.

var container = document.getElementById('slide-container');
var button = document.getElementById('slider-buttons');
var quote = document.getElementById('quote-container');
var interval = 0;

sliderMove = function(position){

  // Move container to next image
  container.style.left = -(350 * position) + 'px';

  // Remove active classes from all children
  for (var i = 0; i < quote.children.length; i++) {
    quote.children[i].classList.remove("quote-active");
    button.children[i].classList.remove('active');
  };

  // Add active classes to specified children
  quote.children[position].classList.add("quote-active");
  button.children[position].classList.add('active');

  // Increase global interval variable by 1
  interval++;

  // Set interval back to 0 if it exceeds the amount of quotes
  if (interval >= quote.children.length) {
    interval = 0;
  };
};

// Add event listener to buttons
button.addEventListener('click', function(event){
  clearInterval(timer); // Resets timer when user clicks on an image
  autoMove(); // Restarts timer
  if (event.target.id > -1) { // Ensures the target is valid
    interval = event.target.id;
    sliderMove(interval);
  };
});

// Auto Rotate
function autoMove(index) {
  timer = setInterval(function(){
    index = interval;
    sliderMove(index);
  },5000);
}

autoMove(0);
sliderMove(0);


texts:
I have this working code tested over lots of np.arrays. It is a for-loop that walks through all the values of a np.array (x,y).

For each y-row, it finds the first x-column for which the value is different to zero. Afterward, it finds the last x-column for which value is different to 0.

Then all the columns between first x-column and last x-column are centred.

This is then repeated for all y-rows.
Example:

#Input :
array([[ 0.0,  0.149,  0.064, 0.736,  0.0],
       [ 0.0,  0.0,  0.258,   0.979,  0.618 ],
       [ 0.0,  0.0,  0.0,     0.786,  0.666],
       [ 0.0,  0.0,  0.0,     0.782,  0.954],

 #Output :
array([[ 0.0,  0.149, 0.064, 0.736, 0.0],
       [ 0.0,  0.258, 0.979, 0.618, 0.0],
       [ 0.0,  0.786, 0.666, 0.0,   0.0],
       [ 0.0,  0.782, 0.954, 0.0,   0.0],

Also:

Not all the values between first and last columns are different than zero.

for y in range(len(array)):

    begin = False
    inside = False
    end = False

    for x in range(len(array[0])):

        if (array[y][x] == 0) & (begin == True) & (end == False):
            boundary_two = ( x - 1 )
            inside = False
            end = True

        elif (array[y][x] != 0) & (inside == False):
            boundary_one = x
            begin = True
            inside = True

    y_position.append(y)
    m = np.split(array[y],[boundary_one,boundary_two])
    zeros = len(array[0])-len(m[1])
    array[y] = np.concatenate((np.zeros(zeros//2),m[1],np.zeros(int(np.ceil(zeros/2)))))

Furthermore, I added a variable(count) inside the function (which I erase for the upper code example, to simplify lecture) which count how many empty rows since last non empty rows. When count ==10, we break out of the loop. This is to save time. Once we have +/- 10 empty rows after the non-empty ones, it is sure all other y-rows will be empty as well.

Finally, I must save the value for the last y-row non-empty.

This is my script most time demanding calculation, so I was wondering if there is a way of to improve it, either by making it clearer and/or faster.

Thanks a lot, hope it is clear!


texts:
I have a WCF service that work with databse. The service should handle incoming message and store messagId into database. Please suggest me how can I improve it?

public class DBWorker
{
    static DBWorker instance;
    private string connectionString;
    private SqlConnection connection;

    protected DBWorker()
    {
        connectionString = GetConncetionString();
        connection = new SqlConnection(connectionString);
        connection.Open();
    }

    public static DBWorker Instance()
    {
        if (instance == null)
            instance = new DBWorker();
        return instance;
    }

    private string GetConncetionString()
    {
        var conn = ConfigurationManager.ConnectionStrings["FsConnectionString"];
        if (conn == null | string.IsNullOrEmpty(conn.ConnectionString))
          throw new Exception("Couln't find connection string in app.config.");
        return conn.ConnectionString;
    }

    public void StoreMessage(string messageId)
    {
        SqlCommand cmd = new SqlCommand("insert into test (MessageId) values (@MessageId)", connection);
        cmd.Parameters.AddWithValue("@MessageId", messageId);
        cmd.ExecuteNonQuery();
    }

}

My WCF:

public class HostTest : IHostTest
{
    private DBWorker dbWorker;

    public HostTest()
    {
        dbWorker = DBWorker.Instance();
    }

    public Stream HandleIncomingMessage()
    {
        var currentContext = WebOperationContext.Current;
        var request = currentContext.IncomingRequest;
        var response = currentContext.OutgoingResponse;

        string messageId = request.Headers["X-Message-Id"];

        response.StatusCode = HttpStatusCode.OK;
        response.ContentType = "text/plain";

        if (request.ContentLength == 0 )
        {
            response.StatusCode = HttpStatusCode.NoContent;
        }
        else
        {
            try
            {
                dbWorker.StoreMessage(messageId);
            }
            catch(Exception e)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
            }
        }

        return new MemoryStream(UTF8Encoding.Default.GetBytes(messageId)); ;
    }
}


texts:
I use this script to get a list of all my photos in a folder and its subfolders. However, the program seems to be really slow.

There are 50,000 .jpg pictures in this folder and subfolders. I can reduce the for loops but the program still runs more or less at the same speed.

I am open to using lambda as well but would like to use Python's basic functions at the best possible speed. Can anyone suggest an improvement?

import os
from fnmatch import fnmatch
import sys

root = "C:\\Users\\Agartha\\Desktop\\photos"
pattern = "*.jpg"

with open("./files\\list.txt", "w") as a:
    for path, subdirs, files in os.walk(root):
       for filename in files:
            if fnmatch(filename,pattern):
                a.write(str(os.path.join(filename)) + '\n')


texts:
I wrote a Rock Paper Scissors game and was hoping to get some feedback on issues like:

Am I utilizing object oriented techniques correctly?  What can I do better?
Am I using main() correctly?  My understanding is that it should be a main controller for the rest of the program.  Should I be utilizing a counter in a different method, instead of in main?
Am I using my instance variables correctly?
I realize that the computer choice is skewed.  How should I do it differently?
The way I check for wins seems a little convoluted.  Should I be using a different system to check?
What did I do well, so that I can remember to use those techniques?  What did I do poorly?

Main

import java.util.*;
public class driver {

public static void main(String[] args) {

    int userWins = 0, computerWins = 0;

    System.out.println("Welcome to Rocks, Paper, Scissors. How many games would you like to play?");
    Scanner in = new Scanner(System.in);
    int numberOfGames = in.nextInt();
    int userCounter = 0;
    int computerCounter = 0;
    for (int i = 0; i < numberOfGames; i++) {
        RPS Game = new RPS();
        String user = Game.startGame();
        String computer = Game.computerChoice();
        boolean wins = Game.evaluateGame(user, computer);
        if (wins == true){
            userWins++;
        }
        else {
            computerWins++;
        }
        System.out.println("Number of wins:");
        System.out.println("Computer: " + computerWins);
        System.out.println("User: " + userWins);
        System.out.println();
    }
  }
}

RPS

import java.util.Scanner;

public class RPS {
    String comparableChoice;
    String userComparableChoice;

        public String startGame() {
        Scanner in = new Scanner(System.in);
        System.out.println("Choose, (1)Rock, (2)Paper or (3)Scissors");
        System.out.println("enter number: 1,2 or 3");
        int userChoice = in.nextInt();

        if (userChoice == 1){
            System.out.println("Your choice: Rock");
            userComparableChoice = "Rock";
        }
        else if (userChoice == 2){
            System.out.println("Your choice: Paper");
            userComparableChoice = "Paper";
        }
        else{
            System.out.println("Your choice: Scissors");
            userComparableChoice = "Scissors";
        }
        return userComparableChoice;
    }

    public String computerChoice(){
        int computerChoiceNumber = (int)(Math.random() * 10);
        if (computerChoiceNumber <= 3){
            System.out.println("Computer choice: Rock");
            comparableChoice = "Rock";
        }
        else if (computerChoiceNumber <= 6){
            System.out.println("Computer choice: Paper");
            comparableChoice = "Paper";
        }
        else{
            System.out.println("Computer choice: Scissors");
            comparableChoice = "Scissors";
        }
        return comparableChoice;
    }

    public boolean evaluateGame(String userFormal, String computerFormal){

        if (userFormal.equals(computerFormal)){
            System.out.println("It's a tie");

        }
        if (userFormal.equalsIgnoreCase("Rock") && computerFormal.equalsIgnoreCase("Scissors")){
            System.out.println("You won!");
            return true;
        }
        if (userFormal.equalsIgnoreCase("Paper") && computerFormal.equalsIgnoreCase("Rock")){
            System.out.println("You won");
            return true;
        }
        if (userFormal.equalsIgnoreCase("Scissors") && computerFormal.equalsIgnoreCase("Paper")){
            System.out.println("You won");
            return true;
        }
        else {
            System.out.println("Computer won");
            return false;
        }

    }

}


texts:
I am using jQuery's collapsible lists grouped and named #List01, #List02, #List03, etc. My code captures clicks on list elements and remembers list items' ID for further processing. Each group has identically looking code so I was wondering how I could encapsulate it in one function.

$(document).on('click', '#List01 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List02 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List03 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});


texts:
The below code removes empty line from test.txt. I posted this answer on StackOverflow but someone commented that this code needs review and suggested me to post here. Please post your comments!

use strict;
use warnings;

my $file = "test.txt";
 open (FH, "+< $file");
my @lines = ();
my $i = 0;
while (<FH>)
{
    if ( m/^\s*$/ )
    {
        print "Found an empty line\n";
    }
    else
    {
        $lines[$i] = $_;
        $i++;
    }
}
close FH;
open (FH, "+> $file");
print FH @lines;
close FH;


texts: Learn Python the Hard Way #48 — lexicon exercise

texts:
I'm trying to get some feedback on my code for the lexicon exercise (#48) in Learn Python the Hard Way. I have only recently started learning Python and want to make sure I have my fundamentals down before progressing. I have some experience coding (only with kdb+/q in my work environment) but none in Python, so all advice is welcomed.

verb=['go','kill','eat']
direction=['north','south','east','west']
noun=['bear','princess']
stop=['the','in','of']
vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop}

def scan(sentence):
    wordlist=sentence.split()
    result=[] #initialize an empty list
    for word in wordlist:
        found=False
        for key,value in vocab.items():
            if word.lower() in value:  #convert to lower case so that we can handle inputs with both cases
                result.append((key,word))
                found=True
                break
        if not found:
            try:
                word=int(word)
                result.append(('number',word))
            except ValueError:
                result.append(('error',word))
    return result

Python version 2.6.


texts:
I wrote this pretty straight forward begin and end overloads for istream_iterator.

Is this standards compliant? Any problems with usage?

#include <iostream>
#include <iterator>
#include <fstream>

namespace std
{

    template <typename T>
    std::istream_iterator<T> begin(std::istream_iterator<T> iter)
    {
        return iter;
    }

    template <typename T>
    std::istream_iterator<T> end(std::istream_iterator<T>)
    {
        return std::istream_iterator<T>();
    }

}

int main()
{
    for (std::string s : std::istream_iterator<std::string>(std::cin))
    {
        std::cout << s;
    }
}


texts: Parsing argv with while-switch construct

texts:
I've been thinking about how to create a robust function that parses the command line arguments for valid filenames. I came up with a while-switch construct because that allows me to reduce redundancy (no break-statement at the end of case 2).

As I am pretty new to programming, I can't really tell the quality of this code.
Can you think of a way to improve this code in robustness as well as in elegance?

void spellchecker::openFiles(int argc, char* argv[]) {
    bool filesOpen = false;
    std::string dict_filename;
    std::string text_filename;

    while (filesOpen == false) {
        switch (argc) {

            case 2:
                printf("You already entered the name of the dictionary file as \"%s\". Is this correct? (y/n): ", argv[1]);
                if (std::cin.get() == 'y') {
                    printf("Ok, please enter the name of the text file you want to check: ");
                    std::cin >> text_filename;
                    break;
                }
                /* no break so user can enter both filenames*/
            default:
            case 1:
                printf("Please enter the name of the dictionary: ");
                std::cin >> dict_filename;
                printf("Please enter the name of the text file to check: ");
                std::cin >> text_filename;
                break;

                case 3:
                    dict_filename = argv[1];
                    text_filename = argv[2];
                    break;
        } // switch

                if (!dict_file.is_open()) {
                    dict_file.open(dict_filename.c_str(), std::ifstream::in);
                }
                if (!text_file.is_open()) {
                    text_file.open(text_filename.c_str(), std::ifstream::in);
                }
                if (dict_file.good() && text_file.good()) {
                    filesOpen = true;
                }
    } // while
}


texts: Push an item onto the end of array in Java

texts:
I want to make a method arrayIntPush(3, {5,4,8}) that will return {5,4,8,3}.
This method seems to work:

public static int[] arrayIntPush(int item, int[] oldArray) {
    int len = oldArray.length;
    int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);
    System.arraycopy(oldArray, 0, newArray, 0, len);
    System.arraycopy(new int[] {item}, 0, newArray, len, 1);

    return newArray;
}

Is there a better way to do this that would be faster?


texts: Append table cells to select boxes in indexed order

texts:
I am having a huge brain fart with efficiency right now.

The idea here is if I have a static table (unfortunately formatted this way with the data I've received), how would I appropriately append a select option dropdown with every value from the table categorized easily?

I currently have it working, but it seems as if I could make it more efficient than my current statement. I have the feeling with all the DOM manipulation I have going on, if I tried to use this on a table with thousands of items it would lag the browser. Let's get to the code.

JS Fiddle: http://jsfiddle.net/z2V2p/1/

HTML:

      Item 1
      Value 1
      Prop 1

      Item 2
      Value 2
      Prop 2

      Item 3
      Value 3
      Prop 3

<select id="item"></select>
<select id="value"></select>
<select id="prop"></select>

Javascript/jQuery:

$('tr td').each(function() {
    var $this = $(this);
    var text = $this.text();
    var select = '<option value="'+text+'">'+text+'</option>';
    switch($this.index()){
        case 0:
          $('#item').append(select);
          break;
        case 1:
          $('#value').append(select);
          break;
        case 2:
          $('#prop').append(select);
          break;
        default:
          alert('Unexpected Error.');
     }
});

So, I suppose the questions are:

Is there any easy way to make this more efficient?
Perhaps utilizing an array to cache the values, and append them
from that?
Or is there an easier method of using index of the items instead of
my switch case that would render quicker and be more expandable for further tds if they were implemented?

I appreciate all of the help.

I've considered just ultimately converting the darn table to a json object, but I figured I'd reach out here first. (this will deploy thousands of times per week, and I don't want anything hard coded.)

Looking for a way to add every TD in its index of its TR to be appended to an existing select option based on the index value.

Basically re-categorize columns of td elements.


texts: Feedback on hangman game about coding style

texts:
I have been playing around with python and made myself a hangman game.

Questions:

How readable my code is?
Are there any logical errors that I'm not aware of?
How to improve it?
Is there a better way to approach the problem?
Overall, how would you rate it out of 10?

import json, random, urllib.request

def get_word():
    url = urllib.request.urlopen("https://raw.githubusercontent.com/sindresorhus/mnemonic-words/master/words.json")
    words = json.loads(url.read())
    random_word = random.choice(words)
    return random_word

saved_word = []
word = get_word()
saved_word = word
length = len(word)
tries = 4

def drawing(t):
    draw = {0: '''
                    ----------
                    |        |
                    |        O
                    |       /|\\
                    |       / \\
                    |
                    -----
                ''',
            1: '''
                    ----------
                    |
                    |
                    |        O
                    |       /|\\
                    |       / \\
                    -----
                ''',
            2: '''

                    |
                    |
                    |        O
                    |       /|\\
                    |       / \\
                    -----
            ''',
            3: '''

                             O
                            /|\\
                            / \\
                    -----
                ''',
            4: '''

                             O
                            /|\\
                            / \\
                '''
            }
    d = draw[t]
    print(d)

def what_range(width):  # checks how many letters should be covered depending on the length of the word
    if width <= 3:
        return 2
    elif 3 < width < 6:
        return 3
    else:
        return 4

def mixer(w):  # creates the blanks on the word
    m = ""
    item = list(w)
    width = what_range(length)
    for z in range(width):
        n = random.randint(0, length - 1)
        if str(n) in m:
            while str(n) in m:
                n = random.randint(0, length - 1)
        if str(n) not in m:
            m = m + str(n)
            item.pop(n)
            item.insert(n, "_")
    print("".join(item))
    return "".join(item)

def find_letter(numbers, item, letter):
    i = list(item)
    for number in numbers:
        i.pop(number)
        i.insert(number, letter)
    return "".join(i)

word = mixer(word)
completed = False
while not completed:
    letter = input("enter a letter: ")
    n = 0
    nums = []
    if letter in saved_word:
        for l in saved_word:
            if l == letter:
                nums.append(n)
            n += 1
    else:
        tries -= 1
    print(f"Tries: {tries}")
    drawing(tries)
    if tries != 0:
        word = find_letter(nums, word, letter)
        print(word)
        if word == saved_word:
            print("You WIN!")
            completed = True
    else:
        print(f"You FAILED!\nThe word was {saved_word}")
        exit()


texts:
I wrote this bit of python intending it to become some module to replace excel mapping programs like MapForce.  Right now it only does columns to columns. So the number of rows in always equals the number of rows out.

To declare a map, use a python defaultdict(list) object

from collections import defaultdict

demoCmd = defaultdict(list)
demoCmd = {
    'A': [mapOper.mapVal, 'Hello, World'],
    'B': [mapOper.mapSum, 0, 1, 2],
    'C': [mapOper.mapAss, 3, 4, 5],
    'D': [mapOper.mapProd, [mapOper.mapSum, 1, 0], 0, 1],
    'E': 5
    }

The keys are the destination columns name or index.  Integers can be used as keys but they must be zero offset.  Strings are converted to zero offset integers. The Lists are the functions mapping to that column.  It's in LISP style [function arg1, arg2, etc], where integers are column indexes (zero offset) and strings are raw values. And you can nest the lists like in 'D'.

mapOper is just a file containing some commonly used functions.  Some of them I don't think I need to include eg

def mapSum(*valueList):
    filter(None, valueList)
    return sum(valueList)

Anyways the main engine is this

def evalOpList(opList, fromSheet, row):
    if type(opList) is str:  # treat arg as a value
        return opList
    elif type(opList) is int:  # treat arg as index
        return fromSheet.cell(row, opList).value
    else:  # its another function
        args = list()
        itOpList = iter(opList)
        next(itOpList)
        args = [evalOpList(it, fromSheet, row) for it in itOpList]
        return opList[0](*args)

def interpColMap(mapCmd, fmSheet, toSheet, rTop=0, rBot=0, rToTop=0):
    if rBot < 0:
        rBot = fmSheet.nrows
    MapCmdConvert(mapCmd)
    assert rTop < rBot and rToTop >= 0
    for row in range(rTop, rBot):
        for key in list(mapCmd.keys()):
            toSheet.write(row, key, evalOpList(mapCmd[key], fmSheet, row))

And you call it like this

colMapper.interpColMap(demoCmd, fws, tws)

Where fws is an worksheet from xlrd to map from and tws is a workbook from xlwt to map to.

I have already tested it some and it works.  It's just that coming from C++ this seems very odd style.  Only two function make up my program and no classes.  I also have the problem of having all ints be indexes and all strs be values.  This means I can't do += 1 to a column without doing [int, '1'].  And I don't even know if that would work.

It's just a very unique style and I need to know if it's too convoluted or not.


texts: Method to encode ordinary characters into html format

texts:
I have had a problem with encoding in a project when trying to convert certain html code into image format. It happens when we receive html that has certain characters with accents and other non standard ones.

To combat this I have the following method which finds all of the text inside html tags and then converts all of it (that aren't already in the encoded format i.e. &nbsp;) to their html escaped representation i.e. + to &#43;.

private string EncodeToHtml(string contents)
{
    Regex textRegex = new Regex("(?<!<[^>]*)(?<Text>[^<>]*)", RegexOptions.Compiled);
    Regex innerRegex = new Regex("(?<=^|;)([^&]|&(?=[^&;]*(?:&|$)))+", RegexOptions.Compiled);

    return textRegex.Replace(contents, new MatchEvaluator(m =>
    {
        return innerRegex.Replace(m.Groups["Text"].Value, new MatchEvaluator(m2 =>
        {
            string result = string.Empty;
            foreach (char c in m2.Value)
            {
                result += $"&#{(int)c};";
            }

            return result;
        }));
    }));
}

I'd appreciate any comments on the code especially anyway to make it more efficient.


texts:
Problem Statement:

  The Christmas tree is comprised of the following Parts Stand Each Part
  is further comprised of Branches. Branches are comprised of Leaves.

  How the tree appears as a function of days should be understood. Basis
  that print the tree as it appears on the given day. Below are the
  rules that govern how the tree appears on a given day. Write a program
  to generate such a Christmas tree whose input is number of days.

Rules

  1.If tree is one day old you cannot grow. Print a message "You cannot generate christmas tree"

  2.Tree will die after 20 days; it should give a message "Tree is no more"

  3.Tree will have one part less than the number of days.

  E.g.

  On 2nd day tree will have 1 part and one stand.

  On 3rd day tree will have 2 parts and one stand

  On 4th day tree will have 3 parts and one stand and so on.

  4.Top-most part will be the widest and bottom-most part will be the narrowest.

  5.Difference in number of branches between top-most and second from top will be 2

  6.Difference in number of branches between second from top and bottom-most part will be 1

  Below is an illustration of how the tree looks like on 4th day

Input Format:

  First line of input contains number of days denoted by N

Output Format:

  Print Christmas Tree for given N

  OR

  Print "You cannot generate christmas tree" if N <= 1

  OR

  Print "Tree is no more" if N > 20

Constraints:

  0<= N <=20

Sample Input and Output

  Input:  2

  Output:( below)

The code:

#include<stdio.h>

int main(){
    int i,j,leaves=1,day,rest,branches,max_leaves;
    scanf("%d",&day);

    //Check for exceptions
    if(day<=1){
        printf("You cannot generate christmas tree");
        return 0;
    }
    else if(day>20){
        printf("Tree is no more");
        return 0;
    }

    // printf("Heres Your Christmas Tree:\n\n");

    // For first part
    branches=day+1;
    max_leaves = 1+(branches-1)*2; // Arithmetic Progression
    for(i=1;i<=branches;i++){
        for(j=i;j<=max_leaves/2;j++){
            printf(" ");
        }
        for(j=1;j<=leaves;j++){
            printf("*");
        }
        printf("\n");
        leaves=leaves+2;
    }

    // For remaining parts
    branches=branches-2;
    for(rest=1;rest<=day-2;rest++){
        leaves=3;
        for(i=2;i<=branches+1;i++){
            for(j=i;j<=max_leaves/2;j++){
                printf(" ");
            }
            for(j=1;j<=leaves;j++){
                printf("*");
            }
            printf("\n");
            leaves=leaves+2;
        }
        branches--;
    }

    // For stand
    for(i=1;i<=2;i++){
        for(j=1;j<=max_leaves/2;j++){
            printf(" ");
        }
        printf("*\n");
    }

    return 0;
}

The code is working fine as can be checked on IDEOne.


texts: Project Euler #3 - how inefficient is my code?

texts:
So I am essentially a complete newbie to programming, and have been attempting to learn Python by completing the Project Euler problems. I haven't gotten very far, and this is my code for problem #3 :

  The prime factors of 13195 are 5, 7, 13 and 29.
  What is the largest prime factor of the number 600851475143 ?

Although my solution works, I'd like to know how I can improve.

primes = [2]
factors = []

def isPrime(x):
    a = 1
    if x == 1:
        return False
    while a < x:
        a += 1
        if x % a == 0 and a != x and a != 1:
            return False
            break
    return True

def generatePrime():
    a = primes[-1]+1
    while isPrime(a) == False:
        a += 1
    primes.append(a)

def primeFactor(x):
    a = primes[-1]
    while a <= x:
        if x % a == 0:
            factors.append(a)
            x /= a
        generatePrime()
        a = primes[-1]

primeFactor(input("Enter the number: "))
print("The prime factors are: " + str(factors) + "\nThe largest prime factor is: " + str(sorted(factors)[-1]))


texts: Moving all .xlsx files from the last five days (but not today)

texts:
My code works, but it looks very bad.

I need to move .xlsx files from the previous days from one folder to another, but I should'nt move the files with today's date, just the files from previous days.

In my current code, I am moving the files by specifying each one of them with a Minus X days, but I think the code is not in the best 'shape' nor the best performance/quality.

Any one can help me improve it?

import datetime,os, glob, shutil
from pathlib import Path

dir_carteiras = r"C:\Users\GuilhermeMachado\Documents\Carteiras"
test = os.listdir(dir_carteiras)

for item in test:
    if item.endswith(".jpg"):
        os.remove( os.path.join(dir_carteiras, item))

#get todays  date and a calculation for today -1 day
today=datetime.date.today()
minus_one_day=datetime.timedelta(days=-1)

#use the calculation to get previous 5 days strings
d_N1=today+minus_one_day
d_N1_ = d_N1.strftime('%Y.%m.%d')
d_N2=d_N1+minus_one_day
d_N3=d_N2+minus_one_day
d_N4=d_N3+minus_one_day
d_N5=d_N4+minus_one_day

#format dates for the files formats
Date_Carteira_N1 = d_N1.strftime('%d_%m_%Y')
Date_Carteira__0 = today.strftime('%d_%m_%Y')
Date_Carteira_N2 =d_N2.strftime('%d_%m_%Y')
Date_Carteira_N3 =d_N3.strftime('%d_%m_%Y')
Date_Carteira_N4 =d_N4.strftime('%d_%m_%Y')
Date_Carteira_N5 =d_N5.strftime('%d_%m_%Y')
Alocacao_0 = today.strftime('%Y%m%d')
Alocacao_N1 = d_N1.strftime('%Y%m%d')
Alocacao_N2 = d_N2.strftime('%Y%m%d')
Alocacao_N3 = d_N3.strftime('%Y%m%d')
Alocacao_N4 = d_N4.strftime('%Y%m%d')
Alocacao_N5 = d_N5.strftime('%Y%m%d')

#folder destination
NewFolderPath = dir_carteiras+"\Historico"
Path(NewFolderPath).mkdir(parents=True, exist_ok=True)

#Move the "Carteira" files from previous 5 days
Carteiras_move_N1 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N1+'.xlsx', recursive=True)
for f in Carteiras_move_N1:
        shutil.move(f,NewFolderPath)
Carteiras_move_N2 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N2+'.xlsx', recursive=True)
for f in Carteiras_move_N2:
        shutil.move(f,NewFolderPath)
Carteiras_move_N3 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N3+'.xlsx', recursive=True)
for f in Carteiras_move_N3:
        shutil.move(f,NewFolderPath)
Carteiras_move_N4 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N4+'.xlsx', recursive=True)
for f in Carteiras_move_N4:
        shutil.move(f,NewFolderPath)
Carteiras_move_N5 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Date_Carteira_N5+'.xlsx', recursive=True)
for f in Carteiras_move_N5:
        shutil.move(f,NewFolderPath)

#Move the "Alocacao" files from the previous 5 days
Alocacao_move_N1 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N1+'.xlsx', recursive=True)
for f in Alocacao_move_N1:
        shutil.move(f,NewFolderPath)
Alocacao_move_N2 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N2+'.xlsx', recursive=True)
for f in Alocacao_move_N2:
        shutil.move(f,NewFolderPath)
Alocacao_move_N3 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N3+'.xlsx', recursive=True)
for f in Alocacao_move_N3:
        shutil.move(f,NewFolderPath)
Alocacao_move_N4 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N4+'.xlsx', recursive=True)
for f in Alocacao_move_N4:
        shutil.move(f,NewFolderPath)
Alocacao_move_N5 = glob.glob(r'C:\Users\GuilhermeMachado\Documents\Carteiras\*'+Alocacao_N5+'.xlsx', recursive=True)
for f in Alocacao_move_N5:
        shutil.move(f,NewFolderPath)


texts:
As a first step in learning Haskell I am solving this problem, which involves finding the Rith-ranked numbers, given some input list and many Ri. In an imperative language I would make a zeroed array c of length 200, increment c[h] for each height h, compute cumulative sums of c and then binary search c to determine the height corresponding to each given index. Because max_height is fixed, this has runtime linear in the size of input and bounded memory(*) excluding the input.
Here's my Haskell code:
max_height = 200
count_eq e = foldl (\c f -> if e == f then c + 1 else c) 0
counts heights = map (flip count_eq heights) [0..max_height]
first_gt e l = f l 0 where f (x:xs) i = if x > e then i else f xs (i+1)
solve heights indices = let accum = scanl1 (+) (counts heights) in
  map (flip first_gt accum) (map (subtract 1) indices)

It is correct but slow. I would like to know how to (A) reason about and (B) improve the performance. Also (C) can I achieve the same asymptotic performance as the imperative code?
(*) assuming each c[i] fits in a machine int. I believe the runtime statement holds regardless.


texts: I want reduce the time complexity for this ladder problem to find the minimum ladders required

texts:
I was trying to attempt below given challenge. I tried multiple ways to solve the problem but none of them were good enough to pass the time limit. Please advise if you have any idea to improve on this.
Problem:
You are visiting a building of N floors. On every floor, only one ladder of specified length is present. If the length of the ladder is x units, you can reach y floors above from the current one.
You can leave the ladder in between in order to change the ladder, but you can only start from the starting floor of the ladder.
You are given Q questions. In each question, you will be given a floor number. For each question, you have to tell the least number of ladders required to reach given floor.
Initially, you are on the ground floor.
Input Format:
The first line contains an integer T, indicating the number of test cases.
For each test case:
The first line contains an integer N, indicating number of floors in the building.
Next line contains N space separated positive integers which denote the length of ladder at each floor (First integer corresponds to ladder length on ground floor, second integer corresponds to ladder length on first floor and so on) .
Next line contains an integer Q, indicating number of questions.
Following Q lines contain an integer each, denoting the floor number for which answer is to be computed.
Output Format:
For each question, print the least number of ladders required required to reach given floor.
Answer for each question should come in a new line.
Sample Input:
1
10
2 2 1 1 2 2 3 1 1 1
10
5
4
3
2
1
10
9
8
7
6

Sample Output:
4
3
2
1
1
6
5
5
5
4

Problem Reference
Solution:
class Program
{
    static void Main(string[] args)
    {
        int T = Convert.ToInt32(Console.ReadLine());
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < T; i++)
        {
            int N = Convert.ToInt32(Console.ReadLine());
            sb.EnsureCapacity(sb.Length + (5 * N));
            int[] numOfStairs = new int[N + 1];
            numOfStairs[0] = 0;
            string[] stairs = Console.ReadLine().Split();
            int[] reaches = new int[N];
            for (int j = 0; j < stairs.Length; j++)
            {
                int length = Convert.ToInt32(stairs[j]);
                reaches[j] = j + length;
            }
            int Q = Convert.ToInt32(Console.ReadLine());

            for (int j = 0; j < Q; j++)
            {
                int target = Convert.ToInt32(Console.ReadLine());
                sb.AppendLine(GetShortestPath(target, reaches.Take(target).ToArray(), numOfStairs).ToString());
            }
        }
        Console.WriteLine(sb.ToString());
    }
    static int GetShortestPath(int target, int[] reaches, int[] numOfStairs)
    {
        if (numOfStairs[target] == 0 && target != 0)
        {
            List<int> connectedFloors = GetPreviousFloorList(target, reaches);
            int[] shortestPaths = new int[connectedFloors.Count];
            for (int i = 0; i < connectedFloors.Count; i++)
            {
                int shortestPath = GetShortestPath(connectedFloors[i], reaches.Take(connectedFloors[i]).ToArray(), numOfStairs);
                shortestPaths[i] = shortestPath;
            }
            int result = shortestPaths.Min() + 1;
            numOfStairs[target] = result;
            return result;
        }
        else
        {
            return numOfStairs[target];
        }
    }
    static List<int> GetPreviousFloorList(int target, int[] reaches)
    {
        List<int> floors = new List<int>(target / 2);
        for (int i = 0; i < target; i++)
        {
            if (reaches[i] >= target)
                floors.Add(i);
        }
        return floors;
    }
}


texts: Create an array of objects from array of arrays

texts:
I have the following function that creates an array of JSON objects with properties from an array of arrays, where the first 'row' in the array contains the keys.

It works, but could it be improved?

var myArray = [
    ["a","b","c","d"], // will become keys
    [1,2,3,4],
    ["foo","bar","baz","bob"]
];

function makeObjProp(arr) {

    var keys = arr[0];
    var numRows = arr.length;
    var numCols = keys.length;

    var result = [];

    // starts i = 1 to avoid adding an object of 'keys':'keys'
    for (var i = 1; i < numRows; i++) {
        var obj = {};

        for (var j = 0; j < numCols; j++) {
            obj[ keys[j] ] = arr[i][j];
        };
        result.push(obj);
    };
    console.log(result);
}

makeObjProp(myArray);

fiddle


texts: Bad performance of the unsorted list (nearly quadratic time)

texts:
I've already made an implementation of unsorted List but I'm not happy with results it gives. It looks like Big-O is nearly \$N^2\$ which is, I suppose, not correct for my list.

Here's the graph that shows the problem:

The X axis represents number of total operations: adding new elements and same number of deleting max element, Y axis represents time in milliseconds.

If you could show me some lines that could be made better, that would be great. Unfortunately, implementation must contain array types instead of easier and faster List types.

TList.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace list
{
    class TList
    {
        // elements of list
        int[] elements;
        int size;
        public TList()
        {
            size = 1;
            elements = new int[size];
        }
        public void Push(int data)
        {
            size++;
            if(size > elements.Length)
            {
                int[] new_elements = new int[elements.Length * 2];
                elements.CopyTo(new_elements, 0);
                elements = new_elements;
            }
            elements[size - 1] = data;
        }
        public int MaxIndex()
        {
            var index = 0;
            var max = elements[0];
            for(var i=1;i< size;i++)
            {
                if(elements[i]>max)
                {
                    max = elements[i];
                    index = i;
                }
            }
            return index;
        }
        public int[] DeleteAt(int indexToRemove)
        {
            return elements = elements.Where((source, indexOfElements) => indexOfElements != indexToRemove).ToArray();
        }

    }
}

Another (better?) way to delete:

public void DeleteAt(int indexToRemove)
{
    int[] new_elements = new int[elements.Length - 1];
    for (int i = 0, j = 0; i < size - 1; i++, j++)
    {
        if (i == indexToRemove)
            j++;
        new_elements[i] = elements[j];
    }
    elements = new_elements;
    size--;
}


texts:
So, I made a tiny (~2 KB, <100 lines) library for simple flat-file data storage.

How it works is, you define a file to be used, and then you can add/read/modify/delete objects as "keys" to/from the file.

All the code is on github, but I'll put it here too:

varDx.php:

<?php
namespace varDX;

class cDX {
    private $dataFile;

    public function def($filename){
        $this->dataFile = $filename;
    }

    public function write($varName, $varVal){
        if(file_exists($this->dataFile)){
            $foundLine = $this->check($varName);
        } else {
            $foundLine = false;
        }

        if(!$foundLine){
            $writeData = $varName.'__=__'.urlencode(serialize($varVal)).PHP_EOL;
            file_put_contents($this->dataFile, $writeData, FILE_APPEND);
        } else {
            return "ERR_DX_KEY_ALREADY_EXISTS";
        }
    }

    public function read($varName){
        if(file_exists($this->dataFile)){
            foreach(file($this->dataFile) as $line) {
                if(strpos($line, $varName) !== false) {
                    list(, $new_str) = explode("__=__", $line);
                    $foundLine = true;
                }
            }
            if($foundLine){
                $val = rtrim($new_str);
                return unserialize(urldecode($val));
            } else {
                return "ERR_DX_KEY_NOT_FOUND";
            }
        } else {
            return "ERR_DX_FILE_DOES_NOT_EXIST";
        }
    }

    public function del($varName){
        if(file_exists($this->dataFile)){
            $f = $this->dataFile;
            $term = $varName.'__=__';
            $arr = file($f);
            foreach ($arr as $key=> $line) {
                if(stristr($line,$term)!== false){unset($arr[$key]);break;}
            }
            //reindexing array
            $arr = array_values($arr);
            //writing to file
            file_put_contents($f, implode($arr));
        } else {
            return "ERR_DX_FILE_DOES_NOT_EXIST";
        }
    }

    public function modify($varName, $varVal){
        if(file_exists($this->dataFile)){
            if($this->check($varName)){
                $this->del($varName);
            }
        }
        $writeData = $varName.'__=__'.urlencode(serialize($varVal)).PHP_EOL;
        file_put_contents($this->dataFile, $writeData, FILE_APPEND);

    }

    public function check($varName){
        if(file_exists($this->dataFile)){
            foreach(file($this->dataFile) as $line) {
                if(stripos($line, $varName.'__=__') === 0){
                    return true;
                }
            }
            return false;
        } else {
            return "ERR_DX_FILE_DOES_NOT_EXIST";
        }
    }
}

Usage:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create object
$dx->def('file1.txt'); //define data file

$a = "this is a string";
$dx->write('val1', $a); //write key to file

$dx->modify('val1', "this is another string"); //modify value of key
echo $dx->read('val1'); //read value of key

if($dx->check('val1')){ //check if key exists
    del('val1'); //delete key
}

File storage:

All keys are stored in this format:

keyname__=__urlencode(serialize(value_of_key))

There's more info on the functions in the README on the github page. I'm wondering if I can make this more efficient when dealing with files, and if there's anything else that I'm doing wrong?


texts:
Problem 1:

  Sum the even numbers for the first n fibonacci numbers

Solution:

def fib(k):
    """Compute kth fibonacci number.

    >>> fib(1)
    0
    >>> fib(2)
    1
    >>> fib(11)
    55
    """
    def recursive_fib(prev, curr, k):
        if k - 1 == 0:
             return curr
        else:
             return recursive_fib(curr, prev + curr, k - 1)
    return recursive_fib(1, 0, k)

def iseven(n):
    if n % 2 == 0:
       return True

def sum_even_fibs(n):
    """Sum the first even fibonacci numbers

    >>> sum_even_fibs(11)
    44
    """
    return  sum(filter(iseven, map(fib, range(1, n + 1))))

def sum_even_fibs_gen(n):
    """Sum the first even fibonacci numbers

    >>> sum_even_fibs_gen(11)
    44
    """
    return sum(fib(k) for k in range(1, n+1) if fib(k) % 2 == 0)

Problem 2:

  List the letters in the acronym for a name, which includes the first letter of each capitalized word.

Solution:

def first(s):
    return s[0]

def iscap(s):
    return len(s) > 0 and s[0].isupper()

def acronym(name):
    """Return a tuple of the letters that form the acronym for name.

    >>> acronym('University of California Berkeley')
    ('U', 'C', 'B')
    """
    return tuple(map(first, filter(iscap,name.split())))

def acronym_gen(name):
    """Return a tuple of the letters that form the acronym for name.

    >>> acronym_gen('University of California Berkeley')
    ('U', 'C', 'B')
    """
    return tuple(w[0] for w in name.split() if iscap(w))

Functions fib, acronym and sum_even_fibs are written in functional paradigm and tested.

Functions acronym_gen and sum_even_fibs_gen are written in imperative paradigm and tested.

My question:

After using predefined functions split filter map in above 5 user defined functions, are the aforementioned paradigms being implemented correctly? If no, please let me know of the improvements.


texts:
The following is a small part of some code I am working on
Which is better/faster/nicer?

1.

for (Future<Subscription> future : futures) {
      try {
        executorService.submit(new Updater(future.get()));
      } catch (ExecutionException e) {
        logger.error(e, e);
      }
    }

2.

  for (Future<Subscription> future : futures) {
          try {
            executorService.submit(new Updater(future));
          //here future.get() will be called in the Updater constructor in its own thread
          } catch (ExecutionException e) {
            logger.error(e, e);
          }
        }

I am tempted to go with the second way as future.get() is called in its own thread and not in the main thread.


texts:
Can please someone review and give me suggestions for improving this code?  I am very new to JavaScript.

I need to create a method in JavaScript which will take parameters as

DateRange (possible values as Today/This Week/This Month
BooleanFullDate (possible values as true/false)

Now, when the parameter value is Today, it should return

10/23/2013
10/23/2013

When This Week and BooleanFullDate are true, it should return

10/20/2013
10/26/2013

When This Week and BooleanFullDate are false, it should return

10/20/2013
10/23/2013

When This Month and BooleanFullDate are true, it should return

10/01/2013
10/31/2013

When This Month and BooleanFullDate are false, it should return

10/01/2013
10/23/2013

For which I have written my code here.

Lastly, can someone please suggest improvements for the code?

original question posted

EDIT:- Source code

function GetStartAndEnd(dateRange, bGetFullRange) {
    var dateObject = new Date();

    var dateobj = new Date()
    var month = dateobj.getMonth()+1
    var day = dateobj.getDate()
    var year = dateobj.getFullYear()

    var start = undefined;
    var end = undefined;
    if (dateRange.toLowerCase() == "today") {
        start = month + "/" + day + "/" + year;
        end = month + "/" + day + "/" + year;
    } else if (dateRange.toLowerCase() == "this week") {
        var curr = new Date;
        var firstDay = new Date(curr.setDate(curr.getDate() - curr.getDay()));
        var lastDay = new Date(curr.setDate(curr.getDate() - curr.getDay() + 6));

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        var lmonth = lastDay.getMonth()+1;
        var lday = lastDay.getDate();
        var lyear = lastDay.getFullYear();
        end = lmonth + "/" + lday + "/" + lyear;

    } else if (dateRange.toLowerCase() == "this month" && bGetFullRange) {
        var date = new Date(),
            y = date.getFullYear(),
            m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        var lmonth = lastDay.getMonth()+1;
        var lday = lastDay.getDate();
        var lyear = lastDay.getFullYear();
        end = lmonth + "/" + lday + "/" + lyear;

    } else if (dateRange.toLowerCase() == "this month" && !bGetFullRange) {
        var date = new Date(),
            day = date.getDate(),
            y = date.getFullYear(),
            m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        end = m+1 + "/" + day + "/" + y;

    }
    console.log({
        "start": start,
            "end": end
    });

    return {
        "start": start,
            "end": end
    }
}
GetStartAndEnd("Today");
GetStartAndEnd("this week");
GetStartAndEnd("this month", true);
GetStartAndEnd("this month", false);


texts: Generic wrapper for System.Runtime.Caching.MemoryCache

texts:
I have implemented a simple generic wrapper for MemoryCache class. Its interface looks like ConcurrentDictionary class but I tried to keep it simple. I tried to keep operations atomic, hoping not to break the thread-safety. Is there a mistake about thread-safety? I also want to know if I there are some boxing-unboxing issues I have to think about. Any suggestions about API or some other thing  is appreciated.

public interface IMemoryCacheWrapper<T>
{
    string Name { get; }
    long CacheMemoryLimitInBytes { get; }
    long PhysicalMemoryLimit { get; }
    TimeSpan PollingInterval { get; }
    CacheItemPolicy CacheItemPolicy { get; set; }
    void AddOrUpdate(string key, T value);
    bool TryGetValue(string key, out T value);
    bool TryRemove(string key, out T value);
    void Remove(string key);
    bool ContainsKey(string key);
    long Count { get; }
    void Dispose();
    bool IsDisposed { get; }
}

public class MemoryCacheWrapper<T> : IMemoryCacheWrapper<T>
{
    private readonly MemoryCache _memoryCache;
    private CacheItemPolicy _cacheItemPolicy;
    private bool _isDisposed;

    public MemoryCacheWrapper(string name, NameValueCollection config = null)
    {
        _memoryCache = config != null ? new MemoryCache(name, config) : new MemoryCache(name);
        _isDisposed = false;
        CacheItemPolicy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(1, 0, 0) };
    }

    public string Name
    {
        get { return _memoryCache.Name; }
    }

    public long CacheMemoryLimitInBytes
    {
        get { return _memoryCache.CacheMemoryLimit; }
    }

    public long PhysicalMemoryLimit
    {
        get { return _memoryCache.PhysicalMemoryLimit; }
    }

    public TimeSpan PollingInterval
    {
        get { return _memoryCache.PollingInterval; }
    }

    public CacheItemPolicy CacheItemPolicy
    {
        get
        {
            return _cacheItemPolicy;
        }
        set
        {
            if (value != null)
            {
                _cacheItemPolicy = value;
            }
        }
    }

    public void AddOrUpdate(string key, T value)
    {
        _memoryCache.Set(key, value, CacheItemPolicy);
    }

    public bool TryGetValue(string key, out T value)
    {
        bool result = false;
        value = default(T);

        object item = _memoryCache.Get(key);
        if (item != null)
        {
            value = (T)item;
            result = true;
        }

        return result;
    }

    public bool TryRemove(string key, out T value)
    {
        bool result = false;
        value = default(T);

        object item = _memoryCache.Remove(key);
        if (item != null)
        {
            result = true;
            value = (T)item;
        }

        return result;
    }

    public void Remove(string key)
    {
        _memoryCache.Remove(key);
    }

    public bool ContainsKey(string key)
    {
        return _memoryCache.Contains(key);
    }

    public long Count
    {
        get { return _memoryCache.GetCount(); }
    }

    public void Dispose()
    {
        _memoryCache.Dispose();
        _isDisposed = true;
    }

    public bool IsDisposed
    {
        get { return _isDisposed; }
    }
}


texts: Bash script to rename subfolder to include name of parent folder

texts:
Here's the current structure of my directory.

.
├── Show 1
│   ├── Season 1
│   └── Season 2
├── Show 2
    ├── Season 1
    └── Season 2

I want to rename the Season folders to include the name of the Show. The desired structure looks like this :

.
├── Show 1
│   ├── Show 1 - Season 1
│   └── Show 1 - Season 2
├── Show 2
    ├── Show 2 - Season 1
    └── Show 2 - Season 2

Here's the script I wrote :

# Parse through all show folders.
for show in /Users/sanjeetsuhag/Desktop/* ; do
    # Check if it is a folder.
    if [ -d "$show" ]; then
        # Parse through all season folders.
        for season in $show/* ; do
            # Check if it is a folder.
            if [ -d "$season" ]; then
                mv $season "$show/$(basename "$show") - $(basename "$season")"
            fi
        done
    fi
done

This is my first time scripting in Bash. Is there any thing I could improve ?