texts: A heap-allocated texture class for a console renderer

texts:
I am working on a console renderer and I want a heap-allocated dynamic texture class. Since I am quite new to C++, I just want to check the memory management, if I destroy all pointers correctly etc.

class Texture {
private :

char** pixels; // heap allocated
int width, height;

public :

Texture(int width, int height, const char* texture) {
    this->width = width;
    this->height = height;

    pixels = new char*[width];
    for (int x = 0; x < width; x++) {
        pixels[x] = new char[height];

        for (int y = 0; y < height; y++)
            pixels[x][y] = texture[y*width+x];

    }

}

Texture(int width, int height, char fill) {

    this->width = width;
    this->height = height;

    pixels = new char*[width];
    for (int x = 0; x < width; x++) {
        pixels[x] = new char[height];

        for (int y = 0; y < height; y++)
            pixels[x][y] = fill;

    }

}

~Texture() {
    for (int x = 0; x < width; x++)
        delete[] pixels[x];

    delete pixels;
}

Texture getSubTexture(int x, int y, int width, int height) {

    Texture newtex(width, height, '?');

    for (int xx = 0; xx < width; xx++)
        for (int yy = 0; yy < height; yy++) {
            newtex.setPixel(xx, yy, getPixel(x+xx, y+yy));
        }

    return newtex;

}

void setPixel(int x, int y, char c) {
    pixels[x][y] = c;
}

char getPixel(int x, int y) {
    return pixels[x][y];
}

int getWidth() { return width; }
int getHeight() { return height; }

};


texts:
The code takes srcPaths and actionType as parameters. The former is a string with tab-delimited file paths, while the latter is a string that may have values of "Lock", "Unlock", and "Toggle", which is chosen by the user.

#!/usr/bin/python

import os
import sys
import ntpath
import subprocess

srcPaths = sys.argv[1]
actionType = sys.argv[2]

srcPaths = srcPaths.split("\t")
srcPathsCount = len(srcPaths)

lockCount = unlockCount = 0

def fileIsLocked(srcPath):

    cmd1 = subprocess.Popen(["ls", "-ldO", srcPath], stdout=subprocess.PIPE)
    cmd2 = subprocess.Popen(["awk", "{ print $5 }"], stdin=cmd1.stdout, stdout=subprocess.PIPE)
    cmd1.stdout.close()

    if "uchg" in cmd2.communicate()[0]:
        return True
    else:
        return False

def setLock(flagStr, srcPath):

    global lockCount, unlockCount

    subprocess.call(["chflags", flagStr, srcPath])

    if flagStr == "uchg":
        lockCount += 1
    else:
        unlockCount += 1

for srcPath in srcPaths:

    if actionType == "Lock":

        if not fileIsLocked(srcPath):
            setLock("uchg", srcPath)

    elif actionType == "Unlock":

        if fileIsLocked(srcPath):
            setLock("nouchg", srcPath)

    else:

        if fileIsLocked(srcPath):
            setLock("nouchg", srcPath)
        else:
            setLock("uchg", srcPath)

sys.stdout.write("{}/{}/{}".format(lockCount, unlockCount, srcPathsCount))

The function fileIsLocked(srcPath) checks if the file is locked. It does this by using ls -ldO and awk to get the file flags. If it finds "uchg" there, then the function returns True, and vice versa. The function setLock(flagStr, srcPath) executes the shell script command to lock/unlock the file depending on the conditions, and keeps count of files that have been locked and unlocked.

Naturally, if the user wants to Lock the files, the file paths will be checked for unlockedness, and will proceed to lock those that are unlocked. If files are to be Unlocked, vice versa. If the user wants to Toggle, then if the files are locked, they are unlocked, and vice versa.

I'm not certain that the code is as concise as it needs to be. It seems to me like the code might be shortened or functions might be joined together. But I haven't been able to modify the code and still keep it working as intended.

What do you think could be done to improve the logic of the code?


texts: Counting pending bookings using a subselect

texts:
Can this query be improved? Is there a way to eliminate the duplicate function call?

-- a Special Group has many Items which have many Bookings
create function f_BookingsForSpecialGroup(@specialGroupId varchar(99))
returns table as
    return select * from v_Booking where ITEM_CODE in
        (select ITEM_CODE from v_Item i where i.SPECIAL_GROUP_ID = @specialGroupId);
go

create view v_SpecialGroup as
select (NON_BAD_BOOKINGS - PAID_BOOKINGS) as PENDING_BOOKINGS, * from
(
select
    (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_BAD=0) as NON_BAD_BOOKINGS,
    (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_PAID=1) as PAID_BOOKINGS,
    *
from SPECIAL_GROUP g
) g
go

The view v_SpecialGroup is never queried directly by the application; it is used to build other views which select individual columns as needed. (You can think of v_SpecialGroup as a "base view" which exists solely to augment the SPECIAL_GROUP table. I have profiled this strategy and it seems that if you don't select the more expensive columns you don't pay for them, but I could be wrong of course...)


texts: Slow import from Excel to datagrid in C# using Excel interop

texts:
I am a civil engineer who happens to love coding. I have written code which imports Excel data from a specific region in to specific columns of datagridview (where columns are already created using a designer). I wrote terrible code which does the following things:

Reads all the Excel sheet
Store values in list

Bypass and avoid blank/null cells in sheets
Delete empty cells
Add rows in datagridview
Populate them using loops

I did it somehow but it takes time and I am not satisfied even if it doesn't take time. I want to use interop Excel, which is the limation. Is there any way to optimize my code in a better way?

string ExcelFinalPath = tb_ExcelPathUCC.Text;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
progressBar1.Value = 2;
Workbook workbook = app.Workbooks.Open(ExcelFinalPath);
progressBar1.Value = 4;
Worksheet sheet = (Worksheet)workbook.Sheets[cmb_SheetUCC.Text]; // Sheet Access
progressBar1.Value = 10;
Microsoft.Office.Interop.Excel.Range Mycells = sheet.Cells; // Getting cells
Mycells = sheet.UsedRange; //Getting Used Cells
object CellValue = null;
object CellValue2 = null;

//Collecting all cell values
for (int i = 1; i < Mycells.Rows.Count; i++)
{

    //Avoid Null Exception due empty cell values
    if (Mycells.Item[i, 1].Value == null)
    {

    }
    else
    {
        //Adding All values to Column 1
        CellValue = Mycells.Item[i, 1].Value;
        // Adding Valuues to a List of Column 1
        UCCValue1.Add(CellValue.ToString());

    }
    //Avoid Null Exception due empty cell values
    if (Mycells.Item[i, 6].Value == null)
    {

    }
    else
    {
        //Adding All Values to Column 2
        CellValue2 = Mycells.Item[i, 6].Value;
        // Adding Values to List of Column 2
        UCCValue2.Add(CellValue2.ToString());
    }

}
progressBar2.Value = 20;
//Removing Empty Cells from Values in Cell for Column1
for (int i = 0; i < UCCValue1.Count; i++)
{

    if (UCCValue1[i] == "")
    {
        UCCValue1.Where(item => item != string.Empty).ToArray();
    }

}
progressBar2.Value = 30;
//Removing Empty Cells from Values in Cell for Column 2
for (int i = 0; i < UCCValue2.Count; i++)
{

    if (UCCValue2[i] == "")
    {
        UCCValue2.Where(item => item != string.Empty).ToArray();
    }

}

progressBar2.Value = 50;
//Adding rows in Datagridview
for (int i = 4; i < UCCValue1.Count - 1; i++)
{

    dataGridView2.Rows.Add();
}
progressBar2.Value = 60;
//Adding Values of Just Guages
for (int i = 4; i < UCCValue1.Count; i++)
{

    dataGridView2.Rows[i - 4].Cells[0].Value = UCCValue1[i];

}
progressBar2.Value = 70;
//Adding Values of Just Guages
for (int i = 3; i < UCCValue2.Count; i++)
{

    dataGridView2.Rows[i - 3].Cells[5].Value = UCCValue2[i];

}


texts: my code is messy and wasteful of lines, how do I make my code simple

texts:
can this script be made simpler? I'm just learning about javascript, so I don't really know which syntax to use.
My HTML I have several id consisting of "doc1, doc2, doc3, .." and there is another id "icon-cek1, icon-ceck2, icon-cek3". "icon-cek" is used to display the place of a checkmark icon when the upload is successful / according to the extension that has been specified and if the file fails / doesn't match the extension will display a crossmark.
 DOcument 1
<input type="file"id="doc1"/>
 Choose

 DOcument 2
<input type="file"id="doc2" />
 Choose

 DOcument 3
<input type="file"id="doc3"/>
 Choose

    $.fn.checkFileType = function (options) {
    var defaults = {
      allowedExtensions: [],
      success: function () {},
      error: function () {},
    };
    options = $.extend(defaults, options);

    return this.each(function () {
      $(this).on("change", function () {
        var value = $(this).val(),
          file = value.toLowerCase(),
          extension = file.substring(file.lastIndexOf(".") + 1);

        if ($.inArray(extension, options.allowedExtensions) == -1) {
          options.error();
          $(this).focus();
        } else {
          options.success();
        }
      });
    });
  };

  $("#doc1").checkFileType({
    allowedExtensions: ["pdf"],
    success: function () {
      document.getElementById("icon-cek1").className = "checkmark";
    },
    error: function () {
      document.getElementById('doc1').value='';
      document.getElementById("icon-cek1").className = "crossmark";
    },
  });

    $("#doc2").checkFileType({
    allowedExtensions: ["pdf"],
    success: function () {
      document.getElementById("icon-cek2").className = "checkmark";
    },
    error: function () {
      document.getElementById("doc2").value = "";
      document.getElementById("icon-cek2").className = "crossmark";
    },
  });

  $("#doc3").checkFileType({
    allowedExtensions: ["pdf"],
    success: function () {
      document.getElementById("icon-cek3").className = "checkmark";
    },
    error: function () {
    alert("Just PDF");
      document.getElementById("doc3").value = "";
      document.getElementById("icon-cek3").className = "crossmark";
    },
  });

or is there a simpler code to handle the case I have?


texts: Can this custom Test:Unit assert be replaced/refactored? Am I missing test cases?

texts:
I have a unit test that needs to compare two arrays but it shouldn't care about the order of the arrays. I didn't see anything in the Test:Unit docs that provided this so I wrote my own. I really don't want to use this code if I don't have to (want to avoid Not Invented Here syndrome).

If you can give me some feedback on the following points it would be a huge help, thanks!

Should I even use this? Is there a built-in Test:Unit assertion I can use?
I've refactored this as much as I can but any further improvements are encouraged and welcome.
I've included my tests for this custom assertion, can you see any cases that I may be missing?

Here is the custom assertion:

def assert_have_same_items(expected, actual, message = nil)
  full_message = build_message(message, "<?> was expected to contain the same collection of items as \n<?> but did not.\n", actual, expected)

  test = expected | actual

  assert_equal expected.size, actual.size, full_message
  assert_equal expected.size, test.size, full_message
