texts: Functional approach to splitting list into sub lists

texts:
Here is my functional approach to split a list into sub lists, each having non-decreasing  numbers, so the input

\$[1; 2; 3; 2; 4; 1; 5;]\$

computes to

\$[[1; 2; 3]; [2; 4]; [1; 5]]\$

The code works, but I need a while to understand it.  I would prefer a solution that is more clear. Is there a way to make this more elegant or readable?  Everything is allowed, F# mutables as well. Or do I just get used more to functional code reading?

The subsets are called "run"s in the code below.

// returns a single run and the remainder of the input
let rec takerun input =
    match input with
    | [] -> [], []
    | [x] -> [x], []
    | x :: xr -> if x < xr.Head then
                     let run, remainder = takerun xr
                     x :: run, remainder
                 else [x], xr

// returns the list of all runs
let rec takeruns input =
    match takerun input with
    | run, []  -> [run]
    | run, rem -> run :: takeruns rem

let runs = takeruns [1; 2; 3; 2; 4; 1; 5;]
> val runs : int list list = [[1; 2; 3]; [2; 4]; [1; 5]]

Edit:

Considering the helpful feedback I ended up with this reusable code. And got more used to functional programming, comparing imperative alternatives I meanwhile find the pure functional approach more readable. This version is good readable, although not tail recursive. For the small lists I had to deal with, readability was preferred.

// enhance List module
module List =

    // splits list xs into 2 lists, based on f(xn, xn+1)
    let rec Split f xs =
        match xs with
        | []  -> [],  []
        | [x] -> [x], []
        | x1 :: x2 :: xr when f x1 x2 -> [x1], x2 :: xr // split on first f(xn, xn+1)
        | x :: xr -> let xs1, xs2 = Split f xr
                     x :: xs1, xs2

// Now takruns becomes quite simple
let rec takeruns input =
    match List.Split (>) input with
    | run, []  -> [run]
    | run, rem -> run :: takeruns rem

let runs = takeruns [1; 2; 3; 2; 4; 1; 5;]


texts: A small "TODO" app built using a modular pattern

texts:
I am just beginning to learn JavaScript and although I feel I am starting to grasp the language, I don't feel I know how to structure an app properly. I decided to start small and build a "TODO"-app using a modular pattern.

I am aware that I should use more validations, there are unused functions, and there may be a missing semicolon here and there. My main focus on this thing was to see if I could structure an app in a good way.

I would love some feedback on my setup. Is this a proper way to set up such a small application? Am I missing something completely? Am I using the modular pattern correctly?

Generally, have I gotten the gist of it?

(function todoApp() {

var storage = (function () {
    var _db,
        todos,
        addTodo,
        removeTodo,
        updateTodo,
        getAllTodos,
        save;

    if (!window.localStorage.todoApp) {
      window.localStorage.todoApp = JSON.stringify({todos: []});
    }

    _db = JSON.parse(window.localStorage.todoApp);

    addTodo = function addTodo(todo) {
      var id = Date.now().toString();
      _db.todos.push({id: id, todo: todo});
      save();
    };

    removeTodo = function removeTodo(id) {
      _db.todos.every(function (c, i) {
        if (c.hasOwnProperty("id") && c.id == id) {
          _db.todos.splice(i, 1);
          save();
          return false;
        }
      });
    };

    updateTodo = function updateTodo(id, todo) {
      _db.todos.every(function (c, i) {
        if (c.hasOwnProperty("id") && c.id == id) {
          _db.todos[i].todo = todo;
          save();
          return false;
        }
      });
    };

    getAllTodos = function getAllTodos() {
      return _db.todos;
    };

    save = function save() {
      window.localStorage.todoApp = JSON.stringify(_db);
    };

    return {
      addTodo: addTodo,
      removeTodo: removeTodo,
      updateTodo: updateTodo,
      getAllTodos: getAllTodos
    };

  })();

  var view = (function (storage) {
    var $todos = $("[rel='jstodo-container'] > [rel='jstodo-todos']"),
        todos = storage.getAllTodos(),
        render;

    render = function render() {
        $todos.html("");
        todos.forEach(function (c) {
          $todos.append("
" + c.todo + "
");
        });
    };

    return {
      render: render
    };
  })(storage);

  view.render();

  $("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    view.render();
  });
})();
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

  <title>JS Bin</title>

Todos:

    <input type="text" rel="jstodo-input"/>
    <button rel="jstodo-submit">Legg til!</button>

Here is a jsbin of the project (in case the Stack Snippet has permission issues).


texts: Exposing a web API wrapper library to consumers

texts:
I'm writing a C# library that's a wrapper around the Yahoo Finance YQL API. I'm stuck on how I want to expose my API to consumers. My design thus far consists of separate interfaces for the different parts of the Yahoo Finance API:

public interface IYahooFinanceCharts {
    Task<Image> GetChartAsync(string tickerSymbol, ChartSize size, ChartTimeSpan timeSpan);
}

public interface IYahooFinanceQuotes {
    Task<IEnumerable<Quote>> GetQuotesAsync(params string[] tickerSymbols);
}

public interface IYahooFinanceStocks {
    Task<IEnumerable<Stock>> GetStocksAsync(params string[] tickerSymbols);
}

public interface IYahooFinanceTickerSymbols {
    Task<IEnumerable<TickerSymbol>> SearchAsync(string symbolOrKeyword);
}

I have internal classes that implement these interfaces to handle the details of building a request for the YQL API and parsing the result of the response. I don't want to expose these classes to consumers.

I was thinking of using a facade to reduce the main entry point into my API to one class. Consumers could cast, instantiate, or register (DI container) the facade using the various interfaces to zero-in on the parts they're interested in.

public class YahooFinance : IYahooFinanceCharts, IYahooFinanceQuotes, IYahooFinanceStocks, IYahooFinanceTickerSymbols
{
    // Delegating calls to the internal classes that implement these interfaces...
}

...

IYahooFinanceStocks stocks = new YahooFinance();
var results = await stocks.GetStocksAsync("MSFT", "GOOG");

I'm not sure if I like this because if consumers simply use

var yahooFinance = new YahooFinance();

the entire API is exposed to them, defeating the purpose of the separate interfaces. On the other hand, not using a facade and forcing consumers to instantiate the concrete class for each interface is clumsy, increases the surface area of the API, and I'd have to expose the concrete types...


texts:
I have been struggling with understanding Model, View, Service, Controller architecture and wrote some code.

Is my Model class the Model part of MVC (did I define it properly)?
Is my Service class a Service Layer (did I define the layer properly)?
Did I connect my layers properly (is the 'wiring' set up correctly)?

 /*
 * Application Idea:  Assume UI has two input boxes and a button and an output box
 * box A is for a number
 * box B is for a number
 *
 * event of a button click sends responce of (A+B) into the output button
 * Implement Controller, Service, Model, View layers
 */
class Controller
{

    /**
     *
     * @var Service
     */
    private $service;

    /**
     *
     * @var Model
     */
    private $model;

    // add A B update C for all
    function addAB()
    {
        $a = $this->model->getA();
        $b = $this->model->getB();

        $c = $this->service->computeSum($a, $b);
        $this->model->setC($c);

        $view = new View();
        return $view->render($a, $b, $c);
    }

    public function getService()
    {
        return $this->service;
    }

    public function setService($service)
    {
        $this->service = $service;
    }

    public function getModel()
    {
        return $this->model;
    }

    public function setModel($model)
    {
        $this->model = $model;
    }
}

class ControllerFactory
{

    function getController(array $request)
    {
        $model = new Model();
        $model->setA($request['a']);
        $model->setB($request['b']);

        $service = new Service();

        $controller = new Controller();
        $controller->setService($service);
        $controller->setModel($model);

        return $controller;
    }
}

class Model
{

    private $a;

    private $b;

    private $c;

    public function getA()
    {
        return $this->a;
    }

    public function getB()
    {
        return $this->b;
    }

    public function getC()
    {
        return $this->c;
    }

    public function setA($a)
    {
        $this->a = $a;
    }

    public function setB($b)
    {
        $this->b = $b;
    }

    public function setC($c)
    {
        $this->c = $c;
    }
}

class Service
{

    function computeSum($a, $b)
    {
        return $a + $b;
    }
}

class View
{

    function render($a, $b, $c)
    {
        print "$a + $b = $c";
    }
}

class Router
{

    function routeRequest($request)
    {
        $controller = (new ControllerFactory())->getController($request);
        switch ($request['event'])
        {
            case 'add_event':
                $controller->addAB();
                break;
        }
    }
}

/*
 * request can come from Web Browser
 */
$request = array();
$request['event'] = "add_event";
$request['a'] = 2;
$request['b'] = 3;

$router = new Router();
$router->routeRequest($request);


texts: Putting all desktop items into a new folder

texts:
I'm quite a newbie with Python, but I wanted to try my own little project, so I made a small script that puts all the desktop icons/folders into a newly created folder (called "Desktop1") if there are more than 25 items on the desktop.

import os
import shutil

#My user on windows is Shadow so you're not like 'huh??'

os.chdir("C:\Users\Shadow\Desktop")
desktop = os.listdir("C:\Users\Shadow\Desktop")
desktopFiles = []

#Folder that the desktop files/icons will move to once created
newFolder = "C:\Users\Shadow\Desktop\Desktop1"

#Function that does the moving
def moveFilesToFolder(files, directory, folder):
    for files in directory:
        shutil.move(files, folder)

#Place the files into a list so I can determine how many there are
for x in desktop:
    desktopFiles.append(x)

if len(desktopFiles) > 25:    #If there's more than 25 files/icons on the desktop

   #If you already have an EMPTY folder named Desktop1 on your Desktop
    if os.path.exists(newFolder) and os.listdir(newFolder) == []:
        moveFilesToFolder(file, desktop, newFolder)
        print "Desktop1 already exists and is empty, so the files have been placed there"

    else:                 #Otherwise, make Desktop1 and move the icons/files into it
        os.mkdir(newFolder)
        moveFilesToFolder(file, desktop, newFolder)

What can I do to make it better? It works well and gets the job done, but is there any improvement I can make to it now (performance, syntax, etc.) that I can use for any later programs I may want to create? I feel like I'm not using object oriented programming at all.


texts:
I implemented K-Nearest Neighbours algorithm, but my experience using MATLAB is lacking. I need you to check the small portion of code and tell me what can be improved or modified.  I hope it is a correct implementation of the algorithm.

function test_data = knn(test_data, tr_data,k)

numoftestdata = size(test_data,1);
numoftrainingdata = size(tr_data,1);

for sample=1:numoftestdata

   %Step 1: Computing euclidean distance for each testdata
   R = repmat(test_data(sample,:),numoftrainingdata,1) ;
   euclideandistance  = (R(:,1) - tr_data(:,1)).^2;

   %Step 2: compute k nearest neighbors and store them in an array
    [dist position] = sort(euclideandistance,'ascend');
    knearestneighbors=position(1:k);
    knearestdistances=dist(1:k);

    % Step 3 : Voting
    for i=1:k
        A(i) = tr_data(knearestneighbors(i),2);
    end

    M = mode(A);

    if (M~=1)
        test_data(sample,2) = mode(A);
    else
        test_data(sample,2) = tr_data(knearestneighbors(1),2);
    end