end

And the tests:

test "assert_have_same_items with two arrays with same items in same order reports success" do
  assert_have_same_items [1,2,3], [1,2,3]
end

test "assert_have_same_items with two arrays with same items in different order reports success" do
  assert_have_same_items [1,2,3], [2,1,3]
end

test "assert_have_same_items with actual missing an item, reports failure" do
  assert_should_fail do
    assert_have_same_items [1,2,3], [2,1]
  end
end

test "assert_have_same_items with actual having more items, reports failure" do
  assert_should_fail do
    assert_have_same_items [1,2,3], [2,1,3,4,5,6]
  end
end

test "assert_have_same_items with actual having duplicates, reports failure" do
  assert_should_fail do
    assert_have_same_items [1,2,3], [2,1,3,2,1,3]
  end
end

test "assert_have_same_items with actual having duplicates and expected having same number of items, reports failure" do
  assert_should_fail do
    assert_have_same_items [1,2,3,4,5,6], [2,1,3,2,1,3]
  end
end

protected
def assert_should_fail
  begin
    yield if block_given?
    flunk "Expected failure but assertion reported success"
  rescue Test::Unit::AssertionFailedError
    assert true
  end
end


texts: Mixing Lens operations with "original" operations

texts:
Is it reasonable to mix Control.Lens operations with the ones provided by the "standard library"?

Consider the following fragment using qualified Data.Map as Map:

getUniqueIdent :: String -> State (Map.Map String Int) (Maybe String)
getUniqueIdent typeName = do indices <- StM.get
                             let identifiers = Map.lookup typeName typeNameMap
                             let uniqueIndex = Map.lookup typeName indices
                             StM.modify $ over (at typeName) (fmap succ)
                             let uniqueIdent = (^?) <$> identifiers <*>
                                                        (element <$> uniqueIndex)
                             return $ join uniqueIdent

For example, I do use both the Map.lookup and Lens.at and also the (^?) as a safe alternative for (!!).

Should I just stick to lenses "everywhere" (at least in spatially local code)?


texts: Marionette.js Mediator ('global' commands vs app controller)

texts:
I am currently migrating a large backbone application over to Marionette and am curious as to the opinions on what is a better design for mediating activity between modules.

I have an Application that have several Modules where an action in one module might cause activity to happen in other modules.

Since these all are coupled to the Application I could simply use the Wreqr interface where:

Module 1:

someActivity: ->
   App.vent.trigger("skyFalling")

Module 2:

initialize: ->
   App.vent.on("skyFalling", @closeOrSomething)

Module 3:

initialize: ->
   App.vent.on("skyFalling", @blinkRapidly)

Or would it be better to trigger an event in Module1 where the Application (or a controller tied to the App) listens and then calls the 'closeOrSomething' and the 'blinkRapidly' functions directly on the modules (since the App is aware of all the modules that it is loading).

Application:

skyFallingEventHandler: ->
   Module2.closeOrSomething()
   Module3.blinkRapidly()


texts:
At first, I had Database to contain std::list<Student> students, but because there are over 2000 students, searching by students should not be done in linear time.  However, searching for students can be by name or by student number.  To enable both searches in logarithmic time, I decided to give Database two maps that hold the same 2000+ students.  Inserting and removing a student will have to update both maps.  This doubles the time, but I figured that \$2*O(logN)\$ is still much better than \$O(N)\$.  If there are to be k different search criteria later on, then \$k*O(logN)\$ is still better than \$O(N)\$ up to, say, k = 20 or so.  Agree?

Space complexity is a different matter though.  Is the doubling of memory usage bad design here, for 2000+ students?  Tripling?  Quadrupling?

Is there a better solution altogether?

#include <iostream>
#include <string>
#include <memory>
#include <map>

class Student {
    std::string surname, firstName;
    long studentNumber;
public:
    std::string getSurname() const {return surname;}
    std::string getFirstName() const {return firstName;}
    std::string fullName() const {return firstName + ' ' + surname;}
    long getStudentNumber() const {return studentNumber;}
};

class Database {
    std::multimap<std::string, std::shared_ptr<Student>> mapByName;
    std::map<long, std::shared_ptr<Student>> mapByStudentNumber;
public:
    void insertStudent (const std::shared_ptr<Student>& p) {
        mapByName.emplace (getName(p), p);
        mapByStudentNumber.emplace (p->getStudentNumber(), p);
        // 2 insertions needed.
    }
    inline void removeStudentByStudentNumber();
    inline void removeStudentByName();
private:
    void remove (const std::shared_ptr<Student>& p) {
        mapByName.erase(getName(p));
        mapByStudentNumber.erase(p->getStudentNumber());
        // 2 removals needed.
    }
    std::string getName (const std::shared_ptr<Student>& p) const {return p->fullName();}
};

inline void Database::removeStudentByStudentNumber() {
    long studentNumber;
    std::cout << "Student number? ";
    std::cin >> studentNumber;
    const auto it = mapByStudentNumber.find(studentNumber);
    if (it == mapByStudentNumber.end()) {
        std::cout << "No student with that student number exists.\n\n";
        return;
    }
    remove(it->second);
}

inline void Database::removeStudentByName() {
    // Similar to above
}

int main() {}


texts: This divides the class of game objects into material and immaterial

texts:
The fact is that a material object must have a field that does not make sense to an immaterial object

Here is a class whose objects I want to divide into material and immaterial:

public class GameObject {
    protected boolean isHidden;
    protected Coordinate position;
    protected int pictureWidth, pictureHeight;
    public Object filling;

    protected GameObject(int pictureWidth, int pictureHeight, Coordinate position, boolean isHidden, Color filling){
        this.position = position;
        this.pictureWidth = pictureWidth;
        this.pictureHeight = pictureHeight;
        this.isHidden = isHidden;
        this.filling = filling;
    }

    protected GameObject(Coordinate position, boolean isHidden, BufferedImage filling){
        this.position = position;
        this.pictureWidth = filling.getWidth();
        this.pictureHeight = filling.getHeight();
        this.isHidden = isHidden;
        this.filling = filling;
    }

    protected GameObject(GameObject gameObject) throws IOException{
        this.position = new Coordinate(gameObject.getPosition());
        this.pictureWidth = gameObject.getPictureWidth();
        this.pictureHeight = gameObject.getPictureHeight();
        this.isHidden = gameObject.isHidden();
        this.filling = gameObject.getFilling(); // передается ссылка
    }

    private GameObject getGameObject() {
        return this;
    }
    public void paint(Graphics gr) throws IOException{
        if(filling instanceof BufferedImage) {
            gr.drawImage((Image) filling, position.getX(), position.getY(), null);
        }
        else if(filling instanceof Color) {
            gr.setColor((Color) filling);
            gr.fillRect(position.getX(), position.getY(), pictureWidth, pictureHeight);
        } else {
            System.err.println("programmer, you forgot to add a way to draw this object");
        }
    }
    Object getFilling() {
        return filling;
    }

    int getPictureWidth() {
        return pictureWidth;
    }
    int getPictureHeight() {
        return pictureHeight;
    }
    boolean isHidden() {
        return isHidden;
    }
    Coordinate getPosition() {
        return position;
    }
}

I suppose that you need to create 2 classes that inherit GameObject, and make the constructor of the GameObject class visible only for these two classes:

1) class MaterialGameObject:

 public class MaterialGameObject extends GameObject{
    final int materialHeight;

    public MaterialGameObject(int materialHeight, int pictureWidth, int pictureHeight, Coordinate position, boolean isHidden, Color filling){
        super(pictureWidth, pictureHeight, position, isHidden, filling);
        this.materialHeight = materialHeight;
    }

    public MaterialGameObject(int materialHeight, Coordinate position, boolean isHidden, BufferedImage filling){
        super(position, isHidden, filling);
        this.materialHeight = materialHeight;
    }

    public MaterialGameObject(MaterialGameObject materialGameObject) throws IOException{
        super(materialGameObject.getGameObject());
        this.materialHeight = materialGameObject.getMaterialHeight();
    }

    public int getMaterialHeight() {
        return materialHeight;
    }

}

class ImMaterialGameObject:

public class ImMaterialGameObject extends GameObject{

    public ImMaterialGameObject(int pictureWidth, int pictureHeight, int materialHeight, Coordinate position, boolean isHidden, Color filling){
        super(pictureWidth, pictureHeight, position, isHidden, filling);
    }

    public ImMaterialGameObject(Coordinate position, boolean isHidden, BufferedImage filling){
        super(position, isHidden, filling);
    }

    public ImMaterialGameObject(GameObject gameObject) throws IOException{
        super(gameObject);
    }

}

Do you know a better way to solve the problem?


texts:
I'm fairly new to object oriented programming here and am trying to get my head around the best way to go about creating Users and Validating them in the system.

My first attempt is below and my main questions apart from does it all seem correct is in regards passing a validator class to the save function and pros/cons to this.

A lot of the functionality has been stripped back to enable you to read it a bit easier, including removing any getters and setters but please assume they are there:

User Model

class User implements Validateable {

    protected $name;
    protected $email;
    protected $validator;

    // getters and setters for name, email, validator here

    public function save( Validator $validator ) {

        $this->validator = $validator;
        if( $this->validator->validate( $this ) )
            return true;

        return false;

    }

    public function getRules() {

        return [
            'name' => new NameValidator( $this->name ),
            'email' => new EmailValidator( $this->email )
            ];

    }

}

Abstract Validator

abstract class ValidatorAbstract {

    protected $errors;

    public function getErrors() {
        return $this->errors;
    }

}

Name Validator

class NameValidator extends ValidatorAbstract {

    protected $name;
    protected $errors;

    public function __construct( $name ) {
        $this->name = $name;
    }

    public function validate() {

        if( empty( $this->name ) )
            $this->errors[] = 'Invalid Name';

        if( $this->errors )
            return false;

        return true;

    }

}

Email Validator

class EmailValidator extends ValidatorAbstract {

    protected $email;
    protected $errors;

    public function __construct( $email ) {
        $this->email = $email;
    }

    public function validate() {

        if( !filter_var( $this->email, FILTER_VALIDATE_EMAIL ) ) :
            $this->errors[] = 'Invalid Email';
        endif;

        if( $this->errors )
            return false;

        return true;

    }

}

User Validator

class UserValidater implements Validator {

    protected $data;
    protected $rules;
    protected $errors;

    public function validate( Validateable $obj ) {

        $this->rules = $obj->getRules();

        foreach( $this->rules as $rule ) :

            if( !$rule->validate() )
                $this->errors[] = $rule->getErrors();

        endforeach;

        if( $this->errors )
            return false;

        return true;

    }

    public function getErrors() {

        return $this->errors;

    }

}

Validator Interface

interface Validator {

    public function validate( Validateable $data );
    public function getErrors();

}