end

To test it you can use :

test_data = [6,0; 2,0; 5,0]
tr_data = [1,1;0,2;3,2; 4,4; 5,3]


texts:
Here is my new working code. Man, working with strings in C is tedious  and annoying. I had built the algorithm in short time, took hours figuring how to implement it properly in C. Tell me if there are more bugs or if some improvement is possible.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
  char data[100];
  struct node *next;
}SNode;

typedef struct{
 int count;
 SNode *top;
}stack;

int isEmpty(stack *s){
  return (s->count==0);
 }

void push(stack *s,char x[]){
  SNode *temp = (SNode *)malloc(sizeof(SNode));
  strcpy(temp->data,x);
  temp->next = s->top;
  s->top=temp;
  s->count++;
  }

char * pop(stack *s){
     if(isEmpty(s)){
      return "-1";

     }
    SNode *temp = s->top;
    s->top = temp->next;
    static char a[10];
    strcpy(a,temp->data);
    free(temp);
    s->count--;
    return a;
  }

 int main(){
    stack *s = (stack *)malloc(sizeof(stack));
    s->count = 0;
    char a[100];
    printf("Enter prefix expression: ");
    gets(a);
    int i;
    for(i=strlen(a)-1;i>=0;i--){
    if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'){
       char s1[10], s2[10];
       strcpy(s1,pop(s));
       strcpy(s2, pop(s));
       char b1[10] ="(",b2[10]=")";
       strcat(b1,s1);
       char t[2]="\0";
       t[0]=a[i];
       strcat(b1,t);
       strcat(b1,s2);
       strcat(b1,b2);
       push(s,b1);
      }
     else if(isalpha(a[i])){
         char t[2] = "\0";
          t[0] = a[i];
          push(s,t);
     }
    }
    char *infix = pop(s);
    printf("Infix expression: %s",infix);
    return 0;
     }


texts: Sorting and searching problem related to a group of people standing in a rectangle

texts:
Please be brutal, and let me know how I've done on this problem, provided I coded it at an interview for a top tech firm.

Time it took me: 44 minutes

Worst case time complexity: O(n2)?  Am I right?

Space Complexity: O(n)?

Problem:

  A group of people stand before you arranged in rows and columns.
  Looking from above, they form an R by C rectangle of people. You will
  be given a String[] people containing the height of each person.
  Elements of people correspond to rows in the rectangle. Each element
  contains a space-delimited list of integers representing the heights
  of the people in that row.

  Your job is to return 2 specific heights in
  a int[]. The first is computed by finding the shortest person in each
  row, and then finding the tallest person among them (the
  "tallest-of-the-shortest"). The second is computed by finding the
  tallest person in each column, and then finding the shortest person
  among them (the "shortest-of-the-tallest").

Definition:

  Class: TallPeople

  Method: getPeople

  Parameters: String[]

  Returns: int[]

  Method signature: int[] getPeople(String[] people) (be sure your method is public)

  Constraints:

  people will contain between 2 and 50 elements inclusive.
  Each element of people will contain between 3 and 50 characters inclusive.
  Each element of people will be a single space-delimited list of positive integers such that:

  Each positive integer is between 1 and 1000 inclusive with no extra
  leading zeros.
  Each element contains the same number of integers.
  Each element contains at least 2 positive integers.
  Each element does not contain leading or trailing whitespace.

Examples:

{"9 2 3",
 "4 8 7"}

  Returns: { 4,  7 }

  The heights 2 and 4 are the shortest from the rows,
  so 4 is the taller of the two. The heights 9, 8, and 7 are the tallest
  from the columns, so 7 is the shortest of the 3. 1)

{"1 2",
 "4 5",
 "3 6"}

  Returns: { 4,  4 }

{"1 1",
 "1 1"}

  Returns: { 1,  1 }

Answer:

public static int[] getPeople(String[] people){
    int maxOfMinHeight = Integer.MIN_VALUE;
    int minOfMaxHeight = Integer.MAX_VALUE;
    int count=0;

    String[][]findMaxOfMin = new String[people.length][people[0].split(" ").length];
    int[][] findMinOfMax = new int[people[0].split(" ").length][people.length];

    for(String s : people){
        String[] sort  = s.split(" ");
        Arrays.sort(sort);
        findMaxOfMin[count++]=sort;
    }
    for(int i=0; i<findMaxOfMin.length; i++){
        maxOfMinHeight = Math.max(maxOfMinHeight, Integer.valueOf(findMaxOfMin[i][0]));
    }
    count=0;
    int cols = people[0].split(" ").length;
    for(int i=0; i<cols; i++){
        int[] temp = new int[people.length];
        for(int j=0; j<people.length; j++){
            temp[j] = Integer.valueOf( ((String[])people[j].split(" "))[i]);
        }
        Arrays.sort(temp);
        findMinOfMax[count++]=temp;
    }
    for(int i=0; i<findMinOfMax.length; i++){
        minOfMaxHeight = Math.min(minOfMaxHeight, findMinOfMax[i][people.length-1]);
    }
    return new int[] {minOfMaxHeight, maxOfMinHeight};
}


texts:
I am trying to create a two player Chess game. To do this I want to generate a list of legal moves. I am having trouble with the brevity of the code to generate the moves for the rooks and bishops.

The code I have pasted below works (i.e. shows legal bishop moves) but there is a lot of repetition, which is not ideal. To make this work for both black and white bishops I would need to add even more repetitive lines.

Is there a better way to do this? I do not want to use any 'chess modules' as this is a learning exercise for me; as you can tell, I am a beginner.

import numpy as np

# chess board is a numpy array
# white pieces are capitalised, black pieces are not
board = np.zeros((8,8),dtype=str)

# example piece positions
white_bishop = (4,5)
white_pawn = (6,7)
black_knight = (0,1)
board[white_bishop] = 'B'
board[white_pawn] = 'P'
board[black_knight] = 'n'

def bishop(insquare):
    '''
    Gets all legal moves for bishop on insquare
    output is a list (outsquares) of indices of possible squares
    '''
    out_squares = []
    y,x = insquare

    y1 = y-1 # these are steps in one of the four directions bishops can go
    x1 = x-1
    while (x1 > -1) and (y1 > -1): # edge of the board
        if not board[(y1,x1)].isupper(): # if not a white piece...
            out_squares.append((y1,x1)) # square is legal
            if board[(y1,x1)].islower(): # if black piece...
                y1 = -1 # look no further in this direction
        else: # if white piece...
            y1 = -1 # look no further in this direction
        y1 -= 1 # check next square
        x1 -= 1

    # check all other directions
    y1 = y+1
    x1 = x+1
    while (x1 < 8) and (y1 < 8):
        if not board[(y1,x1)].isupper():
            out_squares.append((y1,x1))
            if board[(y1,x1)].islower():
                y1 = 8
        else:
            y1 = 8
        y1 += 1
        x1 += 1

    y1 = y + 1
    x1 = x - 1
    while (x1 > -1) and (y1 < 8):
        if not board[(y1,x1)].isupper():
            out_squares.append((y1,x1))
            if board[(y1,x1)].islower():
                y1 = 8
        else:
            y1 = 8
        y1 += 1
        x1 -= 1

    y1 = y - 1
    x1 = x + 1
    while (x1 < 8) and (y1 > -1):
        if not board[(y1,x1)].isupper():
            out_squares.append((y1,x1))
            if board[(y1,x1)].islower():
                y1 = -1
        else:
            y1 = -1
        y1 = y1 - 1
        x1 = x1 + 1
    return out_squares

# Get all legal moves for the white bishop
print bishop((4,5))
# >>> [(3, 4), (2, 3), (1, 2), (5, 6), (5, 4), (6, 3), (7, 2), (3, 6), (2, 7)]


texts:
I wrote this code where division can be done without using C's builtin operator:
#include <stdio.h>
#include <math.h>

int idiv(int a, int b) {
    return a * (pow(b, -1));
}

int main(void) {
    /* 15/3 is 5 */
    printf("%d\n", idiv(15, 3));
    return 0;
}

Is there anything I could do to make this code faster? I benchmarked it with the division operator and it was more than 10x faster.


texts: Entity Framework - updating two different arrays of child associations

texts:
Exercises have Muscles and Tools.  When someone adds or updates an Exercise, they also send an array of Tools and Muscles.  Adds are pretty straightforward, but my update method feels a bit bulky.  How can I simplify this?

public void UpdateExercise(Exercise exercise) {
            var dbExercise = db.Exercises.First(s => s.ExerciseId == exercise.ExerciseId);
            var dbTools = db.Tools.ToList();
            var dbMuscles = db.Muscles.ToList();

            dbExercise.Title = exercise.Title;

            // handle tools
            var existingTools = dbExercise.Tools.ToList();
            foreach (var newTool in exercise.Tools) {
                // handle pre-existing
                var match = existingTools.FirstOrDefault(s => s.ToolId == newTool.ToolId);
                if (match != null) {
                    existingTools.Remove(match);
                }
                else {
                    // add newTool to dbExercise
                    dbExercise.Tools.Add(dbTools.First(s => s.ToolId == newTool.ToolId));
                }
            }
            foreach (var existingTool in existingTools) {
                dbExercise.Tools.Remove(dbTools.First(s => s.ToolId == existingTool.ToolId));
            }

            // handle exercises
            var existingMuscles = dbExercise.Muscles.ToList();
            foreach (var newMuscle in exercise.Muscles) {
                // handle pre-existing
                var match = existingMuscles.FirstOrDefault(s => s.MuscleId == newMuscle.MuscleId);
                if (match != null) {
                    existingMuscles.Remove(match);
                } else {
                    // add newMuscle to dbExercise
                    dbExercise.Muscles.Add(dbMuscles.First(s => s.MuscleId == newMuscle.MuscleId));
                }
            }
            foreach (var existingMuscle in existingMuscles) {
                dbExercise.Muscles.Remove(dbMuscles.First(s => s.MuscleId == existingMuscle.MuscleId));
            }

            db.ChangeTracker.Entries<Tool>().ToList().ForEach(p => p.State = EntityState.Unchanged);
            db.ChangeTracker.Entries<Muscle>().ToList().ForEach(p => p.State = EntityState.Unchanged);

            db.SaveChanges();
        }

Exercise:

public class Exercise {

        public Exercise() {
            Tools = new Collection<Tool>();
            Muscles = new Collection<Muscle>();
        }

        [Key]
        [Required]
        public int ExerciseId { get; set; }

        [StringLength(300, ErrorMessage = "The value cannot exceed 300 characters. ")]
        public string Title { get; set; }

        public virtual ICollection<Tool> Tools { get; set; }
        public virtual ICollection<Muscle> Muscles { get; set; }

    }


texts: Binding data to a ComboBox and then showing ValueMember in another TextBox

texts:
I have a comboBox and a TextBox in the View and when the view is loaded, the ComboBox should be populated. After that when a user selects particular item from the ComboBox, its related ValueMember should be displayed in the TextBox.

The View doesn't know about DAL or Presenter and, it only has properties and events.

VIEW

public partial class frmBankAccount : Form, IBankAccountView
{

    public event EventHandler OnLoadEmployees;

    public BindingSource LoadingEmployees
    {
        set { cmbName.DataSource = value; cmbName.DisplayMember = "Name"; cmbName.ValueMember = "Emp_ID"; }
    }

    private void frmBankAccount_Load(object sender, EventArgs e)
    {
         OnLoadEmployees(sender, e);
    }

    private void cmbName_SelectedValueChanged(object sender, EventArgs e)
    {
        txtEID.Text = cmbName.SelectedValue.ToString();
    }

}

When the event fires, Presenter gets a DataTable from DataService and binds it to the ComboBox through the property.

PRESENTER

class BankAccountPresenter : BasePresenter
{
    public BankAccountPresenter(IBankAccount model, IBankAccountView view, IDataService dataService )
    {
        _DataService = dataService;
        _Model = model;
        _View = view;

        this.WireUpViewEvents();
    }

    private void WireUpViewEvents()
    {
        _View.OnLoadEmployees += new EventHandler(_View_OnLoadEmployees);
    }

    private void _View_OnLoadEmployees(object sender, EventArgs e)
    {
        LoadEmployeeNames();
    }

    private void LoadEmployeeNames()
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = _DataService.LoadEmplyees(); //DataService returns a DataTabel with "Emp_ID" and "Name"
        _View.LoadingEmployees = bs;
    }

    //Main window will call this method to load the View
    public void Show()
    {
        _View.ShowDialog();
    }

}

NOTE: When populating ComboBox since I need only two fields (Emp_ID and Name), The DataService returns a DataTable instead of the Model as the model has about 10 other fields as well. The Model will be used in subsequent tasks like Search, Insert, Update etc.

Could you please review this code and provide your feedback? You may give your attention to the way that I've used properties to set DisplayMember and ValueMember of the Combo. If there is anything which is not acceptable kindly let me know with an alternate solution.


texts: Refactor to provide for multiple instances on a single page

texts:
I have a script that separates the date from a datepicker into day, month, and year. It works fine when there is one form on the page but not when there is a second one (presumably due to the id being the same). How can I add a value to my id and name so that they are unique values if the script runs twice on the same page?

var now = new Date();
var date = jQuery('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

date.val(today);

jQuery('form').on('submit', function() {

    var newVal = date.val().split('-'),
        dateParts = {
            year: parseInt(newVal[0], 10),
            month: parseInt(newVal[1], 10),
            day: parseInt(newVal[2], 10)
        };

    jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) {
        var name = 'date_' + key;

        return jQuery('<input>', {
            type: 'hidden',
            name: name,
            id: name,
            value: dateParts[key]
        });
    }));

});

Here is the form that isn't posting the correct date:

<form id="modal_res" action="http://www.site.com/search.php" method="get" name="disponibilita" target="_blank" class="custom">

                <?php _e('Date:', 'hostel_mama' )?><input type="date" name="date" id="modal_date" class="form-date datepicker">

                <?php _e('Nights:', 'hostel_mama' )?><input type="number" name="nights" id="modal_nights" value="2">

<?php _e('Guests:', 'hostel_mama' )?><input type="number" name="people" id="modal_people" value="1">

                <input name="ref" type="hidden" id="modal_ref" value="558" />
                <input name="langClient" type="hidden" id="modal_langClient" value="eng" />

                <?php _e('Currency:', 'hostel_mama' )?>
                    <select name="expr" id="modal_expr">
        <option value="EUR" selected="selected"><?php _e('EURO', 'hostel_mama' )?></option>
        <option value="USD"><?php _e('US Dollar', 'hostel_mama' )?></option>
        <option value="GBP"><?php _e('British Pound', 'hostel_mama' )?></option>
        </select>

                <input type="submit" name="submit" class="button radius text-center" value="Click to Book">

            </form>


texts: Optimize code for sending collected data to a database

texts:
I'm sending some data over to a database. There is a particular part that requires me to send a bunch of stuff all at once. It seems a little silly to me to write it this way. I feel that I could do this with an array and for loop, but I'm not sure about how that would look. I tried finding implementations elsewhere but I'm not even sure how to phrase what it is I'm looking for.

$sql = "
        INSERT INTO `computers` (`ComputerName`, `usage_0`, `usage_10`, `usage_20`, `usage_30`, `usage_40`, `usage_50`, `usage_60`, `usage_70`, `usage_80`, `usage_90`, `users`, `OrderDate`)
        VALUES (
        '" . mysqli_real_escape_string($cxn, $_POST['ComputerName']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_0']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_10']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_20']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_30']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_40']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_50']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_60']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_70']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_80']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['usage_90']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['users']) . "',
        '" . mysqli_real_escape_string($cxn, $_POST['OrderDate']) . "');
";

mysqli_query($cxn, $sql);


texts: Creating an array length n * n, separating it into n groups, and adding numbers to it n times

texts:
I am completing the CodingBat exercises for Java. Here is the one I have completed just now:

Given n > = 0, create an array length n * n with the following pattern, shown here for n = 3 :
{0, 0, 1,    0, 2, 1,    3, 2, 1} (spaces added to show the 3 groups).

Here is my code:
    public int[] squareUp(int n){

    int[] ary = new int[n * n];
    int numberToInsert = 1;
    int count = 0;
    int target = n;

    //Guard condition for n = 1
    if (n == 1) {
        ary[0] = 1;
        return ary;
    }

    //Do the following n times
    for (int i = 0; i < n; i++) {
        //Working from the end of the array backwards, insert the number
        //at the appropriate point
        for (int j = ary.length - numberToInsert; j > 0; j -= n) {
            ary[j] = numberToInsert;
            //The amount of times a number is inserted decreases each
            //iteration
            count++;
            if (count == target) {
                count = 0;
                target--;
                break;
            }
        }
        numberToInsert++;
    }
    return ary;
}

My questions are:

How would I implement this without the guard condition? The result without it is 0 because it doesn't get as far as the second for loop, as numberToInsert is already 1. I tried to set this as 0, and increment it later in the code, but I couldn't figure this out.
What alternative is there to the count and target system I implemented? Was this a good or bad way to achieve the outcome?
How else could the numbers be inserted? The method I used felt the most logical but I'm curious to see other methods.


texts:
So, I fixed my problem with a public ViewModel for my MainPage like this:

MainPage.xaml.cs:

private static MainPageVM Data = new MainPageVM();
public MainPage()
{
    this.InitializeComponent();
    SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

    this.DataContext = Data;

    this.SizeChanged += (s, args) =>
    {
        PageSizeChanged();
    };

    Windows.Storage.ApplicationData.Current.DataChanged += (a, o) =>
    {
        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Data.Theme = (int)ApplicationData.Current.RoamingSettings.Values["Theme"];
        });
    };
}

MainPageVM.cs:

private void SetValues()
{
    if (Windows.Storage.ApplicationData.Current.RoamingSettings.Values.ContainsKey("Theme"))
    {
        int value = (int)Windows.Storage.ApplicationData.Current.RoamingSettings.Values["Theme"];
        if (value >= 0 && value <= 2) { Theme = value; }
        else { Theme = 0; }
    }
    else { Theme = 0; }
}

private int _theme = 0;
public int Theme
{
    get { return _theme; }
    set
    {
        if (value == _theme) return;
        _theme = value;
        OnPropertyChanged();
    }
}

Settings.xaml.cs:

private void InitSettings()
{
    if (Windows.Storage.ApplicationData.Current.RoamingSettings.Values.ContainsKey("Theme"))
    {
        int value = (int)Windows.Storage.ApplicationData.Current.RoamingSettings.Values["Theme"];
        if (value >= 0 && value <= 2) { Theme.SelectedIndex = value; }
        else { Theme.SelectedIndex = 0; }
    }
    else { Theme.SelectedIndex = 0; }
}

private void ThemeChanged(object sender, SelectionChangedEventArgs e)
{
    ApplicationData.Current.RoamingSettings.Values["Theme"] = Theme.SelectedIndex;
    ApplicationData.Current.SignalDataChanged();
}

Settings.xaml:

    <StackPanel>
        <TextBlock FontSize="15" Margin="0,5">Text and background color:</TextBlock>
        <ComboBox Name="Theme" SelectionChanged="ThemeChanged">
            <ComboBoxItem Content="Black on White/Purple" Foreground="Black" Background="White"/>
            <ComboBoxItem Content="White on Black/White" Foreground="White" Background="Black"/>
            <ComboBoxItem Content="Black on White/Gold" Foreground="Black" Background="White"/>
        </ComboBox>
    </StackPanel>
</StackPanel>

There is similar code for each setting, but this is a good representation of it.  It doesn't feel right to use an int to represent my theme; should this be an enum?  Please tell me all the problems now so I don't have to refactor again later.


texts:
I am searching a recursive solution space and would like to return the first match I find. (I am using this to solve sudoku, but I guess this would apply to any recursively defined problem or datastructure).

So, in pseudocode, I need to call a function repeatedly with a set of possible input values, and return the first non-nil result:

for each possible input i:
    r = do-something(i)
    if r <> nil:
        return r
return nil

My first attempt was to just translate this into clojure:

(defn find-first
  [func values]
  (loop [v values]
    (if (empty? v)
      nil
      (if-let [ret (func (first v))]
        ret
        (recur (rest v))))))

But whenever I use (loop) it feels like I am programming C and not clojure, so I tried looking at this as applying a function to a sequence and returning the first non-nil result:

(defn find-first-2
  [do-something range]
  (->> range
       (map do-something)
       (remove nil?)
       first))

This looks more like clojure, and should work the same way because of lazy sequences. However, lazy sequences actually chunk items in sets of 32, so when my ranges are shorter than 32 items this isn't really lazy at all.

I have found the "unchunk"-trick creating really lazy sequences, but this also doesn't really "feel" right...

What would be other ways of implementing this?


texts: Parsing Windows Bitmap header information

texts:
I am working a a C# program that will manipulate bitmap images. The first step is to read in the File Header and the Windows BITMAPINFOHEADER.

That will give me enough information to loop through pixels and do my manipulations.

Here is the class that reads the file header,

using System;
using System.IO;

namespace Bitmanipulate
{
    public class BMPFileHeader
    {
        char[] header_field = new char[2];
        private uint file_byte_size;
        private uint pixel_start;

        public BMPFileHeader(BinaryReader br)
        {
            br.BaseStream.Seek(0, SeekOrigin.Begin);
            header_field[0] = br.ReadChar();//1
            header_field[1] = br.ReadChar();//2
            file_byte_size = br.ReadUInt32();//6
            br.ReadUInt16();//8
            br.ReadUInt16();//10
            pixel_start = br.ReadUInt32();//14
        }