Validateable Interface

interface Validateable {

    public function getRules();

}

And finally some example code using all of the above:

$user = new User;
$user->setName( 'Peter' );
$user->setEmail( 'peter@email.com' );

if( $user->save( new UserValidater ) ) :
    // do some stuff
else :
    $errors = $user->getValidator()->getErrors();
    // do some stuff with the errors
endif;


texts:
Was playing around tonight and thought this problem was interesting enough to post here.

  Given a 2D array of digits, try to find the location of a given 2D
  pattern of digits.

  Input Format

  The first line contains an integer, T, which is the number of test
  cases.

  T test cases follow, each having a structure as described below:
  The first line contains two space-separated integers, R and C,
  indicating the number of rows and columns in the grid G,
  respectively.

  This is followed by R lines, each with a string of C digits, which
  represent the grid G.

  The following line contains two space-separated integers, r and c,
  indicating the number of rows and columns in the pattern grid P.

  This is followed by r lines, each with a string of c digits, which
  represent the pattern P.

  Output Format

  Display YES or NO, depending on whether (or not) you find that the
  larger grid G contains the rectangular pattern P. The evaluation
  will be case sensitive.

Taken from HackerRank challenge "The Grid Search." Much more detailed explanation there. I borrowed this writeup from a similar question.

Any feedback appreciated - this passes all the tests. I did not really try to optimize beyond passing the test cases and making it fairly simple in order to do that.

Specifically am curious about:

Ability to streamline the nested if statements and loops
All the match/find stuff seems clunky
I don't like all the break statements and my cont boolean, is there a better way to early exit this?

Anything else would be appreciated too. the initial chunk is all system input stuff which I did not change but pasted here in case anyone wants to run it on HackerRank.

#!/bin/python3

import sys

t = int(input().strip())
for a0 in range(t):
    R,C = input().strip().split(' ')
    R,C = [int(R),int(C)]
    G = []
    G_i = 0
    for G_i in range(R):
       G_t = str(input().strip())
       G.append(G_t)
    r,c = input().strip().split(' ')
    r,c = [int(r),int(c)]
    P = []
    P_i = 0
    for P_i in range(r):
       P_t = str(input().strip())
       P.append(P_t)

    # everything above here is auto generated by the site for parsing input

    result = 'NO'

    # search each potential matching row
    for y in range(R - r + 1):
        match_index = -1
        cont = True

        # search vertically for every time that the first row in the search matrix matches
        while cont:
            match_index = G[y].find(P[0], match_index + 1)
            if match_index < 0:
                cont = False

            # check to ensure row in outcome matches input
            for y_p in range(r):
                G_sub = str(G[y + y_p][match_index : match_index + c])
                P_sub = str(P[y_p])
                if G_sub != P_sub:
                    break

                if y_p == r - 1:
                    result = 'YES'
                    break

    print(result)


texts:
The algorithm should be checking if the block fits perfectly when it falls.

The block is always the same shape:

 .##....

   ..##....

Keep in mind I wrote this in 1 hour - all the time we had for the task. How can I make it more optimized?

#include <stdio.h>
#include <stdlib.h>
int check(char *k, int r, int s){
    int i, j, flag = 0;
    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (k[i * s + j] == '*' && k[(i + 1*2) * s + j + 1] == '.'){
                flag = 1;
            }
        }
    }
    return flag;
}
void toLadders(char *k, int r, int s){
    int i, j;
    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (k[i * s + j] == '*')
             k[i * s + j] = '#';
        }
    }

}
int main()
{
    int i, j, r, s;
    int flag = 0;

    do{
        scanf("%d %d", &r, &s);
    }while(r < 1 || s > 15);

    char matrix[r][s];

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            scanf(" %c", &matrix[i][j]);
        }
    }

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            if (matrix[i][j - 1] == '.' && matrix[i][j] == '#' && matrix[i][j + 2] == '.'
                && matrix[i + 1][j] == '.' && matrix[i + 1][j + 1] == '#' && matrix[i + 1][j + 2] == '#' && matrix[i + 1][j + 3] == '.'){

                matrix[i][j] = '*';
                matrix[i][j + 1] = '*';
                matrix[i + 1][j + 1] = '*';
                matrix[i + 1][j + 2] = '*';

            }
        }
    }

    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (matrix[i][j] == '*' && matrix[i + 1][j] == '.' && matrix[i + 2][j + 1] == '.' && matrix[i + 2][j + 2] == '.'){
                    matrix[i + 1][j] = '*';
                    matrix[i][j] = '.';
                    matrix[i + 1][j + 1] = '*';
                    matrix[i][j + 1] = '.';
                    matrix[i + 2][j + 1] = '*';
                    matrix[i + 1][j + 1] = '*';
                    matrix[i + 2][ j + 2] = '*';
                    matrix[i + 1][j + 2] = '.';
            }
        }
    }

    flag = check(&matrix[0][0], r, s);

    toLadders(&matrix[0][0], r, s);

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            printf("%c", matrix[i][j]);
        }
        printf("\n");
    }

    if (flag)
        printf("\nNot perfect!");
    else
        printf("\nPerfect!");

    return 0;
}


texts: Reduce time taken for VBA loop when copying multiple sets of input values, performing Excel formula calculations and recording results

texts:
My VBA code currently loops for 5,000 iterations and takes about 25 minutes to collect the output data in the Output excel sheet. Is there a way to reduce the time taken for instance by improving the copying and pasting of values, collecting the output data in some kind of array etc.? Given that I will be looping it for up to 10,000 iterations when I obtain more data

Note: The calculations are excel formulas within the Calcs excel sheet, as this is a cash flow schedule with irregular cash flows and discount rates, hence I am unable to automate the cash flow calculations via VBA.

Sub x()

Dim r As Long
Dim lastrow As Long

Application.ScreenUpdating = False
Application.CutCopyMode = False

With Worksheets("MCInput")
lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
MsgBox lastrow - 1 & " Trials"
End With

With Worksheets("Calcs")
    For r = 0 To (lastrow - 2)
        .Range("CASHINPUT").Value = Worksheets("MCInput").Range("TCASHRTN").Offset(r).Value
        .Range("EQINPUT").Value = Worksheets("MCInput").Range("TEQRTN").Offset(r).Value
        .Range("FIINPUT").Value = Worksheets("MCInput").Range("TFIRTN").Offset(r).Value
        .Range("Results").Calculate
        .Range("Results").Copy
        Worksheets("Output").Range("A1").Offset(1 + r, 1).PasteSpecial xlPasteValues
    Next r
End With

Application.ScreenUpdating = True
Application.CutCopyMode = True

End Sub


texts: Diagonal Movement Code for Python Chess Engine

texts:
I'm currently in the process of building my own Chess game engine and could really use some suggestions on how to make this segment of code for calculating diagonal moves more efficient. (This is obviously only for diagonals going Up-Right.)

As of now I'm using "Try-Except" to iterate by 1, and then my return statement filters out any off-board values. However this seems like a very bulky way of doing things.

import argparse, json

chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)]

chess_map_from_alpha_to_index = {
    "a" : 0,
    "b" : 1,
    "c" : 2,
    "d" : 3,
    "e" : 4,
    "f" : 5,
    "g" : 6,
    "h" : 7
}

chess_map_from_index_to_alpha = {
    0: "a",
    1: "b",
    2: "c",
    3: "d",
    4: "e",
    5: "f",
    6: "g",
    7: "h"
}

def getBishopMoves(pos, chessBoard):
    column, row = list(pos.strip().lower())
    row = int(row) - 1
    column = chess_map_from_alpha_to_index[column]
    i,j = row, column
    solutionMoves = []

#Up-Right Diagonal
    try:
        temp = chessBoard[i + 1][j + 1]
        solutionMoves.append([i + 1, j + 1])
    except:
        pass
    try:
        temp = chessBoard[i + 2][j + 2]
        solutionMoves.append([i + 2, j + 2])
    except:
        pass
    try:
        temp = chessBoard[i + 3][j + 3]
        solutionMoves.append([i + 3, j + 3])
    except:
        pass
    try:
        temp = chessBoard[i + 4][j + 4]
        solutionMoves.append([i + 4, j + 4])
    except:
        pass
    try:
        temp = chessBoard[i + 5][j + 5]
        solutionMoves.append([i + 5, j + 5])
    except:
        pass
    try:
        temp = chessBoard[i + 6][j + 6]
        solutionMoves.append([i + 6, j + 6])
    except:
        pass
    try:
        temp = chessBoard[i + 7][j + 7]
        solutionMoves.append([i + 7, j + 7])
    except:
        pass
    try:
        temp = chessBoard[i + 7][j + 7]
        solutionMoves.append([i + 7, j + 7])
    except:
        pass

    temp = [i for i in solutionMoves if i[0] >=0 and i[1] >=0]
    solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp]
    solutionMoves.sort()
    return solutionMoves


texts: Python worker pattern for multithreading

texts:
I'm building a script where I pass in a text file of hostnames, and a text file of commands and each command will then be run against each host.

To prevent this getting out of hand I'm also passing in a maximum thread count and trying to manage a maximum number of workers at any one time.

The code I would like feedback on is as follows:

main.py

#!/usr/bin/python3
import sys
from lib.core.input import InputParser, InputHelper
from lib.core.output import OutputHelper, Level
from lib.core.threader import Pool

def build_queue(arguments, output):
    queue = list()
    for target in InputHelper.process_targets(arguments):
        for command in InputHelper.process_commands(arguments):
            output.terminal(Level.VERBOSE, target, command, "Added to Queue")
            queue.append(command)
    return queue

def main():
    parser = InputParser()
    arguments = parser.parse(sys.argv[1:])

    output = OutputHelper(arguments)

    output.print_banner()

    pool = Pool(arguments.threads, build_queue(arguments, output), arguments.timeout, output)
    pool.run()

if __name__ == "__main__":
    main()

threader.py

import threading
import os

class Worker(object):
    def __init__(self, pool):
        self.pool = pool

    def __call__(self, task, output, timeout):
        self.run_task(task)
        self.pool.workers.append(self)

    @staticmethod
    def run_task(task):
        os.system(task)

class Pool(object):
    def __init__(self, max_workers, queue, timeout, output):
        self.queue = queue
        self.workers = [Worker(self) for w in range(max_workers)]
        self.timeout = timeout
        self.output = output

    def run(self):
        while True:

            # make sure resources are available
            if not self.workers:
                continue

            # check if the queue is empty
            if not self.queue:
                break

            # get a worker
            worker = self.workers.pop(0)

            # get task from queue
            task = self.queue.pop(0)

            # run
            thread = threading.Thread(target=worker, args=(task, self.output, self.timeout))
            thread.start()

Essentially, I don't know what I don't know. There's likely some basic gaps in my knowledge here, and I'd love feedback and examples that help me  to bridge those gaps. Any and all help is very welcome, and very appreciated.