        public void show()
        {
            Console.WriteLine("Header Field");
            Console.WriteLine(header_field);
            Console.WriteLine("File size bytes");
            Console.WriteLine(file_byte_size);
            Console.WriteLine("Pixel Start");
            Console.WriteLine(pixel_start);
        }
    }
}

and here is the class reads the Windows BITMAPINFOHEADER

using System;
using System.IO;

namespace Bitmanipulate
{
    public class BMPHeaderReader
    {

        private uint header_size;
        private uint pixel_width;
        private uint pixel_height;
        private ushort pixel_depth;
        private uint row_size;
        private uint padding_bits;
        private uint padding_bytes;
        private uint width_bytes;
        private uint pixels;

        public BMPHeaderReader(BinaryReader br)
        {
            br.BaseStream.Seek(14, SeekOrigin.Begin);
            header_size = br.ReadUInt32();//18
            pixel_width = br.ReadUInt32();//22
            pixel_height = br.ReadUInt32();//26
            br.ReadUInt16();//28
            pixel_depth = br.ReadUInt16();//30
            row_size = (((pixel_depth * pixel_width) + 31) / 32) * 4;
            padding_bits = row_size * 8 - ((pixel_width * pixel_depth));
            padding_bytes = row_size - ((pixel_width * pixel_depth) / 8);
            width_bytes = (pixel_width * pixel_depth) / 8;
            pixels = pixel_height * pixel_width;
        }

        public void show()
        {
            Console.WriteLine("Header size");
            Console.WriteLine(header_size);
            Console.WriteLine("Pixel Width");
            Console.WriteLine(pixel_width);
            Console.WriteLine("Pixel Height");
            Console.WriteLine(pixel_height);
            Console.WriteLine("Pixel Depth");
            Console.WriteLine(pixel_depth);
            Console.WriteLine("Pixels");
            Console.WriteLine(pixels);
            Console.WriteLine("Row size");
            Console.WriteLine(row_size);
            Console.WriteLine("Padding bits");
            Console.WriteLine(padding_bits);
            Console.WriteLine("Padding bytes");
            Console.WriteLine(padding_bytes);

        }
    }
}

I have omitted the getters for clarity.

As this is basically my first ever C# program, is there anything that I am missing?


texts:
I wrote code which sorts items, based on parameters (IconConfiguration). I have a map of items which have index and item so basically a predefined list on which index item should be, and maxPositions parameter which is kind of a limit of how big my list can be. I wrote a code but its repetitive and pretty ugly when i check it, but i am unable to get idea on what to refactor.

private List<GWBaseData> applyItemsIndex(List<GWBaseData> gwInputBaseDataList) { //TODO: Refactor repetitive code?
        List<GWBaseData> gwBaseDataList = new ArrayList<>();

        if (iconConfiguration.getMax_positions() != -1) {
            for (int i = 0; i < gwInputBaseDataList.size(); i++) {
                if (gwBaseDataList.size() < iconConfiguration.getMax_positions()) {
                    if (getItemsMap().get(i) != null && getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)) != null) {
                        gwBaseDataList.add(i, getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)));
                    } else {
                        for (int j = 0; j < gwInputBaseDataList.size(); j++) {
                            if (!gwBaseDataList.contains(gwInputBaseDataList.get(j))) {
                                gwBaseDataList.add(gwInputBaseDataList.get(j));
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            for (int i = 0; i < gwInputBaseDataList.size(); i++) {
                if (getItemsMap().get(i) != null && getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)) != null) {
                    gwBaseDataList.add(i, getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)));
                } else {
                    for (int j = 0; j < gwInputBaseDataList.size(); j++) {
                        if (!gwBaseDataList.contains(gwInputBaseDataList.get(j))) {
                            gwBaseDataList.add(gwInputBaseDataList.get(j));
                            break;
                        }
                    }
                }
            }
        }

        return gwBaseDataList;
    }

So basically the whole difference between both block is only  one additional if (if (gwBaseDataList.size() < iconConfiguration.getMax_positions()))


texts:
I want to optimize the performance of this SQL query. If I populate this hashtable with one million keys the query will take around minute. How I can optimize this Java method for faster execution?

private HashMap<String, Boolean> selectedIds = new HashMap<>();

public void deleteSelectedIDs() throws SQLException {

        if (ds == null) {
            throw new SQLException();
        }

        Connection conn = ds.getConnection();
        if (conn == null) {
            throw new SQLException();
        }

        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            conn.setAutoCommit(false);
            boolean committed = false;
            try {
                String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?";

                Set<String> keySet = selectedIds.keySet();
                String[] keys = new String[]{};
                keys = selectedIds.keySet().toArray(keys);
                ps = conn.prepareStatement(sqlDeleteQuery);

                for (int i = 0; i < keys.length; i++) {
                    if (selectedIds.get(keys[i]).booleanValue()) {
                        ps.setString(1, keys[i]);
                        ps.executeUpdate();
                        ps.clearParameters();
                        selectedIds.put(keys[i], false); //get(keys[i]) = false;
                    }
                }

                conn.commit();
                committed = true;

                //selectedIds.clear();
            } finally {
                if (!committed) {
                    conn.rollback();
                }
            }
        } finally {
            ps.close();
            conn.close();
        }
    }
private HashMap<String, Boolean> selectedIds = new HashMap<>();

public void deleteSelectedIDs() throws SQLException {

        if (ds == null) {
            throw new SQLException();
        }

        Connection conn = ds.getConnection();
        if (conn == null) {
            throw new SQLException();
        }

        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            conn.setAutoCommit(false);
            boolean committed = false;
            try {
                String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?";

                Set<String> keySet = selectedIds.keySet();
                String[] keys = new String[]{};
                keys = selectedIds.keySet().toArray(keys);
                ps = conn.prepareStatement(sqlDeleteQuery);

                for (int i = 0; i < keys.length; i++) {
                    if (selectedIds.get(keys[i]).booleanValue()) {
                        ps.setString(1, keys[i]);
                        ps.executeUpdate();
                        ps.clearParameters();
                        selectedIds.put(keys[i], false); //get(keys[i]) = false;
                    }
                }

                conn.commit();
                committed = true;

                //selectedIds.clear();
            } finally {
                if (!committed) {
                    conn.rollback();
                }
            }
        } finally {
            ps.close();
            conn.close();
        }
    }


texts:
I need some kind of thin wrapper object to mark dictionary keys, like:

d = {
  Required('name'): str,
  Optional('age'): int,
}

And these wrappers should behave like the wrapped object (comparison, hashing, etc):

marked = Required('name')
marked == 'name'  #-> True
d[marked] = 'hello'
d['name']  #-> 'hello'

With a single additional property: it should remember the added class:

isinstance(marked, Required)  #-> True

I dislike those heavyweight Proxy Patterns which mimic all special properties and thinking of the following idea instead:

class Wrapper(object):
    def __new__(cls, value):
        value_type = type(value)
        Type = type(
            value_type.__name__,  # same name
            (cls, value_type),  # Wrapper + bases
            {})
        Type.__new__ = value_type.__new__  # prevent recursion
        return Type(value)

    # Override method
    def __repr__(self):
        return 'Wrapper({})'.format(self)

This basically instantiates the type again, but with an additional base, and seems to work:

v = 'abc'  # Wrapped value
vt = type(v)  # Wrapped value type
w = Wrapper(v)

assert w == v  # equality
assert isinstance(w, vt)  # type matches
assert isinstance(w, Wrapper)  # and is Wrapper
assert hash(w) == hash(v)  # hash matches (required for dict keys)

Can you think of any disadvantages of this approach?


texts: User Registration compress to use less querry, CPU posible

texts:
I want to find out if there are any improvements I can make to this code. How can I make it better, faster and use less queries? Or is it fine the way I wrote it?

<?php if ( $user_ID ) : ?>
<?php
global $user_identity;
?>

Bine ai revenit<?php echo $user_identity; ?> !

<?php
global $current_user;
$current_user = wp_get_current_user();
?>

Utilizatori|Profil|<a href="<?php echo wp_logout_url( get_bloginfo('url') ); ?>" title="Logout">Logout

<?php
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
    echo get_avatar( $current_user->user_email, 40 );
}
?>

<?php else : ?>

<form name="loginform" id="loginform" action="<?php echo get_option('siteurl'); ?>/wp-login.php" method="post">
<input value="Utilizator" class="input" type="text" size="10" tabindex="10" name="log" id="user_login" onfocus="if (this.value == 'Utilizator') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Utilizator';}" />
<input value="Parola" class="input" type="password" size="10" tabindex="20" name="pwd" id="user_pass" onfocus="if (this.value == 'Parola') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Parola';}" />
<input name="wp-submit" id="wp-submit" value="Login" tabindex="100" type="submit">

Recuperare parolaInregistrare<input name="rememberme" id="rememberme" value="forever" tabindex="90" type="checkbox"> Retine parola?

<input name="redirect_to" value="<?php echo get_option('siteurl'); ?>" type="hidden">
<input name="testcookie" value="1" type="hidden">
</form>

<?php endif; ?>


texts: ConditionalActions through std::function Lambdas

texts:
So I just experimented with some code to make a huge if-else construct more human readable, extendable and configurable (switch positions of conditions).

The idea was to have a vector that contains all conditions and their actions and then just iterate over the vector, executing their ConditionalAction.

I solved it with lambdas with capture so I could use membervariables of the class where the ConditionalActions() method is implemented as well as additional parameters without having to define parameters in the std::function declaration.

Additionally I outsourced the CConditionalAction definitions to another header that I included in the method itself. This is the main part that is causing a hassle with colleagues.

So

void ElseIfConstruct()
{
    int SomeVariable = 0;

    if(FirstCondition)
    {
        FirstAction(); // uses membervariables
    }
    else if (SecondCondition)
    {
        SecondAction(SomeVariable); // void SecondAction(&int refParameter)
    }
    //else if ... and so on
    else
    {
        LastAction();
    }
}

becomes

MyConditionalActions.h

#ifdef USE_CONDITIONAL_ACTIONS
// ifdef so the compiler does not try to compile.
// alternatively exclude it from build.

CConditionalAction FirstConditionalAction([&]()
{
    if (false)
    {
        return true;
    }
    return false;
});

CConditionalAction SecondConditionalAction([&]()
{
    if (false)
    {
        return true;
    }
    return false;
});

CConditionalAction LastConditionalAction([&]()
{
    if (true)
    {
        return true;
    }
    return false;
});

#endif

ConditionalAction.h

#include <functional>

class CConditionalAction
{
public:
    CConditionalAction(std::function<bool()> ConditionalAction)
    : m_ConditionalAction(ConditionalAction) {}

    bool operator()() const { return m_ConditionalAction(); }
    std::function<bool()> m_ConditionalAction = nullptr;
};

MyClass.cpp

#include "ConditionalAction.h"
#include <vector>

void ConditionedActions()
{
    #define USE_CONDITIONAL_ACTIONS
    #include "MyConditionalActions.h"
    #undef USE_CONDITIONAL_ACTIONS

    // the vector will later be created just once but could also be used to sort out
    // ConditionalActions that don't have to be tested at all in runtime.

    std::vector<CConditionalAction> vecConditionalActions;
    vecConditionalActions.push_back(FirstConditionalAction);
    vecConditionalActions.push_back(SecondConditionalAction);
    //vecConditionalActions.push_back(MoreConditionalActions);
    vecConditionalActions.push_back(LastConditionalAction);

    for (const auto& ConditionalAction : vecConditionalActions)
    {
        if (ConditionalAction())
        {
            return;
        }
    }
}

Restructuring then becomes a copy-paste in MyClass.cpp
Extending becomes a push_back into the vector in MyClass.cpp and a copy-paste with adjustments in the MyConditionalActions.h


texts: Checking hash and passwords with a wordlist, more efficient

texts:
I have done a small code in which with a wordlist (out68.lst) I get the passwords from the hashes in the file 'shadow3'.

import crypt
import string
import itertools
import datetime

dir = "shadow3"                          #File that contains hashes and users
file = open(dir, 'r').readlines()

username = []
hashed = []
k=0

for x in file:
    usr, hshd, wtf, iss, this, thing, here, doing, example = x.split(':')
    username.append(usr)
    hashed.append(hshd)
#Loop in order to split the data in the file and store it in username and hashed