texts:
This is a simple form validation script.

I'd like to:

improve the jQuery validation
simplify the jQuery code

Questions:

Should I be exporting pure JS validation to avoid potential conflicts with other libraries that users might have installed?
Is it worth the effort or should I stick with my jQuery code?
Is there a way to reduce the chances for conflict with the jQuery code without having to reworking it to JS?


texts: Python, Iterate through a list sending batches of 100 records at a time to an API, then appending results to another list

texts:
I have a list of 9000 dictionaries and I am sending them to an API in batches of 100 (limit of the API). The API returns the list of 100 dictionaries just expanded with more key/value pairs. So both lists look something like this:

[
{Key1:Val1, Key2:Val2},
{Key1:Val3, Key2:Val4},
...
]

and returns:

[
{Key1:Val1, Key2:Val2,Key3:Val1, Key4:Val4},
{Key1:Val3, Key2:Val4,Key3:Val1, Key4:Val4},
...
]

Now, I have to create a list that has all 9000 returned dictionaries in them, because the original input receives a batch of 9000 so it needs to output them all at once as well. I have accomplished this with the following code:

dict_list = [This is the list with 9000 dicts]
batch_list = []
return_list = []

for i in dictlist:
    batch_list.append(i)
    if len(batch_list)  == 100:
        api_batch = API_CALL_FUNCTION(batch_list)
        for j in api_batch:
            return_list.append(j)
        batch_list.clear()
    else:
        continue
if batch_list:
    api_batch = API_CALL_FUNCTION(batch_list)
    for k in api_batch:
        return_list.append(k)

This code does what I want it to, but I really don't like the nested for loop and I'm sure there's probably a more efficient way to do this. Any suggestions?


texts:
I am learning to code in the Assembly language for the x86 architecture. I currently know of a few registers and certain arithmetic operations like add, sub, inc, dec, mov and to check for conditionality using certain jump statements. I am using some "ready-baked" code for input and output. The input - call_hex reads hex from the input and stores it in the eax register and the output - print_eax just prints whatever is in the eax. I am no programmer per se, my end goal is to understand enough assembly to start picking up other things like exploit development. The code below is an exercise to print prime numbers. I know the code I have below could look downright ugly. But if you were rating the code, how much would I get on a scale of 1 to 10, 10 being the highest.

; A prime number is an integer that is divisible only by 1 and by itself.
; A program that takes a number n as input, and prints back to the console all the    primes that are larger than 1 but not larger than n.

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    ; Your program begins here:

    ; Division Operations -
    ;eax <- edx:eax/arg
    ;edx <- edx:eax % arg

    call    read_hex

lb2:
    dec     eax
    jz      exit
    jmp     prime_check

prime_check:

    ; The check for whether 2 is a prime is done separately here
    mov     ecx, eax
    sub     ecx, 2
    jz      is_prime

    mov     ecx, eax        ; eax will be overwritten, hence need to store it someplace else to recover it
    mov     edx, 0          ; initialing the edx:eax registers
    mov     ebx, 2

lb1:
    dec     eax             ; The 3 lines of code are there cause I need a way to exit the program, when eax inside this block is 1.
    jz      exit            ; This seems to be an easy fix. Although downright inelegant
    inc     eax
    div     ebx
    mov     eax, ecx
    sub     edx, 1
    jc      lb2             ; The case where number isnt prime
    mov     eax, ecx        ; re-initialing the edx:eax registers
    mov     edx, 0          ; re-initialing the edx:eax registers
    inc     ebx
    sub     ecx, ebx
    jz      is_prime
    mov     ecx, eax
    jmp     lb1

is_prime:
    call    print_eax
    jmp     lb2

exit:
    ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'


texts:
Using Bootstrap 3 and PHP, I create my navigation bars in the following way:

<?php
$page_url = $_SERVER['REQUEST_URI'];
$active1 = (strpos($page_url, "one.php") !== false ? " class=\"active\"" : "");
$active2 = (strpos($page_url, "two.php") !== false ? " class=\"active\"" : "");
$active3 = (strpos($page_url, "three.php") !== false ? " class=\"active\"" : "");
$active4 = (strpos($page_url, "four.php") !== false ? " class=\"active\"" : "");
?>

      <button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>
      Company Name

        <li<?=$active1?>>Link One

        <li<?=$active2?>>Link Two

        <li<?=$active3?>>Link Three

        <li<?=$active4?>>Link Four

Then, depending on which page you're on, a link within the navigation has class="active" applied to it. However, this feels like a very messy way of building this functionality to the <navbar>. Lots of empty variables at one time, and a lot of almost identical code for each navigation element.

How best can I improve on this code?


texts:
I do programing with core php & i don't want to like use any cms or mvc framework.   if any handy ideas then welcome it.

index.php file

<?php
/** INCLUDE BSIC CONFIGURATION FILE */
strip_php_extension();

/** GET REQUEST NAME */
$request_uri = trim(filter_input(INPUT_GET, 'uri_req'),'/');

/** CALL REQUESTED PAGE */
_PageCall($request_uri);

?>

function.php file

<?php
/**
 * strip_php_extension()
 *
 * check website url in .php file name is exist
 *
 * @param null
 * @return redirect the page with removing .php extension from the url bar
 */
function strip_php_extension()
{
  $uri = filter_input(INPUT_SERVER,'REQUEST_URI');
  $ext = substr(strrchr($uri, '.'), 1);
  if ($ext == 'php')
  {
    $url = substr($uri, 0, strrpos($uri, '.'));
    redirect($url);
  }
}

/**
 * _PageCall()
 *
 * check in web current web request
 *
 * @param null,filename
 * @return return file if or return 404 file
 */
function _PageCall($file_name=null){
    $pagedir = ROOT.DIRECTORY_SEPARATOR.PAGEDIR;

    /* Every File Request Must Be in HTML */
    if(".html"===substr($file_name, -5)):
        $file_name = trim($file_name,'.html');
        if(file_exists($pagedir.$file_name.'.php')):
            require_once $pagedir.$file_name.'.php';
        else:
            redirect('404.html');
        endif;
    else:
        if(NULL==$file_name||$file_name=='index.html'):
            require_once $pagedir.'index.php';
        elseif($file_name=='a'):
            require_once $pagedir.'ajax.php';
        else:
            redirect(SITEURL.'404.html');
        endif;
    endif;
} ?>


texts:
In the past, I have used AsyncTasks to perform network requests for my Android app. I recently switched to RxJava to be able to cancel the requests when the user exits an activity. I have created a system to easily create new async tasks via RxJava which all cancel when a user exits an activity. I have attached some basic code that I hope somebody could give me some pointers on.

public class BaseActivity extends AppCompatActivity{

    ArrayList<OnDestroyListener> listeners = new ArrayList<>();

    @Override
    protected void onDestroy() {

        for(OnDestroyListener listener : listeners){
            listener.onDestroy();
        }

        super.onDestroy();
    }

    public void addOnDestroyListener(OnDestroyListener listener){
        listeners.add(listener);
    }

    public interface OnDestroyListener{
        void onDestroy();
    }
}

public class Tools{
    public static <E> void observe(Callable<E> callable, SingleSubscriber<E> subscriber, BaseActivity activity){
        final Subscription sub = Single.fromCallable(callable)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        if(activity == null){
            return;
        }

        activity.addOnDestroyListener(new BaseActivity.OnDestroyListener() {
            @Override
            public void onDestroy() {
                sub.unsubscribe();
            }
        });
    }
}

public class Endpoint{
    public void makeGetRequestAsync(final String url, final SingleSubscriber<String> subscriber, BaseActivity activity){
        Tools.observe(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return makeGetRequestSync(url);
            }
        }, subscriber, activity);
    }
}

public class SampleActivity extends BaseActivity{

    Endpoint endpoint = new Endpoint();

    void onButtonClick(View v){
        endpoint.makeGetRequestAsync("https://someurl.com", new SingleSubscriber<String>() {
                    @Override
                    public void onSuccess(String result) {
                        //Request success
                    }

                    @Override
                    public void onError(Throwable error) {
                        //Request failure
                    }
                }, this);
    }
}

I know that I do not have a real coding problem, since this method has been working very well so far, but I just want to know if anything about this process is inherently wrong, as I am using it throughout my app.


texts: Watch a directory and insert new entries into database

texts:
This program's main function is to:

Watch a directory.
If there are new files, insert those as entries into the database.
Delete the files from the directory.

My below code runs well, but I want to optimize it and I think it needs better error handling.

import os
import time
import mysql.connector
import MySQLdb
import pooop

file_path = 'C:\\path\\to\\watch\\'

#send files to database
def insert_csv(file,filename):
    try:
        cnx = mysql.connector.connect(user='user',
                                    password ='pass',host='192.168.1.1',
                                  database='test')
        cursor = cnx.cursor()
        thedata = open(file, 'rb').read()
        sql = "INSERT INTO testing(file_backup,file_name) VALUES (%s,%s)"
        cursor.execute(sql,(thedata,filename))
        cnx.commit()

   except MySQLdb.OperationalError, e:
      print e
   except MySQLdb.ProgrammingError, e:
      print e
   finally:
      cursor.close()

def walk():
    try:
        for dirpath, dirnames, files in os.walk(file_path):
            for i in files:
                file = dirpath+i
                try:
                    insert_csv(file,i)
                except Exception, e:
                    print e
                finally:
                    os.remove(file)
                print 'File successfully removed\n'+"-"*80
    except Exception, e:
         print e

#main loop that watches the directory
if __name__ == "__main__":
    print "Application starts running\n"+"-"*80
    while True:
        walk()

The application will run on Windows XP. I'm using Python 2.7.


texts: Loading Active Directory users by username and by SID

texts:
I have many different methods like ones below, but is there way I could improve them and remove duplicate code ?

    public static ADUser Load(string userName)
    {
        using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
        using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, IdentityType.SamAccountName, userName))
        {
            if (user != null)
            {
                return Utilities.LoadUser(user);
            }
        }

        return null;
    }

    public static ADUser LoadBySid(string sid)
    {
        using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
        using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, IdentityType.Sid, sid))
        {
            if (user != null)
            {
                return Utilities.LoadUser(user);
            }
        }

        return null;
    }


texts:
I've written some code to group a list of items into arbitrarily sized buckets. If the items are all the same and the and the count is a multiple of the bucket size a single bucket is returned, if the items are different then they are grouped into  buckets of a given size.

For example, with a bucket size of 3:

1,2         => [1,2]
1,2,3,4,5   => [1,2,3][4,5]
1,1,1,1,1,1 => [1,1,1,1,1,1]
1,1,1,1,1   => [1,1,1][1,1]

To achieve this I've written the following .Net extension method:

public static IEnumerable<IList<T>> GroupBySize<T>(this IEnumerable<T> source, int groupSize, Func<T, T, bool> comparer)
{
    var result = new List<List<T>>();

    if (source.IsNullOrEmpty())
        return result;

    List<T> currentGroup = null;

    for (var i = groupSize; i <= source.Count(); i += groupSize)
    {
        var possibleGroup = source.Slice(i - groupSize, groupSize);
        if (possibleGroup.All(x => comparer(x, possibleGroup.First())))
        {
            if (currentGroup == null)
            {
                currentGroup = new List<T>();
                result.Add(currentGroup);
            }

            currentGroup.AddRange(possibleGroup);
        }
        else
        {
            currentGroup = new List<T>();
            currentGroup.AddRange(possibleGroup);
            result.Add(currentGroup);
            currentGroup = null;
        }
    }

    var remainingItems = source.Count() % groupSize;
    if (remainingItems > 0)
    {
        result.Add(source.Slice(source.Count() - remainingItems, remainingItems).ToList());
    }

    return result;
}

public static IEnumerable<T> Slice<T>(this IEnumerable<T> source, int start, int count)
{
    return source.Skip(start).Take(count);
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
    // Taken from :http://haacked.com/archive/2010/06/10/checking-for-empty-enumerations.aspx
    return items == null || !items.Any();
}

The code passes the tests I've written, but it all (including the method name) feels a bit clunky.

How could this be improved?


texts:
This is a question from the book "Cracking the Coding Interview".

  Design an algorithm and write code to remove the duplicate characters
  in a string without using any additional buffer NOTE: One or two
  additional variables are fine An extra copy of the array is not

This is not the efficient code, but I want to preserve the order of characters after deleting duplicate characters.

#include <iostream>
#include <string>
#include <cctype> //std::toupper, std::tolower

void removeDuplicates(std::string& str)
{
    int flag = 0;
    int len = str.length();
    for (int i = 0; i < len - 1; ++i)
    {
        for (int j = i + 1; j < len - 1; ++j)
        {
            if (str[i] == std::toupper(str[j])
                || str[i] == std::tolower(str[j]))
            {
                str.erase(str.begin() + j);
                flag = 1;
            }
        }
    }
    if (flag == 0)
    {
        std::cout << "There are no duplicate characters\n";
    }
    else
    {
        std::cout << "There are duplicate characters\n";
    }
}

int main()
{
    std::string str;
    std::cout << "Enter String\n";
    std::getline(std::cin, str);
    removeDuplicates(str);
    std::cout << "New String\n";
    std::cout << str << '\n';
}

Help me optimize this code.


texts:
Imagine a UTF-8 decoder that takes a list of bytes and returns human-readable code points like:

> (utf-8->human-readable-code-points '(32 32 195 160 160))
("u+0020" "u+0020" "u+00E0" ("Error: trailing byte without preceding start byte" 160))

This list builder functionality is meant for that function:

;; a list builder will allow us to build a list
;; by successively adding to the end without retracing
;; the list each time. And without having a stack of
;; cons calls to unwind. Will allow constructing a list
;; in order in a tail call fashion
;; (list-builder 'add! item) -- returns list so far
;; (list-builder 'list) -- returns list so far
(define (make-list-builder)
  (let [(list-under-construction '())
        (last-cons-cell '())]
    (lambda (dispatch . parameters)
      (case dispatch
        [(add!) (if (null? list-under-construction)
                   (begin
                     (set! list-under-construction (list (car parameters)))
                     (set! last-cons-cell list-under-construction))
                   (let ((new-cons-cell (list (car parameters))))
                     (set-cdr! last-cons-cell new-cons-cell)
                     (set! last-cons-cell new-cons-cell)))
         list-under-construction]
        [(list) list-under-construction]
        [else (error "unmatched dispatch" dispatch)]))))

Sample use:

> (define lb (make-list-builder))
> (lb 'list)
()
> (lb 'add! "here's an atom")
("here's an atom")
> (lb 'add! '(here's a list))
("here's an atom" (here 's a list))

Questions for review:

Is there a standard scheme function or way of doing this that I missed? The problem I am trying to ultimately solve can't be solved by a map because a map produces a list of the same size as the input, and map does not guarantee the order that elements of a Lisp or processed. Googling and searching Stack Overflow for scheme list builder or scheme list accumulater did not return useful results.
Is make-list-builder expressed in idiomatic Scheme?
How would you improve make-list-builder, or what would you do differently?


texts: "Longest Substring Without Repeating Characters" in Python

texts:
I was trying to solve this problem from Leetcode:

  Given a string, find the length of the longest substring without
  repeating characters.

  Examples:

  Given "abcabcbb", the answer is "abc", which the length is 3.

  Given "bbbbb", the answer is "b", with the length of 1.

  Given "pwwkew", the answer is "wke", with the length of 3. Note that
  the answer must be a substring, "pwke" is a subsequence and not a
  substring.

I would like to get some code review for the following solution:

class Solution:
    def lengthOfLongestSubstring(self, s):
      dict = {}
      start, end, curr_length, max_length = 0, 0, 0, 0
      while ( end < len(s)):
        char = s[end]

        if char not in dict:
            curr_length += 1
        else:
            start = max(dict[char], start)

        max_length = max(max_length, end - start + 1)
        dict[char] = end + 1
        end += 1
      return max_length

"""
    my logic is that
    * 1) Initialize a hashmap/dictionary/object that will map characters to their index.
    * 2) Initialize `start`, `end`, and `answer`
    * 3) Loop through the string while `end` is less than `length` of string
    * 4) Check if character at `end` is in hashmap
      * a) If so, repeating character exists between `start` and `end`. Set `start` to be the `max_length` between the value of character in the hashmap, and `start`

"""

And it passes all of the leetcode tests.


texts: Searching for a binary tree for a vehicle with a given name

texts:
I'm searching my binary search tree of Vehicle objects and I'm just wondering whether there would be much point, if it's best practice to search to see if a node has a left/right child first like so:

return n.hasLeft() ? find(name, n.left()) : null;

Or just go with the following, since it will return null if it doesn't exist anyway:

return find(name, n.left());

Here's the code for the whole method:

protected Vehicle find(String name, Node n)
{
    if (n == null) return null;

    int order = name.compareTo(n.getVehicleName());

    if (order == 0)
        return n.getVehicle();
    else if (order < 0)
        return n.hasLeft() ? find(name, n.left()) : null;
    else
        return n.hasRight() ? find(name, n.right()) : null;
}

Would checking first be more efficient since it saves an extra recursive call being made?


texts: Depth-first traversal implementation in Java (by recursion)

texts:
I implemented a recursive depth-first traversal, with all three traversal modes in this function. Is this the most succinct way to write the code?

/**
 * Node
 */
public class Node {
  private int value;
  Node left;
  Node right;

  public Node(int value) {
    this.setValue(value);
    left = null;
    right = null;
  }

  /**
   * @return the value
   */
  public int getValue() {
    return value;
  }

  /**
   * @param value the value to set
   */
  public void setValue(int value) {
    this.value = value;
  }

/**
 * Depth-First Traversal (Recursion)
 * @param root root of node-tree to be traversed
 */
public void dftRecursion(Node root) {
    if (root == null) {
      return;
    }
    switch (tMode) { // traversal mode
    case IN_ORDER:
      dftRecursion(root.left);
      System.out.print(root.getValue() + " ");
      dftRecursion(root.right);
      break;
    case PRE_ORDER:
      System.out.print(root.getValue() + " ");
      dftRecursion(root.left);
      dftRecursion(root.right);
      break;
    case POST_ORDER:
      dftRecursion(root.left);
      dftRecursion(root.right);
      System.out.print(root.getValue() + " ");
      break;
    default:
      throw new IllegalArgumentException("Mode value:" + tMode);
    }
  }


texts: Review implementation for Partial Ordering of Vectors

texts:
Partial ordering may be useful in some scientific contexts. This is quick prototype in Python, which I believe works correctly.

Do you notice any flaws? Can you provide a counter-example of wrong results? Additional test cases will be also rewarded with +1.

#!/usr/bin/env python3

import unittest as ut

def leq (L1, L2):
    assert len(L1) == len(L2)
    l = g = 0
    for v1, v2 in zip(L1, L2):
        if v1 < v2:
            l += 1
        elif v1 > v2:
            g += 1
    return l >= 0 and g == 0

class Test (ut.TestCase):

    def test1 (self):
        V1 = [1, 2, 3]
        V2 = [1, 2, 2]
        self.assertFalse(leq(V1, V2))
        self.assertTrue(leq(V2, V1))

    def test2 (self):
        V1 = [1, 2, 3]
        V2 = [2, 2, 3]
        self.assertTrue(leq(V1, V2))
        self.assertFalse(leq(V2, V1))

    def test3 (self):
        V1 = [1, 2, 3]
        self.assertTrue(leq(V1, V1))

    def test4 (self):
        V1 = [1, 2, 3]
        V2 = [3, 2, 1]
        self.assertFalse(leq(V1, V2))
        self.assertFalse(leq(V2, V1))

Edit: redefining the leq function (thanks to Cary for the comment)

leq = lambda L1, L2: sum(v1 > v2 for v1, v2 in zip(L1, L2)) == 0

Proved to be working with the same unit test.

Same result, but using short-circuit logic and avoiding to scan both lists:

leq = lambda L1, L2: not any (v1 > v2 for v1, v2 in zip(L1, L2))

As suggested in comment, equivalent version, more natural:

leq = lambda L1, L2: all(v1 > v2 for v1, v2 in zip(L1, L2))


texts: Lua OOP and classically-styled prototypal inheritance

texts:
I want to do some object-oriented programming in Lua, and I decided on something like this:

local B = {} -- in real life there is other stuff in B

B.Object = {

  constructor = function() end,

  extend = function(this, that, meta)
    if not that then that = {} end
    if not meta then meta = {} end
    meta.__index = this
    setmetatable(that, meta)
    return that
  end,

  isa = function(this, that)
    for meta in function() return getmetatable(this) end do
      if this == that then return true end
      this = meta.__index
    end
    return this == that
  end,

  new = function(this, ...)
    local that = this:extend()
    that:constructor(...)
    return that
  end,

}

All objects (including "class-like objects") extend B.Object, directly or indirectly. For example:

-- Request handler base

B.RequestHandler = B.Object:extend()

-- override these
function B.RequestHandler:accept() error "not implemented" end
function B.RequestHandler:process() error "not implemented" end

-- URL-encoded POST handler

B.PostHandler_URLEncoded = B.RequestHandler:extend()

function B.PostHandler_URLEncoded:accept()
  return self.method == "POST" and
         self.content_type == "application/x-www-form-urlencoded"
end

function B.PostHandler_URLEncoded:process()
  -- some code
end

-- Multipart POST handler

B.PostHandler_Multipart = B.RequestHandler:extend()
-- etc.

It might be used something like this:

B.request_handlers = {
  GetHandler:new(),
  URLEncodedPostHandler:new(),
  MultipartPostHandler:new(),
}

B.handle_request = function()
  for k, v in ipairs(B.request_handlers) do
    if v:accept() then
      return v:process()
    end
  end
  error "request not handled"
end

As far as I know, this is pretty much the normal way to handle inheritance in Lua. Did I miss anything? Is there anything that needs improvement?


texts:
I wrote a simple chatbot in Python a while ago, and I'd like to know how it could be improved. Here's the code:

import random
import pickle

class Bot:
    current = ""
    botText = "BOT> "

    def __init__(self, data, saveFile):
        self.data = data
        self.saveFile = saveFile

    def say(self, text):
        print(self.botText + text)
        self.current = text

    def addResponse(self, userInput, response):
        if userInput in self.data:
            self.data[userInput].extend(response)

        else:
            self.data[userInput] = []
            self.data[userInput].extend(response)

    def evaluate(self, text):
        if text in self.data:
            self.say(random.choice(self.data[text]))

        elif text == "/SAVE":
            f = open(self.saveFile, 'wb')
            pickle.dump(self.data, f)
            f.close()

        elif text == "/LOAD":
            f = open(self.saveFile, 'rb')
            self.data = pickle.load(f)
            f.close()

        elif text == "/DATA":
            print(self.data)

        else:
            if not self.current in self.data:
                self.data[self.current] = []

            self.data[self.current].append(text)
            self.say(text)

Here's how the bot works. I'm sorry if you don't understand, I'm not the best at explaining things.

User enters input.
If the input is in the database, choose a random response associated with the input and output it.
If it isn't, add the input to the database and echo the input.
User enters input again.
The input is associated with the bot's output.

Inputs and outputs can be added manually using the addResponse() function.

There are also a few commands, which are quite self-explanatory, but I'll list them here anyways.

/SAVE pickles the file and saves it in the saveFile.
/LOAD unpickles the saveFile and loads it.
/DATA displays the database.


texts:
I have the following code implemented in C# for NHibernate:

public class UnitOfWork : IDisposable {
        private ISession _session;
        private ITransaction _transaction;

        public UnitOfWork() {
            _session = NHibernateHelper.OpenSession();
            _transaction = _session.BeginTransaction();
        }

        public IProductRepository Products {
            get {
                return new ProductRepository(_session);
            }
        }

        public IPersonRepository People {
            get {
                return new PersonRepository(_session);
            }
        }

        public void SaveChanges() {

            if (_transaction == null) {
                throw new InvalidOperationException("Unit Of Work already saved");
            }

            _transaction.Commit();
        }

        public void Dispose() {
            //throw new NotImplementedException();
            CloseSession();
            CloseTransaction();
        }

        #region Transaction and Session Management Methods

        public void BeginTransaction() {
            _transaction = _session.BeginTransaction();
        }

        public void CommitTransaction() {
            // _transaction will be replaced with a new transaction            // by NHibernate, but we will close to keep a consistent state.
            _transaction.Commit();

            CloseTransaction();
        }

        public void RollbackTransaction() {
            // _session must be closed and disposed after a transaction            // rollback to keep a consistent state.
            _transaction.Rollback();

            CloseTransaction();
            CloseSession();
        }

        private void CloseTransaction() {
            _transaction.Dispose();
            _transaction = null;
        }

        private void CloseSession() {
            _session.Close();
            _session.Dispose();
            _session = null;
        }

        #endregion
    }

As I have doubts whether this implementation is right or not, I felt the need for other people to correct my work and suggest for further improvements. I feel like somehow the Repository should not reside inside Unit of Work.

Then again, I need the Unit of Work pattern to inject the same session in all repositories as it also felt I'm not utilizing its use if I use 1 session inside each repository methods.

This is how I consume my Unit of Work inside service layer:

public class PersonService {

        private UnitOfWork uow = new UnitOfWork();

        public IEnumerable<Person> GetAllPerson() {
            var uo = new UnitOfWork();

            return uo.People.GetAll();
        }

        /// <summary>
        /// 1st implementation of scoping unit of work session lifetime
        /// </summary>
        /// <returns></returns>
        public void AddPerson() {
            var uo = new UnitOfWork();

            uo.People.Add(new Person() {
                Fname = "Sonny",
                Mname = "Ramirez",
                Lname = "Recio"
            });
            uo.SaveChanges();

        }

        /// <summary>
        /// 2nd implementation of scoping unit of work session lifetime
        /// </summary>
        /// <returns></returns>
        public PersonInfoViewModel GetInfo() {
            using (UnitOfWork uo = new UnitOfWork()) {
                //todo: implementation
            }

            return uow.People.GetInfo();
        }

    }

Feel free to correct my code as you see fit. I think I already saw a different implementation of UoW which it doesn't have any repository residing in it, but I don't like how it was implemented.


texts:
Hi I am pretty new to programming and I would like you to give me some feedback about my code, how does it look, what could be better. Thank you.

A = []
B = []
C = []
PegDict = {'A': A,'B': B,'C': C} #Would it be better to use a two dimensional array?

discs = int(input("Podaj ilość dysków: "))
for i in range(discs, 0, -1):
    A.append(i)

movesNeeded = pow(2, discs) - 1
StartingPeg = A.copy()

def move(fromm, to):
    to.append(fromm[-1])
    fromm.pop()

Moves the smallest disc one peg to the left. This part could be done better i think.

def moveLeft():
    if A and A[-1] == 1:
        move(A, C)
        return
    if B and B[-1] == 1:
        move(B, A)
        return
    if C and C[-1] == 1:
        move(C, B)
        return

Moves the smallest disc one peg to the right

def moveRight():
    if A and A[-1] == 1:
        move(A, B)
        return
    if B and B[-1] == 1:
        move(B, C)
        return
    if C and C[-1] == 1:
        move(C, A)
        return

Returns key of a peg that is the only valid move target for a cartain peg

def PossibleMove(Peg):
    if Peg:
        if Peg[-1] != 1:
            for i in PegDict:
                x = PegDict[i]
                if not x:
                    return i
                elif Peg[-1] < x[-1]:
                    return i

Main part

moves = 0
while not C == StartingPeg:
    if discs%2 == 0:
        moveRight()
        moves += 1
    else:
        moveLeft()
        moves += 1

    print(A)
    print(B)
    print(C)
    print()

    for key in PegDict:
        if PossibleMove(PegDict[key]) != None:
            fromPeg = PegDict[key]
            onePossibleMove = PossibleMove(PegDict[key])

    if fromPeg:
        moves += 1
        move(fromPeg, PegDict[onePossibleMove])
        print(A)
        print(B)
        print(C)
        print()

print()
print('Moves: '+ str(moves))
print('Minimal number of moves: '+ str(movesNeeded))


texts:
I want to convert db columns such as is_deleted or product_code which consist of xx_xx to java-style names: isDeleted or productCode. I wonder if there is a way to improve my following code, using regex or such things.

def getJavaName(column):
   words = column.split('_')
   first = words[0]
   return first + ''.join((w.capitalize() for w in words[1:]))


texts:
This is my implementation of an AStar-like algorithm for maze solving.
A quick summary of the problem I am trying to solve with my algorithm might be:

A simple binary maze is given to you to solve, you may only go in the standard cardinal directions: north, east, west and south. There is a twist, however: You may also break only one wall. Create a function solution(maze) which determines the minimal number of steps to reach the end defined at point (width-1, height-1) from the start point (0, 0).

class AStar:
    def __init__(self, maze):
        self.queue = []
        self.visited = set()
        self.maze = maze
        self.end = len(self.maze)-1, len(self.maze[0])-1

    def forward(self):
        self.queue.append((0, 0, False, 0, 0, None))

        while self.queue:
            self.queue = sorted(self.queue, key=lambda x: x[-3]+x[-4])  #Might be suboptimal to sort every time...
            node = self.queue.pop(0)

            if node[0:2] == self.end:
                return node
            self.visited.add(node[0:2])

            new_nodes = self.rulebook(node)
            self.queue.extend(new_nodes)

    def rulebook(self, node):
        x, y, broken, cost, heuristic, _ = node
        new_nodes = []

        #------RULES & ACTIONS-----#
        for direction in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
            x_dir, y_dir = direction
            x_pdir = x + x_dir
            y_pdir = y + y_dir
            distance = self.distance((x_pdir, y_pdir), self.end)
            if (x_pdir, y_pdir) not in self.visited:
                if (x_pdir,y_pdir) not in self.visited:
                    if (x_pdir < len(self.maze) and y_pdir < len(self.maze[0])):
                        if (x_pdir >= 0 and y_pdir >= 0):
                            if self.maze[x_pdir][y_pdir] == 1:
                                if not broken:
                                    new_nodes.append((x_pdir, y_pdir, True, cost+1, \
                                        distance, node))
                            elif self.maze[x_pdir][y_pdir] == 0:
                                new_nodes.append((x_pdir, y_pdir, False, cost+1, \
                                    distance, node))
        return new_nodes
    def distance(self, node, end):
        #Chose the Taxicab Metric as it is more of a fit for the problem,
        #as you cannot go diagonally in the problem statement.
        x = node[0]
        y = node[1]
        end_x = end[0]
        end_y = end[1]
        return abs(x - end_x) + abs(y - end_y)
    def backward(self, node):
        steps = 0
        while node != None:
            steps += 1
            node = node[-1]
        return steps

def solution(maze):
    astar = AStar(maze)
    end_node = astar.forward()
    steps = astar.backward(end_node)
    return steps


texts: Guidance on grouping equal sets of numbers, so each group has a similar average

texts:
Goal: I am trying to build teams of 5 people. Each person has an integer elo (rank). My goal is to make all the teams as equal/fair as possible, by having the average elo of each team be as close as possible to one another.

Approach: My initial thought was to go through the list of elos and take the highest elo player and pair it with the lowest elo player. I did this twice (4 people on each team), sorting the array of teams after each loop by the teams median elo. On the final loop, I took the last set of elos (5th teammate) and put the highest players with the lowest team averages.

After my 3rd loop I noticed the biggest jump in the elo difference between the lowest team and highest team.

Question: I am wondering if my 3rd loop's logic is the main problem, or if this whole approach in general is bad. I have tried searching for algorithms about this like the "partition problem", but am having little success implementing it into my functions.

Demo: https://jsfiddle.net/aanders50/8m7m9tdw/3/

Omitted visual code that is in the JSFiddle above

var elos = ['big array of integers'];
var teams = [];     //store teams
var teamCount = 0;  //number of total teams
var teamSize = 5;   //number of players on each team

function myFunction() {
 teamCount = elos.length / teamSize;
 teams.length = 0;
 var i = 0;

 //order default list of elos
 elos.sort();

 //add 1 high and 1 low elo to each team
 for (i = 0; i < teamCount; i++) {
   teams[i] = new Array();
   teams[i][0] = elos.splice(0,1);
   teams[i][1] = elos.splice(elos.length-1,1);
 }

 //first sort by median elo
 sortTeams();
 $("#dif1").html(getMedian(teams[teams.length - 1]) - getMedian(teams[0]));

 //add another high and another low elo to each team
 for (i = teamCount-1; i > -1; i--) {
   teams[i][2] = elos.splice(0,1);
   teams[i][3] = elos.splice(elos.length-1,1);
 }

 //second sort by median elo
 sortTeams();
 $("#dif2").html(getMedian(teams[teams.length - 1]) - getMedian(teams[0]));

 //add highest remaining elo to lowest median elo team
 for (i = 0; i < teamCount; i++) {
   teams[i][4] = elos.splice(elos.length-1,1);
 }

 //3rd and final sort by median elo
 sortTeams();
 $("#dif3").html(getMedian(teams[teams.length - 1]) - getMedian(teams[0]));

 //display results
 printTeams();
}

//sort each team by average elo
function sortTeams() {
 teams.sort(function (a, b) {
  a = getMedian(a);
  b = getMedian(b);

  if (a > b) {
    return 1;
  }
  if (a < b) {
    return -1;
  }
  return 0;
  });
}

//get average elo of each team
function getMedian(numberArray) {
   var sum = numberArray.reduce(function(a,b) {
     return Number(a) + Number(b);
   });
   return (sum / teamSize);
}


texts: Determining if there is a route between two nodes in a directed graph

texts:
This algorithm should return a boolean value, telling if there is a path between two nodes in a given directed graph.

public enum State{
    White, Grey;
}

public class Node {
    State state = State.White;
    List<Node> neighbors = new ArrayList<Node>();
    //Assumption: Every node already knows about its direct adjacents
    public List<Node>getAdjacent(){ return neighbors;}
}

public static boolean isThereAPath(Node src, Node dst){
    //Assumption: Nodes are initialized with State.White
    if(src.state == State.White){
        src.state = State.Grey; //Means visiting this node right now
        for(Node node : src.getAdjacent()){
            if(node == dst){
                return true; //Hit - path found!
            }
            if(isThereAPath(node, dst))return true;

        }
    }
    return false; //NO path found
}

What do you think about the concept of it? What are the advantages of of an iterative solution?


texts: zip_longest without fillvalue in typescript

texts:
I would like to create a function like zip_lognest in python and if the array size is uneven, I do not want to filled any value. following is my code and example

const aFixture = [
  { name: 'name_a', value: 'value_a'},
  { name: 'name_b', value: 'value_b'},
  { name: 'name_c', value: 'value_c'},
  { name: 'name_d', value: 'value_d'},
];
const bFixture = [
  { name: 'name_1', value: 'value_1'},
  { name: 'name_2', value: 'value_2'},
];
const cFixture = [
  { name: 'name_x', value: 'value_x'},
  { name: 'name_y', value: 'value_y'},
  { name: 'name_z', value: 'value_z'},
];
export function zipLongest(...arrays: Array<any>) {
  const length = Math.max(...arrays.map((arr) => arr.length));
  const tempArray = Array.from({length}, (_, index) =>
    arrays.map((array) => (array.length - 1 >= index ? array[index] : undefined))
  )
  return tempArray.map((array) => array.filter((x: any) => x !== undefined))
}

const myarray =
  zipLongest(
    aFixture,
    bFixture,
    cFixture,
  )
console.log(myarray);
//[ [ { name: 'name_a', value: 'value_a' },
//    { name: 'name_1', value: 'value_1' },
//    { name: 'name_x', value: 'value_x' } ],
//  [ { name: 'name_b', value: 'value_b' },
//    { name: 'name_2', value: 'value_2' },
//    { name: 'name_y', value: 'value_y' } ],
//  [ { name: 'name_c', value: 'value_c' },
//    { name: 'name_z', value: 'value_z' } ],
//  [ { name: 'name_d', value: 'value_d' }, ]
//]


texts: Factory for object init and configuration

texts:
I want to extract the creation of different objects in a factory class for the reason of reusability. The problem is that within the current code the objects are configured also for the specific problem. Now I want to reuse only the creation of the objects within another code place.

 if (FieldConfiguration.FIELD_TYPE.TEXTFIELD == type)
            {
                TextField textField = new TextField(caption);
                textField.setNullRepresentation("");
                bind(textField, propertyId);
                field = textField;
                if (field.getValue() == null && isNestedProperty)
                {
                    ObjectProperty property = new ObjectProperty("", String.class);
                    textField.setPropertyDataSource(property);
                }
            }
            else if (FieldConfiguration.FIELD_TYPE.SEARCHFIELD == type)
            {
                SearchBox searchField = new SearchBox(caption);
                bind(searchField, propertyId);
                field = searchField;
            }
            else if (FieldConfiguration.FIELD_TYPE.DATEFIELD == type)
            {
                DateField dateField = new DateField();
                dateField.setCaption(caption);
                dateField.setDateFormat(UilibI18N.dateFormat.getText());
                dateField.setResolution(Resolution.DAY);
                bind(dateField, propertyId);

I want to reuse only the creation of the objects at another code place too, can anybody give me a hint what's the right way to extract the creation logic?


texts:
I'd like to know your opinions on this minimal type-checking decorator  (with @ annotations) to make type checking of a method while debugging like :

def typecheck(*tuples, **kwtuples):
    def decorator(func):
        def function_wrapper(*args, **kwargs):

            #print('tuples : ' , tuples)
            #print('kwtuples : ' , kwtuples)
            #print('args : ' , args)
            #print('kwargs : ' , kwargs)

            for index, tup in enumerate(tuples):
                arg = args[index]
                if not isinstance(arg, tup):
                    raise ValueError('in ' + str(func.__name__) + ' : wrong argument on position ,' + str(index) + ' :'  + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )

            for key, tup in kwtuples.items():
                arg = kwargs[key]
                if not isinstance(args[index], tup):
                    raise ValueError('in ' + str(func.__name__) + ' : wrong argument ' + str(key) + ' :'  + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )

        #print("arguments: ", *args, **kwargs)
            func(*args, **kwargs)
        return function_wrapper
    return decorator

@typecheck(str,(str, float))
def foo2(x,y):
    print("Hi, foo has been called with ",str(x) ,y)

foo2('2',3.4)

The benefit of it is :

Custom and detailed description about the wrong argument
Later, you can extend this for custom validation like some item is in some range or structural inspection of an argument.
Easy to write, apply and delete after testing (so it won't consume cpu time)


texts: Calculating a time in a time zone from multiple dates in SQL

texts:
I'm trying to calculate what time a certain time in a time zone is today, so I can schedule something to happen at that time in that time zone.

I've got a table with what I have termed the Nominal Time, which is stored as a datetimeoffset with an arbitrary date, as the only parts I care about is the time and the time zone offset. So, the Nominal Time column has values along the lines of:

2014-07-01 10:00:00.0000000 +02:00
2014-07-01 10:00:00.0000000 -05:00
2014-07-01 10:00:00.0000000 -07:00
2014-07-01 10:00:00.0000000 +01:00

(In this case 10am is my time I want to schedule this events). From this, I want to get that time today, so these would become:

2014-07-02 10:00:00.0000000 +02:00
2014-07-02 10:00:00.0000000 -05:00
2014-07-02 10:00:00.0000000 -07:00
2014-07-02 10:00:00.0000000 +01:00

when run at the date of this writing (2014-07-02). I currently have SQL that does this, but I don't really like it:

With    NominalTimes as (select Id, NominalTime, SYSDATETIMEOFFSET() Now
                        from FaxQueue where status=0),
        CalcTimes as (select Id, NominalTime, Now, DATEPART(year,Now) NomYear,
                        DATEPART(month,Now) NomMonth,DATEPART(day,Now) NomDay,
                        DATEPART(hour,NominalTime) NomHour,DATEPART(minute,NominalTime) NomMinute,
                        DATEPART(tzoffset,NominalTime) NomOffset from NominalTimes)
select Id, NominalTime, Now,
    DATETIMEOFFSETFROMPARTS(Nomyear,NomMonth,NomDay,NomHour,NomMinute,0,0,NomOffset/60,NomOffset%60,0)
    from CalcTimes

(Excuse the excessive CTEs; I'm trying to build this up bit by bit.) The end goal of this is to have a query that returns a list of rows where the nominal time happens within the next, say, hour (actual window size isn't important).

I will also note that from the function of the program, I do not need to worry about a time straddling a daylight saving time transition (the program is meant to run before DST happens in a time zone, and deliver a notification).

Is there a better way of doing these date calculations in SQL, or is this really about as good as it's going to get?


texts: Displaying RSS feeds from Google Feed API as HTML list

texts:
What it does is:

Reads from a RSS feed using Google Feed API
Shows the list in an unordered list

How good/bad is the code snippet?

$(document).ready(function(){
var FeedManager = {
        config : {
            feedContainer : $('#feedContainer'),
            feedUrl : 'http://rss.bdnews24.com/rss/english/home/rss.xml',
            feedLimit : 10
        },
        init: function(){
            var feed = new google.feeds.Feed(FeedManager.config.feedUrl);
            feed.setNumEntries(FeedManager.config.feedLimit) ;
            feed.load(function(result) {
                if (!result.error) {
                    FeedManager.$feedContainer = FeedManager.config.feedContainer;
                    for (var i = 0; i < result.feed.entries.length; i++) {
                        var entry = result.feed.entries[i];
                        $('<li/>').append(
                            $('<a>'+entry.title+'</a>').attr(
                                {
                                    'title': entry.title,
                                    'href': entry.link
                                }
                            ).bind('click',FeedManager.showStory)
                        ).appendTo(FeedManager.$feedContainer);
                    }
                }
                else{
                        FeedManager.handleError(result.error.message);
                }
            });
        },
        showStory: function(){
              var href = event.currentTarget.href;
              FeedManager.showURL(href);
              event.preventDefault();
        },
        showURL: function(url){
             if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
                return;
            }
            chrome.tabs.create({
                url: url
            });
        },
        handleError: function(errorText){
            $('<li/>')
                .css("color","red")
                .append("Error:"+errorText)
                .appendTo(FeedManager.config.feedContainer);
        }
    };

    FeedManager.init();
});

At the 2nd stage, I wanted to add custom accordion feature and news snippet:

processFeedResult: function(result) {
    if (result.error) {
        FeedManager.handleError(result.error.message);
        return;
    }
    FeedManager.$feedContainer = FeedManager.config.feedContainer;
    $.each(result.feed.entries, function() {
        $('<li/>').append(
            $('<a>', {  // this should not be an anchor tag,right? TBD
                title: 'Published at: '+this.publishedDate,
                text: this.title
            })
        ).append($('<div>', {
            text: this.contentSnippet,
            css : {'display':'none',
                'padding-top':'2px'}
            }).append(
                $('<a>', {
                    text: '[more..]',
                    href: this.link,
                    click: FeedManager.showStory
                }))
        )
        .bind('click',FeedManager.showSnippet)
        .appendTo(FeedManager.$feedContainer);
    });
},
showSnippet: function() {
    var $obj = $(event.currentTarget),
    $snippetDiv = $obj.find('div').slideDown('normal');

    if(FeedManager.$lastOpenedDiv === undefined){
        FeedManager.$lastOpenedDiv = $snippetDiv ;
    }
    else{
        FeedManager.$lastOpenedDiv.slideUp('normal');
        FeedManager.$lastOpenedDiv = $snippetDiv ;
    }
    }
};

I feel that I have put some tightly coupled code in my processFeedResult such as text and CSS.  I also wanted to know if my showSnippet function good enough or not.  However, it works, and I know that there are 3rd party good accordion available, but I wanted to learn it.

So far I've kept the anchor tag to show the news title and I used anchor title as a tooltip that shows the time.  Maybe there is a good alternate, like span or paragraph?


texts:
When checking a python dict for a key, which is the better way here:
(I can't figure how to use dict.get() to make this cleaner)

if 'y' in self.axes:
    ax = self.axes['y'].ax
    coord1[ax] = x0
    coord2[ax] = (y1) - height[ax]
    coord3[ax] = x0 + width[ax]
    coord4[ax] = y1

or:

try:
    ax = self.axes['y'].ax
except KeyError:
    pass
else:
        coord1[ax] = x0
        coord2[ax] = (y1) - height[ax]
        coord3[ax] = x0 + width[ax]
        coord4[ax] = y1

The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.


texts:
I'm learning Rust by learning the Rust programming language book. I'm now implementing the solution for the third challenge.

  Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, "Add Sally to Engineering" or "Add Amir to Sales." Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

I decided to do a simple UI to enter commands, but the implementation is very naive overall.

Rust is my first systems language. My background is in Ruby and Javascript.

use std::collections::HashMap;
use std::io::{self, Write};
use std::str::SplitWhitespace;

fn main() {
    println!("Welcome to the department interface. Please run a command:");
    help();

    let mut departments: HashMap<String, Vec<String>> = HashMap::new();

    loop {
        print_promt();
        let command = get_command();
        let mut command_iter = command.split_whitespace();

        match command_iter.next() {
            Some("add") => match process_add(&mut command_iter) {
                Ok((employee, department)) => {
                    let mut employees = departments.entry(department).or_insert(Vec::new());
                    employees.push(employee);
                }
                Err(err) => println!("Error: {}", err),
            },
            Some("help") => help(),
            Some("list") => println!("{:#?}", &departments),
            Some("exit") => break,
            Some(_) => println!("{}: Command unknown. Try `help`", command),
            None => panic!("We shouldn't be here"),
        }
    }
}

fn help() {
    println!("help: show this help.");
    println!("exit: exits this program.");
    println!("show: shows the deparment structure.");
    println!("add: adds an employee to a department");
    println!("     - usage: `add <employee name> to <department_name>`");
}

fn print_promt() {
    print!("> ");
    io::stdout().flush().ok().expect("Couldn't flush stdout!");
}

// I think this can be made better returning an Enum/Struct with a parsed command.
fn get_command() -> String {
    let mut command = String::new();
    io::stdin()
        .read_line(&mut command)
        .expect("Couldn't read command!");
    command
}

// The compiler told me to add the lifetime, but I don't understand why (I haven't reached that
// part of the book yet.)
// FIXME `SplitWhitespace` is too specific.
fn process_add<'a>(command: &mut SplitWhitespace) -> Result<(String, String), &'a str> {
    let mut employee = String::new();
    let mut department = String::new();

    // For a command "add Ronald Reagan to Old Presidents"
    // - Consume the iterator onto `employee` until you find "to""
    // - Consume the rest of the iterator onto `department`
    // Using two loops feels naive though. I don't like the duplication inside them.
    //
    // Maybe `String` can be extended and I could add a `push_str_with_separator` method that does
    // the extra check.
    //
    //      employee.push_str_with_separator(word);
    //
    while let Some(word) = command.next() {
        if word == "to" {
            break;
        }

        if employee.len() > 0 {
            employee.push_str(" ");
        }
        employee.push_str(word)
    }

    for word in command {
        if department.len() > 0 {
            department.push_str(" ");
        }
        department.push_str(word);
    }

    if employee.len() > 0 && department.len() > 0 {
        Ok((employee, department))
    } else {
        Err("Could not parse command. Try `add <employee name> to <department name>")
    }
}


texts: C++ operator overloading for rationalNumber

texts:
I have created a rationalnumber class and used operator overloading function of C++.

My questions are:

Have I implemented the class and < operator correctly?
Objects of class can now inserted in map and set. Is that part done correctly?

#include <bits/stdc++.h>
using namespace std;

class RationalNumber {
    int num;
    int den;
    bool negative;
    int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
public:
    RationalNumber() {
        num = den = 1;
        negative = 0;
    }
    RationalNumber(int a, int b) {
        if ((a < 0) ^ (b < 0))
            negative = 1;
        else
            negative = 0;
        num = abs(a);
        den = abs(b);
        int h = gcd(a, b);
        num /= h;
        den /= h;
    }
    RationalNumber operator+(const RationalNumber &r) {
        RationalNumber added;
        added = RationalNumber(num * r.den + r.num * den, den * r.den);
        return added;
    }
    bool operator<(const RationalNumber &r) const {
        return num * r.den < r.num * den;
    }

    void toString() {
        cout << num << "/" << den << endl;
    }
};
int main(int argc, char **argv) {
    RationalNumber r1(3, 5);
    RationalNumber r2(1, 3);
    RationalNumber r3 = r1 + r2;
    RationalNumber r4(9, 13);
    vector<RationalNumber> v;
    map<RationalNumber, string> S;
    map<RationalNumber, string>::iterator it;
    S[r1] = "1";
    S.insert(S.begin(), pair<RationalNumber, string>(r2, "2"));
    S.insert(S.begin(), pair<RationalNumber, string>(r2, "2"));
    S.insert(S.begin(), pair<RationalNumber, string>(r3, "3"));
    S.insert(S.begin(), pair<RationalNumber, string>(r4, "4"));
    for (it = S.begin(); it != S.end(); ++it) {
        RationalNumber r = it->first;
        r.toString();
        cout << it->second << endl;
    }
    return 0;
}


texts:
I'm a student working as a research assistant and wrote this script to automate density functional theory HPC tasks with SLURM. When a calculation is complete the script checks the contents of a log file for the total force, and if it's above the desired threshold it generates a new input file, file.in.new, with relaxed atomic positions from the log which is passed to another script in the automation process. Please point out any issues with formatting, syntax, etc, and if there's anything I could do to simplify things.
Example of use: python generate.py file.log file.in
from sys import argv

def arg_parse(argv):
    try:
        log_file=argv[1]
        input_file=argv[2]
        override=False
    except IndexError as e:
        raise SystemExit

    if len(argv)==4 and argv[3].strip("-")=='o':
        override=True

    scan_and_write(log_file, input_file, override)
#---------------------------------------------------------------------
def scan_and_write(log_file, input_file, override):
    with open(log_file, 'r+') as log:
        total_force=[float(line.split()[3]) for line in log if line.rfind('Total force =') != -1][-1]
        tolerance(total_force, override, input_file)
        log.seek(0)
        total_cycles=sum([1 for line in log if line.rfind('ATOMIC_POSITIONS (crystal)') != -1])
        log.seek(0)
        index=[int(line.split("=")[1]) for line in log if ("number of atoms/cell" in line)][0]
        log.seek(0)
        for line in log:
            if line.rfind('ATOMIC_POSITIONS (crystal)') != -1:
                atomic_positions=[log.readline().split() for i in range(index)]

    new_input=open(input_file.replace('.in', '.in.new'), "w+")
    fmt = '{:2}      {:12.9f}  {:12.9f}  {:12.9f}\n'
    with open(input_file, 'r+') as old_input:
        for line in old_input:
            if len(line.split()) != 4 and not line[0].isnumeric():
                new_input.write(line)
            if ('ATOMIC_POSITIONS') in line:
                for position in atomic_positions:
                    new_input.write(fmt.format(position[0],*[float(xred) for xred in position[1:4]]))

#---------------------------------------------------------------------
def tolerance(force, override, file_name):
    print('A total force of {} was achieved in the last SCF cycle'.format(force))
    if (force < 0.001 and not override):
        print("Relaxation sufficient, total force = %s...terminating" %force)
        raise SystemExit
    if (force < 0.001 and override):
        print("Relaxation sufficient...total force = %s\n\nOverriding threshold"\
            " limit and generating %s" %(force, file_name.replace('.in', '.in.new')))
#---------------------------------------------------------------------
if __name__ == "__main__":
    arg_parse(argv)


texts: Select latest phase of objects not marked "remove"

texts:
I have the following table in a PostgreSQL DB (simplified for the question), where I want to select only the rows marked with *:

uuid | status | info1 | info2
-------------------------------
1234 |   CONF |     - | 10
1234 |  START |   abc | 10
1234 |    FIN |   abc | 10 *
-------------------------------
7890 |   CONF |     - | 20 *
-------------------------------
1111 |   CONF |     - | 30
1111 |  START |   zzz | 30
1111 |    FIN |   zzz | 30
1111 |    REM |   zzz | 30
-------------------------------
2222 |   CONF |     - | 100
2222 |  START |   ijk | 100 *

The separating lines between different values of uuid are only for clarity, as I will explain now.

The logic for selection is the following:

Partition the table by the column uuid in order to create groups of all the different values.
Discard all the groups where there is at least one row with status REM.
For all the remaining groups, select only the one with the last status. The values of this column define a custom order like this: CONF < START < FIN. The value REM is only used to remove this group of the selection.

I wrote this query that does the job, but I think there might be a better solution, and I have the sensation of abusing the subtable structures:

SELECT *
FROM (
    SELECT MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s
    , *
    FROM(
        SELECT
         CASE
                WHEN status = 'FIN' THEN 3
                WHEN status = 'START' THEN 2
                WHEN status = 'CONF' THEN 1
                ELSE -1
            END AS phase
        , *
        FROM (
            SELECT *
            , BOOL_OR(status = 'REM')
            OVER (PARTITION BY uuid) AS removed
            FROM mytable
        ) nonremoved
        WHERE NOT removed
    ) numericphase
) lastphase
WHERE s = phase
AND s > 0

Here I'm doing the following operations (from inner to outer):

First, select all rows where status is not REM (using BOOL_OR).
Then, map each status value to a numeric one so they can be sorted.
Compute the maximum value of each uuid group (corresponding to the last status following the custom sorting).
Finally, select only rows where status = max(status). This way, only the rows corresponding to the maximum status for each group are selected.

Any possible status that does not correspond to any value in this question is not suitable, so they are mapped to -1 and discarded.

I think is easier to understand the problem by looking at the table than trying to redact it, so feel free to correct me if something is not clear.