grupo1=open('out68.lst','r').readlines()
long=len(grupo1)
print(long)
for y in grupo1:    #Loop in order to go through all the possible words available
  c = 0
  y=y.rstrip('\n')
  y=y.capitalize()
  k = k+1
  if k==(long//100):
    print('1%')
  if k==(long//10):
    print('10%')
  if k==(long//5):
    print('20%')
  if k==(3*long//10):
    print('30%')
  if k==(4*long//10):     #Just to check the progress
    print('40%')
  if k==(5*long//10):
    print('50%')
  if k==(6*long//10):
    print('60%')
  if k==(7*long//10):
    print('70%')
  if k==(8*long//10):
    print('80%')
  if k==(9*long//10):
    print('90%')

  for x in hashed:
      rehashed = crypt.crypt(y, x) #Hash verification f(passwor+hash)=hash?
      if rehashed == x:
          print('La contraseña del usuario ' + username[c] + ' es ' + y)
      c = c + 1

It does work but depending on the size of the files, it can last now from 30 minutes to 6 hours.  So I am asking if there is any way to improve the performance, by paralelization, or GPU processing (but I have no idea about this).


texts:
This Google Sheets script performs an iterative (circular) calculation to find values based on a gross percentage of project cost. Range names are used so that users can add/delete rows/columns and not have to reset the code. The ranges included in copyTo() are part of the total sum of project cost and based on a percentage of project cost. During the iterations, each time ranges are copied and pasted, the overall project cost changes and therefore the values of each range is changed.

The iterations take about two seconds each, which is too slow. How can I improve their speed?

//<!-- FEE, BOND, & INSURANCE CALCULATOR --!>
  function feeBondInsCalculator (){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Pretty Sum Form");
  sheet.activate();
  // Get all variables from named ranges
  var bondValue = ss.getRangeByName("bondValue");
  var bondCalc = ss.getRangeByName("bondCalc");
  var insValue = ss.getRangeByName("insValue");
  var insCalc = ss.getRangeByName("insCalc");
  var feeValue = ss.getRangeByName("feeValue");
  var feeCalc = ss.getRangeByName("feeCalc");
  var interCount = ss.getRangeByName("interCount")

  // Interative calculation to paste calculated values into the body of the spreadsheet
    for (var i = 0; i<11; i++){
      feeCalc.copyTo(ss.getRangeByName("feeValue"), {contentsOnly: true});
      bondCalc.copyTo(ss.getRangeByName("bondValue"), {contentsOnly: true});
      insCalc.copyTo(ss.getRangeByName("insValue"), {contentsOnly: true});
      interCount.setValue(i)
    }
  }


texts: Get the first item in a sequence that matches a condition

texts:
I've been trying to figure out what's the best, most Pythonic way to get the first element of a sequence that matches a condition. Here are three options:

I don't like that I've written caller[0].f_locals.get("runner") twice, but it feels most Pythonic otherwise.
runner = next(
    caller[0].f_locals.get("runner")
    for caller in inspect.stack()
    if isinstance(caller[0].f_locals.get("runner"), AbstractRunner)
)

Is it weird to rely on an assignment during the loop?
for caller in inspect.stack():
    runner = caller[0].f_locals.get("runner")
    if isinstance(runner, AbstractRunner):
        break

The second line is Pythonic and all, but the first line is only there to set up a generator where you no longer have to compute the expression (only apply the conditional in the second line).
generator = (caller[0].f_locals.get("runner") for caller in inspect.stack())
runner = next(x for x in generator if isinstance(x, AbstractRunner))

There's no performance difference at all from my tests.


texts:
My program has to detect the real file type of a given file using signatures. For now I'm just checking JPG, but I want to add more.

Dim files() As String = IO.Directory.GetFiles(pictures)
Dim file_data As Byte()

Dim jpg_file_extension() As Byte = {&HFF, &HD8, &HFF}
Dim office_file_extension() As Byte = {&H50, &H4B, &H3, &H4, &H14, &H0, &H6, &H0}

Dim check As Integer = 0

For Each file As String In files
    file_data = IO.File.ReadAllBytes(file)
    If file_data.Length > 2 Then
        For i = 0 To jpg_file_extension.Length - 1
            If file_data(i) = jpg_file_extension(i) Then
                check += 1
            Else
                check = 0
                Exit For
            End If
        Next
        If (check.ToString.Length = jpg_file_extension.Length - 1) Then
            MsgBox(file.Split("\").Last & ": its jpg")
        End If
     End If
Next

The code looks a bit messy right now and It's only checking one file type, my questions are:

How can I improve this code, make it cleaner and efficient.
Is there a way to implement this code in such a way that I can have a function, give it the file data and check if the signature is "whitelisted"?


texts:
I am attempting to build my own website, based off Google's Material Design principles, to better my design/UX skills.

I am currently working on effects for my navigation, I wondered what would be best to lower browser resource usage when viewing my web page.

  Quick Example:
  When scrolling, without wrapping certain property changes within an if, does the browser (jQuery) attempt to make the property changes although they have already been made?

var scrollPos = $(window).scrollTop();
$(window).scroll(function() {
    scrollPos = $(window).scrollTop();
    if(scrollPos >= 200) {
        if(!$('div.header').is('[style]')) { $('div.header').css('position','fixed'); };
    };
};

compared to...

var scrollPos = $(window).scrollTop();
$(window).scroll(function() {
    scrollPos = $(window).scrollTop();
    if(scrollPos >= 200) {
        $('div.header').is('[style]')) { $('div.header').css('position','fixed');
    };
};

Full Code Example:

//scroll listener
$(window).scroll(function() {
    scrollPos = $(window).scrollTop();
    if(scrollPos >= 200) {
        if(!$('div.header').is('[style]')) { $('div.header').css('position','fixed'); };
        if(!$('div.nav').is('[style]')) { $('div.nav').css('padding','0'); };
        $('div.nav > ul > li, div.nav > ul > ul > li')
            .not('.faded')
            .css('display','none')
            .fadeIn(250)
            .addClass('faded')
            .css('display','inline-block');
        if(!$('div.header div.title').is('[style]')) {
            $('div.header div.title')
                .css('display','none')
                .children('h1')
                .css('display','none');
        }
    } else {
        if($('div.header').is('[style]')) { $('div.header').removeAttr('style'); };
        if($('div.header div.title').is('[style]')) { $('div.header div.title').removeAttr('style'); };
        if($('div.nav').is('[style]')) { $('div.nav').removeAttr('style'); };
        if($('div.nav li').hasCLass('faded')) { $('div.nav li').removeClass('faded'); };
        if($('div.nav li.nav-title').is('[style]')) {
            $('div.nav li.nav-title').fadeOut(250, function() {
                $('div.header div.title h1').fadeIn(250);
            });
        };
    };
});

compared to...

//scroll listener
$(window).scroll(function() {
    scrollPos = $(window).scrollTop();
    if(scrollPos >= 200) {
        $('div.header').css('position','fixed');
        $('div.nav').css('padding','0');
        $('div.nav > ul > li, div.nav > ul > ul > li')
            .not('.faded')
            .css('display','none')
            .fadeIn(250)
            .addClass('faded')
            .css('display','inline-block');
        $('div.header div.title')
            .css('display','none')
            .children('h1')
            .css('display','none');
    } else {
        $('div.header').css('position','static');
        $('div.header div.title').css('display','block');
        $('div.nav').removeAttr('style');
        $('div.nav li').removeClass('faded');
        $('div.nav li.nav-title').fadeOut(250, function() {
            $('div.header div.title h1').fadeIn(250);
        });
    };
});

Does either one make a difference in browser resource usage? Or is one incorrect?


texts:
Description:

Given a binary tree find the number of leaves. Although the problem is simple and has been solved many times I am more interested in find object oriented ways to solve the algorithmic problems.

Code:

interface Node {
   public int count();
 }

 class LeafNode implements Node {
   LeafNode() {}

   public int count() {
     return 1;
   }
 }

 class NonLeafNode implements Node {
   private Node left;
   private Node right;

   NonLeafNode(Node left, Node right) {
     this.left = left;
     this.right = right;
   }

   public int count() {
     return this.left.count() + this.right.count();
   }
 }

 class NullNode implements Node {
   public int count() {
     return 0;
   }
 }

 public class Main {
   public static void main(String[] args) {
     Node tree = new LeafNode();
     System.out.println(tree.count()); // 1

     tree = new NonLeafNode(new LeafNode(), new LeafNode());
     System.out.println(tree.count()); // 2

     tree = new NonLeafNode(
       new NonLeafNode(new LeafNode(), new NullNode()), new NullNode());
     System.out.println(tree.count()); // 2
   }
 }


texts: Converting UK drams to ounces and pounds in PHP

texts:
I have written this little function to convert UK weight drams (dr) to ounces (oz) and pounds (lbs). As far as my research goes, 1 lbs = 16 oz and 1 oz = 16 dr. I need the function to return an array of lbs, oz and dr.

Am I doing it right? Or is there a better way to do it? Has my method got any flaws?

function fromDrams($drams){

    // Nullify pounds
    $ouncesAndDrams = $drams % 256;

    $lbs = (int) ($drams / 256);
    $oz  = (int) ($ouncesAndDrams / 16);
    $dr  = $ouncesAndDrams % 16;

    return ['lbs' => $lbs, 'oz' => $oz, 'dr' => $dr];
}

It does return good values when tested:

fromDrams(273) = ['lbs' => 1, 'oz' => 1, 'dr' => 1];
fromDrams(272) = ['lbs' => 1, 'oz' => 1, 'dr' => 0];
fromDrams(271) = ['lbs' => 1, 'oz' => 0, 'dr' => 15];
fromDrams(256) = ['lbs' => 1, 'oz' => 0, 'dr' => 0];
fromDrams(32) = ['lbs' => 0, 'oz' => 2, 'dr' => 0];
fromDrams(17) = ['lbs' => 0, 'oz' => 1, 'dr' => 1];
fromDrams(15) = ['lbs' => 0, 'oz' => 0, 'dr' => 15];


texts: Was this an idiomatic and prudent way to extend R's matrix multiplication syntax? Should I have used R's object system?

texts:
After reading one too many Lisp books, I decided to try extending R's syntax. My goal was to implement repeated matrix multiplication in a way such that I could write matrix%^%n to produce the result from multiplying matrix by itself n times (where n is a natural number). I produced the following working code that gives the expected outputs, but found it unsatisfactory.
`%^%`<-function(squareMat,exponent)
{
  stopifnot(is.matrix(squareMat),is.numeric(exponent),exponent%%1==0)
  out<-diag(nrow = nrow(squareMat))
  for(i in seq_len(exponent)){out<-squareMat%*%out}
  out
}
testMatrix<-matrix(c(0,10,20,30),2,2)
lapply(0:3,function(k) testMatrix%^%k)#tests

For the purposes of this question, I'm happy to ignore the contents of my for loop. I know that it's not optimised. What I'm more interested in investigating is if this was a prudent way to extend R's syntax. I have listed my objection to my code below. If they are valid, how can they be addressed?

The method for checking if exponent is an integer is pathetic. I don't think that doing better is possible, but I would dearly love to be proven wrong.
My strongest objection is that I believe that this problem calls for an S3 or S4 solution, but I do not believe that one is possible. isS4(testMatrix) tells me that matrices are not S4 objects, ruling that out. S3 might be possible, but I'm unsure if this will make problem #1 even worse (because S3 is not very strict on types) or requiring risky hacking of the matrix type.
Because of problem #1, stopifnot does not throw useful error messages.
The job of throwing errors regarding the multiplication is delegated to %*%. I'm OK with that, but I don't know if I should be.
Again, ignoring the content of the for loop, was for actually the right thing to use? Is there something like an apply family function for "the index of my loop doesn't actually matter, I just want to run this code seq_len(exponent) times"?


texts: Nearest Neighbor Algorithm (general nearest, forward-nearest, or backward-nearest)

texts:
I am trying to write an algorithm that can find user-specified nearest neighbors. By user-specified, I mean that the user can specify whether it's a general nearest neighbor, a forward-nearest neighbor, or a backward-nearest neighbor.

The idea for this code was inspired from this SO post. While it isn't ideal to search the entire array (perhaps use searchsorted as an alternative), I want to find all occurrences of the user-specified nearest value in the given data array. While there are other techniques that can be used to achieve the same goal (such as using the cumulative sum of differences of argsorted values), I feel the code below is easier to read/understand and is likely quicker since it performs less operations that require traversing the entire data array. That said, I would like to know if there are better approaches (in terms of speed) to achieve the same output, as this code will be applied to a dataset of at least ~70,000 data points. More than the value itself, I am concerned with the indices at which the values occur.

import numpy as np

Sample Data

sample = np.array([300, 800, 200, 500, 600, 750, 700, 450, 400, 550, 350, 900])
# sample = np.array([300, 800, 200, 500, 600, 750, 700, 450, 400, 550, 350, 900] * 2)

Main algorithm

def search_nearest(data, search_value, direction=None):
    """
    This function can find the nearest, forward-nearest, or
    backward-nearest value in data relative to the given search value.
    """

    if not isinstance(data, np.ndarray):
        data = np.array(data)

    print("\n>>     DATA\n{}\n".format(data))
    print(">>     SEARCH VALUE\n{}\n".format(search_value))

    if direction is None:
        delta = np.abs(data - search_value)
        res = np.where(delta == np.min(delta))[0]

    elif direction == 'forward':
        delta = data - search_value
        try:
            res = np.where(delta == np.min(delta[delta >= 0]))[0]
        except:
            raise ValueError("no forward nearest match exists")

    elif direction == 'backward':
        delta = search_value - data
        try:
            res = np.where(delta == np.min(delta[delta >= 0]))[0]
        except:
            raise ValueError("no backward nearest match exists")

    print(" .. INDEX OF NEAREST NUMBER\n{}\n".format(res))
    print(" .. NUMBER AT THAT INDEX\n{}\n".format(data[res]))
    print("--------------------")

Call the main function

# crd = None
crd = 'forward'
# crd = 'backward'

for val in (799, 301, 800, 250, 8, 901):
    search_nearest(sample, search_value=val, direction=crd)


texts: Replacing English words in a string with their Spanish equivalents by dictionary lookup

texts:
I want to improve my code's performance and running time, looking for write my loops better.

For example, I have a dictionary that contains words as keys, and their translation in Spanish as values.

{
    'Hello' : 'Hola',
    'Goodbye' : 'Adios',
    'Cheese' : 'Queso'
}

I also have a given English sentence, and I want to iterate over any word in my dict and replace it with the Spanish translation.
For this scenario I consider that up to one word could be exist in the given sentence.

I wrote a basic code that do that, but I am not sure that it is best practice:

words_list = {
        'Hello' : 'Hola',
        'Goodbye' : 'Adios',
        'Cheese' : 'Queso'
    }
sentence = "Hello, I want to talk Spanish"

for english_word in words_list.keys():
    if english_word in sentence:
        sentence = sentence.replace(english_word, words_list[english_word])
        break

print sentence

How can I write it better?


texts:
A code to check the time slice for each thread separately, it will receive an integer number from the command line for the number of threads to run simultaneously. Would love some feedback on what is possible to be done differently in order to improve it (e.g different functions to use which are more accurate?, etc.).
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

int curThread = 0;
void* f(void* thread_serial);

void main(int argc, char* argv[]){
    int N;//amount of threads to activate
    int i;//will be used as an index and thread's serial number
    int status;//will be used to indicate a failed thread creation
    int* serials;//will be used to save the serial number of a thread
    pthread_t* threads;

    //check if the amount of parameters is valid
    if (argc < 2){
        printf("ERROR - missing parameters\n");
        exit(EXIT_FAILURE);
    }

    N = atoi(argv[1]);//saves the amount of threads provided by the user

    threads = (pthread_t*)malloc(N * sizeof(pthread_t));//allocate threads
    serials = (int*)malloc(N * sizeof(int));//allocate array for the serial number of threads

    //check if allocation failed
    if (threads == NULL || serials == NULL){
        printf("ERROR - memory allocation failed!");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < N; i++){
        serials[i] = i + 1;

        //create new thread
        status = pthread_create(&threads[i], NULL, f, (void*)&serials[i]);

        //check if thread allocation failed
        if (status != 0){
            printf("ERROR - failed to create a thread");
            exit(EXIT_FAILURE);
        }
    }

    sleep(2);
    free(threads);
    free(serials);
}

void* f(void* thread_serial){
    int k = *(int*)thread_serial;
    struct timeval thread1, thread2;
    double elapsedTime;

    while(1){
        gettimeofday(&thread1, NULL);//start the timer
        curThread = k;//get the thread serial

        //while on the same thread
        while (curThread == k)
            gettimeofday(&thread2, NULL); //update the timer

        //compute and print the elapsed time in millisec
        elapsedTime = (thread2.tv_sec - thread1.tv_sec) * 1000.0;//sec to ms
        elapsedTime += (thread2.tv_usec - thread1.tv_usec) / 1000.0;//us to ms
        printf("Time slice for thread %d = %lf ms.\n", curThread, elapsedTime);
    }
}

One possible output:
Time slice for thread 1 = 54.410000 ms.
Time slice for thread 2 = 10.530000 ms.
Time slice for thread 3 = 44.491000 ms.
Time slice for thread 5 = 66.553000 ms.
Time slice for thread 4 = 56.311000 ms.
Time slice for thread 1 = 44.143000 ms.
Time slice for thread 3 = 43.631000 ms.
Time slice for thread 5 = 78.483000 ms.
Time slice for thread 2 = 56.536000 ms.
Time slice for thread 4 = 55.217000 ms.
Time slice for thread 1 = 56.470000 ms.
Time slice for thread 3 = 56.644000 ms.
Time slice for thread 5 = 43.937000 ms.
Time slice for thread 4 = 45.256000 ms.


texts:
I've put together a function in Delphi XE7 which returns the Dropbox directory path on my machine, as this path can be customized by the user.

This function currently works on my computer, but it could have many defects preventing it to work for other users on different machines. So I would be very grateful if anybody could point to these defects.

uses
  System.IOUtils, System.JSON, System.NetEncoding, JclSysInfo, JclStrings

function GetDropboxPath: string;
var
  tempstr: string;
  function ParseJsonStr(jStr, jPar1, jPar2: string): string;
  var
    jObj: TJSONObject;
    jVal: TJSONValue;
  begin
    Result:= '';
    jObj := TJSONObject.ParseJSONValue(jStr) as TJSONObject;
    try
      jVal:= jObj.Get(jPar1).JsonValue;
      Result:= TJSONObject(jVal).Get(jPar2).JsonValue.Value;
    finally
      jObj.Free;
    end;
  end;
begin
  Result := '';
  tempstr := IncludeTrailingBackslash(JclSysInfo.GetAppdataFolder) + 'Dropbox\';
  if DirectoryExists(tempstr) then
  begin
    if FileExists(tempstr + 'info.json') then // try with info.json
    begin
      tempstr := tempstr + 'info.json';
      tempstr := System.IOUtils.TFile.ReadAllText(tempstr);
      try
        tempstr := ParseJsonStr(tempstr, 'personal', 'path');
      except
        // Todo: log this error
        EXIT;
      end;
      Result := Trim(tempstr);
    end
    else if FileExists(tempstr + 'host.db') then // else try with host.db
    begin
      tempstr := tempstr + 'host.db';
      tempstr := Trim(JclStrings.StrTrimCharLeft(System.IOUtils.TFile.ReadAllText(tempstr), '0'));
      Result := Trim(TNetEncoding.Base64.Decode(tempstr)); // needs XE7
    end;
  end;
end;


texts: Java probability if 2 integers are coprime

texts:
Hi I am trying to write a programme that outputs the probability that the two randomly selected numbers are coprime

Two integers are coprime if the only positive integer that divides into both of them
is 1. In other words, the greatest common divisor of two coprime numbers is 1.
If two numbers x and y are selected randomly, the odds that they will be coprime
with each other is 61% (6 divided by PI^2). But what if we put some restrictions on
the two numbers? For example, if x is a randomly selected number that is divisible
by 7 and y is a randomly selected number that is divisible by 13? In this case, the
odds that they are coprime is 49%.
I am given a divisor of the first number and a divisor of the
second number. I must then output an integer from 0 to 100, which is the
percentage probability that the two randomly selected numbers are coprime.

here is what I have so far
import java.util.Scanner;
public class Main {
    public static int myTestMethod(int a, int b)
    //method taking two numbers a and b
    {
        //Calculating gcd because if gcd is 1 then a and b are //coprimes.
        if (b == 0)
            return a;
        else
            return myTestMethod(b, a % b);
    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a and b");
        int y;
        float p = 0;
        //taking inputs a and b two numbers.
        int a = sc.nextInt();
        int b = sc.nextInt();
        //Calculating gcd by calling method
        y = (myTestMethod(a, b));
        System.out.print("gcd is:");
        System.out.println(y);
        p = (myTestMethod(a, b));
        //if gcd is 1 the probability should be 1
        if (y == 1) {
            System.out.println("probability is:");
            System.out.println(p);
        }
        //else print probability as p/100.
        else {
            System.out.println("The probability is :");
            System.out.println(p / 100);
        }
    }
}

is this the correct way to go about it?


texts:
I have a method like this:

public boolean wasUserInactive() {
    boolean result = userInactive;
    userInactive = false;
    return result;
}

This works, but is there a “smarter” way to code this?


texts: Check if modelitem refers to currently logged in user with mvc identity

texts:
I'm using MVC in order to generate a couple of views within my webpage. For a way of logging in, I've decided to use Asp.net's Identity, which I am very happy with.

However, I'm trying to find an efficient/ 'normal' way of testing if the user is logged in, and are looking at info that refers to them.

As a test, I found that:

 if (User.Identity.Name == (Html.DisplayFor(modelItem => item.Email).ToString()))
        {

THIS IS ME

        }

razor code works for this.

However, this seems quite inefficient, and I was wondering if there is a more appropriate way of telling 'is this their row in which they can edit'.


texts: Elegant function to "increase" a JavaScript string - for example, turning "aac" into "aad"

texts:
I'm writing a function to increase a string so, for example, "aac" becomes "aad" and "aaz" becomes "aba". The result is horribly inelegant, I can't get it simple enough and I feel I'm missing something. How to improve that code?

function inc_str(str){
    var str = str.split("").map(function(a){ return a.charCodeAt(0); });
    var n = 1;
    while (n<str.length){
        str[str.length-n]++;
        if (str[str.length-n] > "z".charCodeAt(0))
            str[str.length-n] = "a".charCodeAt(0),
            ++n;
        else
            break;
    };
    return str.map(function(a){ return String.fromCharCode(a); }).join("");
};

Extra points for a brief functional style solution! (Even if it needs to implement other functional functions such as zip or whatever.)


texts: DFS/BFS implementation of Cormen's pseudo code

texts:
This is DFS/BFS C++ code for Cormen pseudo code. Please comment on this.

#include "iostream"
#include "vector"
#include "list"

enum color{
    WHITE,
    GREY,
    BLACK
};

struct edge{
    int destination_vertex;
    edge(int ver){
        destination_vertex = ver;
    }
};

struct vertex{
    int id;
    color visited;
    std::list<edge>  list;
    vertex(int _id){
        id = _id;
    }
};

class graph
{
private:
    std::vector<vertex> vertexes;
    void dfs_visits(vertex& source);
    int next;
public:
    graph(void){
        next = 0;
    }
    ~graph(void){}
    void dfs();
    void bfs();
};

void graph::dfs(void)
{
    for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
        iter->visited = WHITE;
    }

    for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
        if(iter->visited == WHITE){
            dfs_visits(*iter);
        }
    }
}

void graph::dfs_visits(vertex& source){
    source.visited = GREY;
    for(std::list<edge>::iterator iter = source.list.begin();iter != source.list.end();iter++){
        if(vertexes[iter->destination_vertex].visited == WHITE){
            dfs_visits(vertexes[iter->destination_vertex]);
        }
    }
    source.visited = BLACK;
    std::cout<< source.id <<std::endl;
}

void graph::bfs(){

    for(std::vector<vertex>::iterator iter=vertexes.begin();iter != vertexes.end();iter++){
        iter->visited = WHITE;
    }

    std::queue<vertex*> bsf_q;

    bsf_q.push(&vertexes[0]);

    while(!bsf_q.empty()){
        vertex * v = bsf_q.front();
        bsf_q.pop();

        for(std::list<edge>::iterator iter = v->list.begin() ;iter != v->list.end();iter++ ){
            if(vertexes[iter->destination_vertex].visited == WHITE){
                vertexes[iter->destination_vertex].visited = GREY;
                bsf_q.push(& vertexes[iter->destination_vertex]);
            }
        }

        v->visited = BLACK;
        std::cout << v->id <<std::endl;
    }
}


texts: Please help and improve this script for displaying search results

texts:
I wrote a search script, now I want a more efficient way of finding the keywords used for the search and make them bold. I used this code but it I feel it could be greatly improved on. Thanks for any suggestion.

// I use this code to select the lines to display
$lines = explode('.', trim($search_result));

// Break up the result into sentences
$j = 0; $line = '';
for($i = 0; $i < sizeof($lines); $i++) {
    // Look for the keywords in each of the line
    if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) ||
        strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])
    ) {
        $j++;
        $line .= trim($lines[$i])."...";
    }

    if ($j == 2)
        return $line;

    // If no keyword is found in first 100 lines/sentences, just display the first 3 lines
    if ($i == 100)
        return $lines[0]."...".$lines[1]."...".$lines[2];

}

I use this code to make the keywords bold

function findAndReplace($keywords, $sentence) {
    for ($i=0; $i<sizeof($keywords); $i++)
        $words[] = "<b>".ucfirst($keywords[$i])."</b>";

    return str_ireplace($keywords, $words, $sentence);
}


texts: Implementing PLC "Timer Pulse" function block in C++

texts:
I have been implementing a library of the PLC function blocks. One of the function blocks is the "Timer Pulse" function block which behavior is following:

I have implemented this function block in this manner

Tpulse.h:

#include <stdint.h>
#include "LogicBlk.h"

namespace LogicBlocks
{

// Timer Pulse i.e. logic one at the output for specified time as soon as 0->1 at the input
class Tpulse : public LogicBlk{
public:
    Tpulse(uint32_t*, uint32_t, uint32_t, uint32_t);
    virtual ~Tpulse();

    void Update(void);

private:

    uint32_t *m_BitsArray;
    uint32_t m_Input;
    uint32_t m_Output;
    uint32_t m_PulseTime;
    uint32_t m_StartTime;
    uint32_t m_ElapsedTime;
    uint32_t m_CurrentTime;

};

}

Tpulse.cpp:

LogicBlocks::Tpulse::Tpulse(uint32_t *bitsArray, uint32_t input, uint32_t output, uint32_t pulseTime):
                            m_BitsArray{bitsArray}, m_Input{input}, m_Output{output}, m_PulseTime{pulseTime}{
                                m_StartTime     = 0;
                                m_ElapsedTime   = 0;
                                m_CurrentTime   = 0;
}

LogicBlocks::Tpulse::~Tpulse(){
}

void LogicBlocks::Tpulse::Update(void){

    if(Utils::TestBitSet(m_BitsArray, m_Input) && Utils::TestBitClr(m_BitsArray, m_Output) && !m_ElapsedTime){

        m_StartTime = GetTick();
        SetBit(m_BitsArray, m_Output);

    }else if(Utils::TestBitSet(m_BitsArray, m_Output)){

        m_CurrentTime = GetTick();
        m_ElapsedTime = m_CurrentTime - m_StartTime;

        if(m_ElapsedTime >= m_PulseTime){

            ClrBit(m_BitsArray, m_Output);
            if(TestBitClr(m_BitsArray, m_Input)){

                m_ElapsedTime = 0;
            }
        }

    }else if(TestBitClr(m_BitsArray, m_Input) && TestBitClr(m_BitsArray, m_Output)){

        m_ElapsedTime = 0;

    }

}

LogicBlk.h

namespace LogicBlocks
{

class LogicBlk {
public:

    virtual void Update(void) = 0;

private:

};

}

Based on the tests which I have already done it seems to me that it works fine but I am not sure. Please can anybody assess my code from functional and programming style point of view? Thank you in advance for any suggestions.


texts:
I have this Python project to draw tessellated triangles on the screen. It takes the height to form the size of the triangle, cols to specify how many triangles on a line, and rows which is how many lines it outputs.
This program has taken me some time to put together and I'm not sure if this is the best way to do this. The first line is just the normal triangle, the second line and every other line after however only should show half of the triangle on the first and last column.

Here's my .py file:

import sys

print("make sure shell in full screen so the triangles are viewed properly... or disable word wrap :)")
height          = int(input("height"))
cols            = int(input("cols"))
rows            = int(input("rows"))

MAX_PAGE_WIDTH = 19 * 8

width = height * 2 - 1
if((width * cols) > MAX_PAGE_WIDTH):
    print("Triangles not gonna fit on page, please enter smaller params... :/")
    sys.exit()

def get_even_number(num):
    return num % 2 == 0

triangle        = ""

for column_row in range(rows):
    half_space      = height - 1
    stars           = 1

    for row_of_triangle in range(height):
        if(get_even_number(column_row)):
            for column in range(cols):
                triangle += " " * (half_space + 1) + "*" * stars + " " * half_space
        else:
            for column in range(cols + 1):
                if(not(column == 0)):
                    triangle += " " * (half_space + 1)

                if(column == 0 or column >= cols):
                    sub = row_of_triangle
                    if(column >= cols):
                        sub += 1
                    triangle += "*" * (stars - sub)
                else:
                    triangle += "*" * stars

                if(column < cols):
                    triangle += " " * half_space

        half_space      -= 1
        stars           += 2
        triangle        += "\n"

print(triangle)

Here is some sample output:

input: height: 6 cols: 6 rows: 4

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


texts:
Does someone know of a better way to get proper grammar in sentences than this method of mine? I don't want to continue with this for my entire huge program if there is a much more elegant way.

#include <iostream>
#include <string>

enum Gender {Male, Female};
enum Capitalized {Capital, NonCapital};

struct Person {
    std::string name;
    Gender gender;
    Person (const std::string& newName, Gender sex) : name (newName), gender (sex) {}
} *you;

std::string youHeShe (const Person* person, Capitalized capital = NonCapital) {
    return (capital == NonCapital) ?
        ( (person == you) ? "you" : (person->gender == Male) ? "he" : "she" ) :
        ( (person == you) ? "You" : (person->gender == Male) ? "He" : "She" );
}

std::string isAre (const Person* person) {
    return (person == you) ? "are" : "is";
}

std::string verb (const Person* person, const std::string& verb) {
    return (person == you) ? verb : verb + "s";
}

int main() {
    std::string yourName;
    std::cout << "What is your name? ";
    std::getline (std::cin, yourName);
    you = new Person (yourName, Male);
    Person *mary = new Person ("Mary", Female), *bob = new Person ("Bob", Male);
    Person* people[] = {you, mary, bob};
    for (const Person* x : people)
        std::cout << youHeShe(x, Capital) << " (" << x->name << ") " << isAre(x) <<
        " awesome because " << youHeShe(x) << " " << verb(x, "rock") << "!" << std::endl;
}

Output:

  What is your name? John Doe

  You (John Doe) are awesome because you rock!

  She (Mary) is awesome because she rocks!

  He (Bob) is awesome because he rocks!

In my program, there are sentences involving either the 3rd person or the 2nd person, so the grammar has to be correct based on which it is.

Of course, my method will involve many more such grammar functions, but I just need to know if there is a better way before I write those other functions (and special cases).


texts:
I am doing a join in the axios call.
since doing two different api calls.
for performance is this the good way.
or do I need to use async await and then do join.
providing code snippet below

export function getSearch(value) {
    console.log('-- getSearch value', value);
    return dispatch => {
        if (value.length) {
            if (typeof this._source !== 'undefined') {
                this._source.cancel('Operation canceled due to new request');
            }
            this._source = axios.CancelToken.source();
            return axios
                .get(
                    `http://localhost:787878/hold/search?mode=Smart&value=${value}`,
                    {
                        cancelToken: this._source.token,
                    }
                )
                .then(response => {

                    console.log('search response.data-->', response.data);
                    let values = response.data.map(filterSearch => {
                        if (filterSearch.playerIDs) {
                            console.log(
                                'search response.data playerIDs',
                                filterSearch.playerIDs[0]
                            );
                            return filterSearch.playerIDs[0].number + ',';
                        }

                    });
                    console.log(
                        'search response.data join--->',
                        values.join('')
                    );
                    axios
                        .get(
                            `http://localhost:787878/hold/animalworldCardList/?playerID=${values.join(
                                ''
                            )}&isHistory=false`,
                            //localhost:787878/hold/ce-affiliation/?animalPimsId=${animalPimsId}&isHistory=${isHistory}`,
                            {
                                cancelToken: this._source.token,
                            }
                        )
                        .then(responseplayerIDs => {
                            console.log(
                                'search response.data -->',
                                responseplayerIDs
                            );
                            dispatch({
                                type: ANIMAL_SEARCH_DATA,
                                payload: {
                                    animalSearch: response.data,
                                    playerIDs:
                                        responseplayerIDs.data.animalsInfo,
                                },
                            });
                            //  callBack(response);
                        })
                        .catch(error => {
                            if (axios.isCancel(error)) {
                                console.log(
                                    '-- Request canceled',
                                    error.message
                                );
                            } else {
                                console.log('-- Error', error.message);
                            }
                        });
                })
                .catch(error => {
                    if (axios.isCancel(error)) {
                        console.log('-- Request canceled', error.message);
                    } else {
                        console.log('-- Error', error.message);
                    }
                });
        } else {
            dispatch({
                type: ANIMAL_SEARCH_DATA,
                payload: [],
            });
        }
    };
}


texts:
I'm using Winforms C# .NET 3.5. I'm getting frames, and this is how I handle them:

    delegate void videoStream_NewFrameDelegate(object sender, NewFrameEventArgs eventArgs);
    public void videoStream_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        if (ready)
        {
            if (this.InvokeRequired)
            {
                videoStream_NewFrameDelegate del = new videoStream_NewFrameDelegate(videoStream_NewFrame);
                this.Invoke(del, new object[] {sender, eventArgs} );
            }
            else
            {
                Rectangle rc = ClientRectangle;
                Bitmap bmp = new Bitmap(rc.Width, rc.Height);
                Graphics g = Graphics.FromImage((Image)bmp);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                g.DrawImage((Bitmap)eventArgs.Frame, rc.X+10, rc.Y+10, rc.Width-20, rc.Height-20);

                g.Dispose();
                this.Image = (Image)bmp;
            }
        }
    }

Is there any way to optimize or improve performance?

I'm getting low performance when my image is 320x240 and I'm stretching it to 1280x1024, But the same image on 640x480 and stretching to 1280x1024 wont get much loss in performance.

I tried to use WPF and still same performance loss. That is weird because WPF is supposed to use DirectX and be fast in image processing.

Here is my WPF code:

    delegate void videoStream_NewFrameDelegate(object sender, NewFrameEventArgs eventArgs);
    public void videoStream_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        if (ready)
        {
            if (!this.Frame.Dispatcher.CheckAccess())
            {
                videoStream_NewFrameDelegate del = new videoStream_NewFrameDelegate(videoStream_NewFrame);
                this.Frame.Dispatcher.Invoke(del, new object[] { sender, eventArgs });
            }
            else
            {
                Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
                IntPtr hBitmap = bmp.GetHbitmap();
                BitmapSource img = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                bmp.Dispose();
                GC.Collect();

                this.Frame.Source = img;
            }
        }
    }


texts:
So the way I understand this code I wrote, it is thread safe, as long as the retrievers and depositors are thread safe. The only bad state I could see occurring is that a thread is using a retriever as a method local while another thread calls RefreshDependencies(), which would mean the thread with it as a method local would continue to use it even though it wasn't one of the current depositors/retrievers, but that one should be cleaned up when the method local using it exited as there would be no root anymore.

also open to any other notes on the code.

public static class DependencyContainer
{
    private const string DEPENDENCIES_LOCATION_APP_SETTINGS_KEY = "DependenciesLocation";

    private static object _lockDependenciesManagement;
    private static string _dependenciesLocation;

    public static IEnumerable<IEntryRetriever> Retrievers { get; private set; }
    public static IEnumerable<IEntryDepositor> Depositors { get; private set; }

    static DependencyContainer()
    {
        _lockDependenciesManagement = new object();
        string dependenciesLocation = ConfigurationManager.AppSettings[DEPENDENCIES_LOCATION_APP_SETTINGS_KEY] ?? typeof(DependencyContainer).Assembly.CodeBase.Replace(@"file:///", "");
        SetDependenciesLocation(dependenciesLocation);
        RefreshDependencies();
    }

    public static string GetDependenciesLocation()
    {
        lock (_lockDependenciesManagement)
        {
            return _dependenciesLocation;
        }
    }

    public static void SetDependenciesLocation(string newDependenciesLocation)
    {
        lock (_lockDependenciesManagement)
        {
            _dependenciesLocation = newDependenciesLocation;
        }
    }

    public static void RefreshDependencies()
    {
        lock (_lockDependenciesManagement)
        {
            // compose/load dependencies in here for writing and retrieving blog entries
        }
    }
}


texts: Convert first letter of every word to uppercase

texts:
I am learning swift and I came across this problem.
Converting each start letter to capitalized form if it's lowercase.
func upperCaseFirstCharacter(str:String){
    let myArr = str.components(separatedBy: " ")
    var finalStr :String=""
    for word in myArr {
        let myStr = word.replacingCharacters(in: ...str.startIndex, with: word.first?.uppercased() ?? "")
        finalStr.append(myStr)
        if myArr.last != word{
            finalStr.append(" ")
        }
    }
    print(finalStr)
}


texts: Compile time integer square root for large numbers

texts:
This computes the integer square root at compile time for any \$0 \le N \le L\$ where \$L\$ is the largest integral representation of template parameter T.

This was motivated by the fact that many of the algorithms I found were not able to handle large values of \$N\$. I also just wanted to practice template meta-programming.

Important: I cannot simply declare the runtime algorithm as a constexpr function because my compiler does not allow it.

The implementation is based on this runtime algorithm:

template <typename T>
T rt_square_root( T num )
{
    T bit{ static_cast<T>( 1 ) << ( sizeof( T ) * 8 - 2 ) };

    while ( bit > num )
        bit >>= 2;

    T res{ 0 };
    while ( bit )
    {
        T delta{ res + bit };
        if ( num >= delta )
        {
            num -= delta;
            res = ( res >> 1 ) + bit;
        }
        else
        {
            res >>= 1;
        }
        bit >>= 2;
    }
    return res;
}

Source

square_root.h

Template meta-programming based implementation of the algorithm:

#ifndef CR_SQUARE_ROOT_H
#define CR_SQUARE_ROOT_H

namespace ct
{
    template <typename T, typename U>
    bool constexpr greater( T a, U b )
    {
        return b < a;
    }

    template <typename T, T num, T bit, bool condition = true>
    class calc_shifted_bit
    {
    private:
        static T constexpr shifted_bit = bit >> 2;

    public:
        static T constexpr result = calc_shifted_bit<T, num,
            shifted_bit, ct::greater( shifted_bit, num )>::result;
    };

    template <typename T, T num, T bit>
    class calc_shifted_bit<T, num, bit, false>
    {
    public:
        static T constexpr result = bit << sizeof( T ) / 2;
    };

    template <typename T, T num, T res, T bit, typename = void>
    class calc_sqrt
    {
    private:
        static T constexpr delta = res + bit;
        static bool constexpr num_gt_delta = num >= delta;

    public:
        static T constexpr result = calc_sqrt
            <T,
            num_gt_delta ? num - delta : num,
            num_gt_delta ? ( res >> 1 ) + bit : ( res >> 1 ),
            ( bit >> 2 )
            >::result;
    };

    template <typename T, T num, T res, T bit>
    class calc_sqrt<T, num, res, bit, std::enable_if_t<( bit == 0 )>>
    {
    public:
        static T constexpr result = res;
    };

    template <typename T, T n>
    struct sqrt
    {
        static T constexpr result =
            calc_sqrt
            <T, n, 0,
                calc_shifted_bit
                <T, n,
                static_cast<T>( 1 ) << ( sizeof( T ) * 8 - sizeof( T ) / 2 )
                >::result
            >::result;
    };
}

main.cpp

Some tests, compilation time seems fast, but I'm not very experienced with template meta-programming costs:

#include <limits>

int main()
{
    using ULL = unsigned long long;
    using UL  = unsigned long;

    auto constexpr n_max64bit = std::numeric_limits<ULL>::max();
    auto constexpr n_max32bit = std::numeric_limits<UL>::max();

    static_assert(
        ct::sqrt<ULL, n_max64bit>::result == n_max32bit,
        "bad square root" );

    static_assert(
        ct::sqrt<ULL, n_max32bit * n_max32bit>::result - 2 == n_max64bit,
        "bad square root" );
}


texts:
What is the transpose of a matrix:
In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal; that is, it switches the row and column indices of the matrix A by producing another matrix, often denoted by Aᵀ.
Code
dimension = int(input())
matrix = []
transpose = []
for row in range(dimension):
    entry = list(map(int,input().split()))
    matrix.append(entry)
for i in range(dimension):
    for j in range(dimension):
        transpose.append(matrix[j][i])
m = 0
n = dimension

for x in range(dimension+1):

    row = transpose[m:n]
    list1 = [str(item) for item in row]
    string2 = " ".join(list1)
    print(string2)
    m = n
    n = n + dimension

My question
What all modifications I can do to this code to make it better furthermore efficient?