texts:
Previously, I had written this program in C++ and asked about it here on Code Review. After spending some time with C++, I desired to become more familiar with its namesake. This is my first C program.

The purpose of the program is to help with remembering complex bash commands. It's invoked with arguments describing the desired operation and displays the commands matching the input ordered by closest match.

I'm trying to stick as close as possible to ANSI C, and I'm still not clear on when to use char [] or char *.

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

#define MAX_TEXT_LENGTH 100
#define MAX_DESC_LENGTH 100
#define MAX_KEYWORDS_LENGTH 100
#define NUM_COMMANDS 8
#define NUM_RESULTS 3

struct command {
    char text[MAX_TEXT_LENGTH];
    char description[MAX_DESC_LENGTH];
    char keywords[MAX_KEYWORDS_LENGTH];
};
struct command commands[NUM_COMMANDS] = {
    { "amixer -Mq set Master 1%-", "decrease volume", "lower" },
    { "amixer -Mq set Master 1%+", "increase volume", "raise" },
    { "makepkg -sri", "build and install a package using a PKGBUILD" },
    { "makepkg -efi", "rebuild and reinstall a package using a PKGBUILD" },
    { "pacman -Qdt", "list orphaned packages", "find" },
    { "pacman -Qe", "list explicitly installed packages", "find" },
    { "pacman -Ql [package]", "list files owned by package", "find" },
    { "pacman -Qo [file]", "list packages that own file", "find owned" }
};
struct result {
    int found;
    char text[MAX_TEXT_LENGTH];
    char description[MAX_DESC_LENGTH];
};
struct result results[NUM_COMMANDS];

int compare_results(const void *, const void *);
void convert_lower(char []);

int main(int argc, char *argv[])
{
    char current[MAX_TEXT_LENGTH + MAX_DESC_LENGTH + MAX_KEYWORDS_LENGTH];
    int a, c, found, r;

    /* convert argv to lowercase */
    for (a = 1; a < argc; ++a)
        convert_lower(argv[a]);
    for (c = 0; c < NUM_COMMANDS; ++c) {
        strcpy(current, commands[c].text);
        strcat(current, commands[c].description);
        strcat(current, commands[c].keywords);
        /* convert current to lowercase */
        convert_lower(current);
        found = 0;
        /* count words in both argv and current */
        for (a = 1; a < argc; ++a)
            if (strstr(current, argv[a]) != NULL)
                ++found;
        if (found == 0)
            continue;
        results[c].found = found;
        strcpy(results[c].text, commands[c].text);
        strcpy(results[c].description, commands[c].description);
    }
    /* sort commands with most words in common with argv at top */
    qsort(results, NUM_COMMANDS, sizeof(*results), compare_results);
    /* only print NUM_RESULTS results */
    for (r = 0; r < NUM_RESULTS && results[r].found > 0; ++r) {
        printf("%s\n", results[r].text);
        printf("    %s\n", results[r].description);
    }
    return 0;
}

int compare_results(const void *a, const void *b)
{
    struct result *r1 = (struct result *)a;
    struct result *r2 = (struct result *)b;

    return r2->found - r1->found;
}

void convert_lower(char string[])
{
    int c;

    for (c = 0; string[c] != '\0'; ++c)
        string[c] = tolower(string[c]);
}


texts: Increment value in a list of dictionaries

texts:
I have a list of dictionary let's say : l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}]
and I want to have another list l2 and add 4 to the 'a' in the all dictionaries
l2=[{'a':5,'b':2},{'a':9,'b':6},{'a':7,'b':2}]
(the first list l shouldn't change)
so I am doing it this way but i feel there is better, it is a bit hard coded I think :
 l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}]
l2=[d.copy() for d in l]
for v in l2:
    v['a']=v['a']+4


texts: Extension methods to get direct reports from user

texts:
I have created a few extension methods to get the direct reports of a UserPrincipal as UserPrincipals themselves. This saves the user of the API quite a bit of typing.

public static IEnumerable<UserPrincipal> GetDirectReportUserPrincipals(
    this UserPrincipal userPrincipal)
{
    var directReportDistinguishedNames =
        userPrincipal.GetDirectReportDistinguishedNames();
    var directReportDistinguishedNamesArray =
        directReportDistinguishedNames as string[] ??
        directReportDistinguishedNames.ToArray();
    if (directReportDistinguishedNamesArray.IsNullOrEmpty())
        return null;
    return userPrincipal.Context.FindUsersByDistinguishedNames(
            directReportDistinguishedNamesArray);
}

public static IEnumerable<string> GetDirectReportDistinguishedNames(
    this UserPrincipal userPrincipal)
{
    return userPrincipal.GetProperty(DirectReports).Cast<string>()
        .Where(
            directReportDistinguishedName =>
                !directReportDistinguishedName.IsNullOrWhiteSpace())
        .ToList();
}

public static PropertyValueCollection GetProperty(
    this Principal principal, string propertyName)
{
    return principal.GetAsDirectoryEntry().Properties[propertyName];
}

public static DirectoryEntry GetAsDirectoryEntry(
    this Principal principal)
{
    return principal.GetUnderlyingObject() as DirectoryEntry;
}

public static UserPrincipal FindUserByDistinguishedName(
    this PrincipalContext principalContext, string distinguishedName)
{
    return UserPrincipal.FindByIdentity(
        principalContext,
        IdentityType.DistinguishedName,
        distinguishedName);
}

public static IEnumerable<UserPrincipal> FindUsersByDistinguishedNames(
    this PrincipalContext principalContext,
    IEnumerable<string> distinguishedNames)
{
    return distinguishedNames.Select(
            principalContext.FindUserByDistinguishedName).ToList();
}

Yes, it does take all of those to do this one task, but the task itself can be called with

userPrincipal.GetDirectReportUserPrincipals();

instead of

Converting user principal to dictionary entry.
Getting direct reports property of dictionary entry.
Casting property to string enumerable.
Using each string (distinguished name) to search for a user principal.

Some of these do feel odd, like they are too Linq-heavy or just unnatural ways of accomplishing the goal. The top method GetDirectReportUserPrincipals has an array cast to avoid "multiple enumeration" as ReSharper says. Is that really necessary?


texts:
I want to make this code generic, so that I could remove if/else and recursive for loops.

I am open to accept all kind of suggestions regarding common interface implementation but kindly check that their property names FKID are different, and as these are POCO entities I can't change the proper names.

var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();

    int counter = -1;
    for (int i = 0; i < newClientTripTypeContracts.Count; i++)
    {
        newClientTripTypeContracts[i].ClientTripTypeContractChargeValueListID = counter;
        if (newClientTripTypeContracts[i].ChargeBITValues.Count > 0)
        {
            for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeBITValues.Count; j++)
            {
                newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeBITValues[j].ChargeBITValueFKID = counter;
            }
        }
        else if (newClientTripTypeContracts[i].ChargeDECIMALValues.Count > 0)
        {
            for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeDECIMALValues.Count; j++)
            {
                newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeDECIMALValues[j].ChargeDECIMALValueFKID = counter;
            }
        }
        else if (newClientTripTypeContracts[i].ChargeENUMValues.Count > 0)
        {
            for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeENUMValues.Count; j++)
            {
                newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeENUMValues[j].ChargeENUMValueFKID = counter;
            }
        }
        else if (newClientTripTypeContracts[i].ChargeTierMONEYValues.Count > 0)
        {
            for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeTierMONEYValues.Count; j++)
            {
                newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeTierMONEYValues[j].ChargeTierMONEYValueFKID = counter;
            }
        }
        counter -= 1;
    }


texts: OO shopping cart class + product class interaction

texts:
I built a small store site for learning purposes. I loaded my 'products' from the db into a Products class.  I used a method from this class to display the products in HTML.  Of course, the HTML contains 'Add to Cart' buttons which POST the product ID and quantity when a button is clicked.  The result is that the POSTed ID and quantity are sent to the Cart class.  This works, but it seems like I should be sending a product object to my cart instead of just two values that will be stored in an array.

I'm not sure how to do that, given that product information needs to be POSTed non-objectively.  And I'm not sure if it would be better.

class Products
{

private $products;

function __construct($data)
{

    $this->products = $data;

}

public function showProduct($id, $price, $type)
{
        echo "
";
        echo $type."
";
        echo $price."
";
        echo "Quantity: <input class='quantity' name='quantity' value='1' type='text'/>
";
        echo "<button onclick='add($id);'>Add to Cart</button>";
        echo "
";
}

public function showAll()
{
    foreach ($this->products as $id => $product) {

        $this->showProduct($id, $product->price, $product->type);
    }

}

}

And the Cart class:

class Cart
{
public $items = array();

function __construct() {

    if (isset($_SESSION['cart'])) { $this->items = $_SESSION['cart']; } else { $_SESSION['cart'] = ''; }
}

private function update() {

    $_SESSION['cart'] = $this->items;
}

public function add($id, $quantity) {

    $this->items[] = array('id'=>"$id", 'quantity'=>"$quantity");
    $this->update();

}
}

I'm not sure that I was able to get the objects from these classes to interact with each other properly.

Also, in this situation, since I need to use $_SESSION to keep the cart inventory persistent, I'm not sure why I need a Cart class at all.  It seems a little superfluous, but I have a nagging feeling that it shouldn't be.


texts: Avoid --compiler-options in makefile using nvcc

texts:
I am working with CUDA and I am currently using this makefile to automate my build process. However, there are multiple --compiler-options, basically one for each flag I want to pass to gcc.

How can I avoid repeating it over and over?

(Any suggestion about improving my makefile is also really welcome)

CC=nvcc
LIBS=-lm
CFLAGS=-Wno-deprecated-gpu-targets --compiler-options -Wextra --compiler-options -Wall --compiler-options -O3 --compiler-options -Wno-unused-result --compiler-options -Wno-unused-parameter

all:    main

main:   main.o
    $(CC) $(CFLAGS) $(LIBS) main.o -o main

main.o: main.cu
    $(CC) $(CFLAGS) $(LIBS) -c main.cu -o main.o

clean:
    rm -f *.o main


texts: Writing a class for common block of code used in many other classes

texts:
In this I have written the setAnalyticsInfo() method.  The code inside this is common to almost all other (30) classes, so I have created GoogleAnalyticsCode and defined one common method and calling this method from all other classes.

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;

import android.app.Activity;

public class GoogleAnalyticsCode {
    private String caption;
    private Activity activity;
    public GoogleAnalyticsCode(String caption, Activity activity) {
        super();
        this.caption = caption;
        this.activity = activity;
    }

    public void setAnalyticsInfo(){
        EasyTracker easyTracker = EasyTracker.getInstance(activity);

        if(easyTracker!=null)
        {
            easyTracker.send(MapBuilder
                    .createEvent(caption,     // Event category (required)
                            caption,  // Event action (required)
                            caption,   // Event label
                            null)            // Event value
                            .build());
        }
    }
}

I am calling setAnalyticsInfo() method like this in other classes in NavDrawer.java:

      public class NavDrawer {
    public void navigate_to_rating() {
        GoogleAnalyticsCode gac = new GoogleAnalyticsCode("Rate Us", activity);
        gac.setAnalyticsInfo();

        final String appPackageName =activity.getPackageName(); // getPackageName() from Context or Activity object
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    }
    }

My question is:

Is it good programming standard to write separate classes for common blocks of code used in many other classes?


texts:
The following is a series of functions to ensure that various elements on a page line up no matter what window size or when the window is resized. However I'm not sure my code is very concise as I am using the same function on three different event handlers. I read that function expressions aren't "hoisted" so I can't get the proper values on $(document).ready but I'm not sure how I could declare them with out making the code really messy and repetitive.

I've made a jsfiddle with the complete HTML and CSS.

 function captHeight(){
    var figCaption = $('.cap-bot').find($('figcaption'));
    var captionHeight = Math.max.apply(null, $('figcaption').map(function ()
      {
          return $(this).height();
    }).get());

    $('.cap-bot').css({
      'overflow': 'visible'
      });
      figCaption.css({
      'position': 'relative',
      'opacity': '1',
      'bottom': '0',
      'min-height': captionHeight+ 20 + "px" //to account for padding
      });
}

function sameHeight(){
if($('.find-height').length > 0){
    var foundHeight= $('.find-height').height();
    var gaveHeight= $('.give-height').height();

    if (gaveHeight > foundHeight){
      captHeight();
    }

    $('.give-height').css({
      'min-height': foundHeight
    });
  }
}

$(document).ready(function(){
  sameHeight();
});

$(window).on('resize', function(){
  sameHeight();
});

$(window).on('scroll', function(){
  sameHeight();
});


texts:
I have a fixed-width input format. The widths are known to me. Suppose I am told that the first field is 20 characters, the second is 10, the third is 12. The total width of a row should therefore be 42 characters. I have a working solution:

parseFW =: dyad def '(+/ (0,+/\x) ="(0 1) i. (+/x)) <;.1 y'"(_ _1)

My plan here is to use the dyadic form of cut (i.e. ;.) with a boolean array to indicate the fret locations. I'm going to get the rolling sum of the field widths to find where the indices of the frets and then I'm going to reduce that to a boolean array by looking for those indices.

This works:

   input =. noun define
NAME                STATE     TELEPHONE
John Smith          WA        418-Y11-4111
Mary Hartford       CA        319-Z19-4341
Evan Nolan          IL        219-532-c301
)

   $ input
171

  (20 10 12) parseFW >cutLF input
┌────────────────────┬──────────┬────────────┐
│NAME                │STATE     │TELEPHONE   │
├────────────────────┼──────────┼────────────┤
│John Smith          │WA        │418-Y11-4111│
├────────────────────┼──────────┼────────────┤
│Mary Hartford       │CA        │319-Z19-4341│
├────────────────────┼──────────┼────────────┤
│Evan Nolan          │IL        │219-532-c301│
└────────────────────┴──────────┴────────────┘

      $ (20 10 12) parseFW >cutLF input
4 3

My concerns are:

In my head, I feel like this shouldn't take so much code to accomplish and I'm missing something
Is it idiomatic? I'm new to J and would like to know
I. :^ _1 looks like it would do the work I need to convert the rolling sum to a boolean array of fret locations, but it doesn't seem to work (domain error). Am I misusing it?
Efficiency isn't a huge concern of mine, but I would like to know if I'm missing a "special code" opportunity here with this approach


texts:
I created my first shell script. It's an audio logger that runs on the hour for an hour and restarts. Although if it is started within the hour it will only run until the end of the hour.

I've added it to Startup Applications with the command:

gnome-terminal -e /home/admin/Desktop/audiolog.sh

However when it starts up the text in terminal flickers and is resolved by maximizing the window but works fine. Any suggestions for improvements on my script or anything that is wrong? Thanks

#!/bin/sh

DAY=$(date +%d)
MO=$(date +%m)
YR=$(date +%y)
SE=$(date +%-S)
H=$(date +%H)
M=$(date +%M)

NOW=$(date)

DURATION=$(((60 - M) * 60-SE))

PART=$(find ./Documents/ -type f -name "LoggerAudio
${DAY}-${MO}-${YR}\ ${H}*" | wc -l)

reset

echo "Recording for $DAY $MO $YR - $H 00"
echo "Started at $NOW"
echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - -"

if [ "$PART" -eq 0 ]
then
arecord -f cd -c 1 -d$DURATION -t raw -v -v | lame -b 128 -q2 -mm
-r - ./Documents/"LoggerAudio "$DAY-$MO-$YR\ $H"00".mp3
else
arecord -f cd -c 1 -d$DURATION -t raw -v -v | lame -b 128 -q2 -mm
-r - ./Documents/"LoggerAudio "$DAY-$MO-$YR\ $H"00 - Part - "$PART.mp3
fi

sleep 1s

./Desktop/audiolog.sh;


texts: Efficient way to efficiently merge arrays of objects in JavaScript

texts:
I have the below scenario where I am trying to merge two arrays of objects.

The current code works, but I am looking for a more efficient way.

var constList = [
  { name: "jack", id: "1", designation: "hr" },
  { name: "mary", id: "2", designation: "it" },
  { name: "john", id: "3", designation: "fin" }
]

var apiList = [
  { name: "jack", id: "1", height: "10" },
  { name: "mary", id: "2", height: "20" }
]

var temp = [];

constList.forEach(x => {
  apiList.forEach(y => {
    if (x.id === y.id) {
      temp.push({ ...x,
        ...y
      });
    }
  });
});

console.log(temp);


texts:
Custom class Image takes a 2-D array of 0's and 1's upon initialization. Method transform returns a modified array by modifying 0's adjacent to a 1, such that

[[0,0,0],
 [0,1,0],
 [0,0,0]]

returns

[[0,1,0],
 [1,1,1],
 [0,1,0]]

I've been working on method blur(n), which outputs an array that has been transformed n times, such that n=3 changes

[[0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,1,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0]]

into

[[0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 1, 0, 0, 0, 0]
 [0, 0, 0, 1, 1, 1, 0, 0, 0]
 [0, 0, 1, 1, 1, 1, 1, 0, 0]
 [0, 1, 1, 1, 1, 1, 1, 1, 0]
 [0, 0, 1, 1, 1, 1, 1, 0, 0]
 [0, 0, 0, 1, 1, 1, 0, 0, 0]
 [0, 0, 0, 0, 1, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0]]

Right now my solution to blur(n) works, by first creating a new Image object, transforming and then transforming additional instances of Image an additional (n-1) times. I've been getting errors if I try to apply blur without instantiating a new Image and transforming it — the transform method is not available to class Array. How could I go about applying transform iteratively without having to instantiate Image inside the class?

class Image
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def transform
    cloned = self.arr.map(&:clone)

    #scan original array for 1; map crosses into clone if found
    self.arr.each.with_index do |row, row_index|
      row.each.with_index do |cell, col|
        if cell == 1
          cloned[row_index][col+1] = 1 unless col+1 >= row.length #copy right
          cloned[row_index+1][col] = 1 unless row_index+1 >= cloned.length # copy down
          cloned[row_index][col-1] = 1 unless col.zero? # copy left
          cloned[row_index-1][col] = 1 unless row_index.zero? #copy up
        end
      end
    end
    cloned
  end

  def blur(n)
    blurred = Image.new(self).arr.transform
    (n-1).times do
      blurred = Image.new(blurred).transform
    end
    blurred
  end

end

image = Image.new([[0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,1,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0]])

image.blur(3)

#returns...
# [[0, 0, 0, 0, 0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 1, 0, 0, 0, 0],
#  [0, 0, 0, 1, 1, 1, 0, 0, 0],
#  [0, 0, 1, 1, 1, 1, 1, 0, 0],
#  [0, 1, 1, 1, 1, 1, 1, 1, 0],
#  [0, 0, 1, 1, 1, 1, 1, 0, 0],
#  [0, 0, 0, 1, 1, 1, 0, 0, 0],
#  [0, 0, 0, 0, 1, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0, 0, 0, 0, 0]]


texts:
Could anyone provide any constructive criticism? I'm trying to get a jump on data structures before classes start.

One thing is that I should add a copy constructor and assignment operator. Changes made: got rid of using namespace std.

As the code allows users to specify a cap, if they wish, for their stack any ideas of how I could signal that that particular stack is full? Currently I'm outputting a message from within the method but I don't like it when method handle output. What about a method that returns whether the stack is full?

#include <iostream>

using namespace std; // TESTING

template <typename T>
class Stack
{
public:
    Stack()
        : head(nullptr), capacity(0), currSize(0), sized(false)
    {}
    Stack(int cap)
        : head(nullptr), capacity(cap), currSize(0), sized(true)
    {}
    ~Stack();

    void push(T val);
    void pop();
    bool isEmpty() const { return head == nullptr; }
    int size() const;
    T top() const;

private:
    template <typename T>
    struct StackNode
    {
        StackNode()
            :data(0), next(nullptr)
        {}
        StackNode(T val, StackNode *ptr = nullptr)
            :data(val), next(ptr)
        {}

        T data;
        StackNode *next;
    };

    StackNode<T> *head;
    int capacity;
    int currSize;
    const bool sized;
};

template <typename T>
Stack<T>::~Stack()
{
    while (head != nullptr)
    {
        StackNode<T> *tmp = head->next;
        delete head;
        head = tmp;
    }
}

template <typename T>
void Stack<T>::push(T val)
{
    if (sized == false || currSize != capacity)
    {
        head = new StackNode<T>(val, head);
        ++currSize;
    }
    else cout << "stack full" << endl; //delete
}

template <typename T>
void Stack<T>::pop()
{
    if (head != nullptr)
    {
        StackNode<T> *tmp = head;
        head = head->next;
        delete tmp;
        --currSize;
    }
}

template <typename T>
int Stack<T>::size() const
{
    return currSize;
}

template <typename T>
T Stack<T>::top() const
{
    if (head != nullptr)
    {
        return head->data;
    }
    else return NULL;
}

int main()
{
    Stack<char> myStack(3);

    cout << "is isEmpty: " << myStack.isEmpty() << endl;

    cout << "push: "; myStack.push('H'); cout << myStack.top() << endl;
    cout << "push: "; myStack.push('G'); cout << myStack.top() << endl;
    cout << "push: "; myStack.push('B'); cout << myStack.top() << endl;
    cout << "push: "; myStack.push('D'); cout << myStack.top() << endl;
    myStack.pop();
    cout << "push: "; myStack.push('D'); cout << myStack.top() << endl;

    cout << "Size: " << myStack.size() << endl;
    cout << "Destroyed" << endl;  myStack.~Stack();

    cout << endl << endl;
    system("pause"); // TESTING
    return 0;
}


texts:
I'm a beginner, and I have just written this basic code that simply plots a parabola in a graph.
Is it possible to make my code more efficient?

The process works by the creating lists of X and Y then adding range of numbers squared to the list Y and normal X to its list and then the function plot simply goes ahead and creates a range doubled + 2 the size ( because the previous range(-size, size) creates both the minus and positive values and a zero) and fills the canvas.create_line(starting X location, starting Y location, ending X location, ending Y location) statement and also creates a log.

import tkinter
from tkinter import Tk

# Adding a Tk window
root: Tk = tkinter.Tk()
root.geometry('640x480')   # Configuring the resolution

# Adding the canvas to put the graph on it
CanvasNo1 = tkinter.Canvas(root, width=640, height=480)
CanvasNo1.grid()

def draw_axis(canvas_object):   # a function in order to draw the horizontal and vertical lines and setting the scroll
    canvas_object.update()
    x_origin = canvas_object.winfo_width() // 2
    y_origin = canvas_object.winfo_height() // 2
    canvas_object.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
    canvas_object.create_line(x_origin, 0, -x_origin, 0)
    canvas_object.create_line(0, y_origin, 0, -y_origin)

def parabola(number, size):  # Calculating the parabola
    result = number * number // size
    return result

def plot(canvas_object, size, color):  # The grand function to do the plotting process
    y_location = []
    x_location = []
    for each in range(-size, size+1):
        y_location.append(parabola(each, size))
        x_location.append(each)
    for each_of in range(0, size*2+2):
        if each_of <= size*2-1:
            canvas_object.create_line(x_location[each_of], -y_location[each_of], x_location[each_of+1],
                                      -y_location[each_of+1], fill=str(color))
            print('A line from X location of {} and Y location of {} to the X location of {} and Y location of {} was'
                  ' drawn, Color = {}'.format(x_location[each_of], y_location[each_of], x_location[each_of+1],
                                              y_location[each_of+1], color))
        else:
            break

draw_axis(CanvasNo1)
plot(CanvasNo1, 500, 'red')
CanvasNo1.mainloop()   # running the window


texts:
I wanted to write the best implementation I could think of the following really, super simple and stupid OOP model in php.

class Number {
    private $number = false;

    function __construct($n) {
        if(is_int($n)) {
            $this->number = $n;
        }
    }

    public function get() {
        return $this->number;
    }
}

class Numbers {
    public static function multiply(Number $a, Number $b) {
        return ($a->get() * $b->get());
    }
}

////
// Example
////
$first = new Number(45);
$second = new Number(80);

echo Numbers::multiply($first, $second);

Anything you guys would change? I was thinking of having Numbers extend Number, but really, the type of operations (functions) Numbers does do not need to extend the Number class. Is there a better object oriented pattern for this model?


texts:
This is a silly Redis implementation that handles only three commands: INFO, ECHO, PING.

The implementation is based on streams:

var _ = require('lodash')
var expect = require('chai').expect;
var assert = require('chai').assert;
var redis = require('redis')
var split = require('split')
var net = require('net');

var util = require('util');
var Transform = require('stream').Transform;

function makeCommand(parts) {
  var parts = _.filter(parts, (_, i) => i % 2 === 1)
  return {
    command: _.first(parts),
    args: _.drop(parts)
  }
}

function CommandParser(options) {
  if (!(this instanceof CommandParser)) {
    return new CommandParser(options)
  }

  Transform.call(this, {readableObjectMode: true})
  this.__counter = 0
  this.__parts = []
}

util.inherits(CommandParser, Transform);

CommandParser.prototype._transform = function(chunk, encoding, done) {
  var str = chunk.toString('utf-8')
  if(this.__counter == 0) {
    assert(str[0] == '*')
    this.__counter = Number(_.drop(str)) * 2
  } else {
    console.log(this.__counter, str)
    this.__parts.push(str)
    this.__counter--
  }
  if(this.__counter === 0 && !_.isEmpty(this.__parts)) {
    console.log('here')
    var command = makeCommand(this.__parts)
    console.log(command)
    this.push(command)
    this.__parts = []
  }
  done()
};

function CommandProcessor(options) {
  if (!(this instanceof CommandProcessor)) {
    return new CommandProcessor(options)
  }

  Transform.call(this, {writableObjectMode: true})
}

util.inherits(CommandProcessor, Transform);

CommandProcessor.prototype._transform = function(command, encoding, done) {
  switch (command.command) {
    case 'ping':
      done(null, '+pong\r\n')
      break;
    case 'info':
      done(null, '$9\r\nsome info\r\n')
      break;
    case 'echo':
      done(null, `\$${command.args[0].length}\r\n${command.args[0]}\r\n`)
      break;
    default:
      console.log(command)
      assert.fail()
  }
};

var TEST_PORT = 6380

var server = net.createServer(function(socket) {
  var commandParser = new CommandParser()
  var commandProcessor = new CommandProcessor()
  socket
    .pipe(split())
    .pipe(commandParser)
    .pipe(commandProcessor)
    .pipe(socket)
});

server.listen(6380, '127.0.0.1')

You can use the standard redis client to work with it. I'm mostly interested in any advice about node streams, but any other ideas are welcome too.


texts: Bash script to check available name in Github

texts:
I just wrote this script to check if the name (that has 2 characters: 1 alphabet and 1 number) in Github is available or not so I can accompany this name.

Here is my script:

#!/bin/bash

for i in {a..z}
do
  echo 'running ...'
  for j in {0..9}
  do
    out=$(curl -s -o /dev/null -w "%{http_code}" "https://github.com/$i$j") &
    if [[ $out =~ .*4.* ]]
    then
      echo "$i$j is available"
    else
      echo "$i$j is not available"
    fi
  done
  echo 'finish batch ...'
  wait
done

Let me explain:

I use 2 loops to generate all permutation of 2  characters.
I use curl to check status of the the host. For example:

curl -s -o /dev/null -w "%{http_code}" "https://github.com/google"

it will return the status of the host, in case the username exist it will return 200 else it will return 404

Then I compare the status code with any 4xx error:

$out =~ .*4.*

If the status is 4xx then the user name is available so I can get it.
Currently, it is running 10 background jobs at the same time by using curl with &.

As you can see I have found j3 and m6, n5, u6, y4, y6, y9 are available.

Could you please help me to review this script.


texts: Pig Latin game resolved with a regex in Java

texts:
I recreated the Pig Latin game on Java. The program takes an arbitrary number of command line arguments as words, and prints to the standard output these words translated with following rules:

For words that begins with a consonants, all letters until first vowel are moved to the end, and it is added the sequence "ay";
For words that begins with a vowel, it is simply added the sequence "way".

About the implementation, I've used a regular expression to split the word. I think that it is an elegant solution, maybe less efficient against a specific implementation of the rules.

The code is composed only with a class, PigLatin. You can compile it with javac PigLatin.java and run with java PigLatin <word> .... Here there is PigLatin.java:

/**
 * This small program implements the game Pig Latin. You can specify one or more
 * words as a command line argument, and the program will print the modified
 * version on the standard output.
 *
 * The rules of the game are:
 *      - For words that begin with a consonant, all letters before the first
 *        vowel are placed at the end of the word, then the sequence "ay" is
 *        appended.
 *      - For words that begin with a vowel, it is appended the sequence "way".
 *
 * Note that command line arguments are limited.
 *
 * Note that you should only use uppercase or lowercase letters.
 */
public class PigLatin {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.print(convertWord(args[i]));

            if (i < args.length - 1)
                System.out.print(" ");
            else
                System.out.println();
        }
    }

    /*
     * This method convert a word using Pig Latin rules.
     *
     * @param word the word to convert
     *
     * @return the converted word
     */
    private static String convertWord(String word) {
        /* If the word begins with a consonant (or more), this regex splits the
         * word into two groups: the first are the consonants before the first
         * vowel, the second is the rest of the string.
         * If the word begins with a vowel, only a single group is returned.
         */
        String[] tokens = word.split("^([^aeiouAEIOU]*)(\\w*)");

        if (tokens.length == 2)
            return String.join(tokens[1], tokens[0], "ay");
        else
            return word + "way";
    }
}


texts:
I have this code and this works fine but I think it's too lengthy. I want to know if there can be a less lengthy code. I've heard from people that lengthy code is often not considered good.

<title>Table</title>

<form method = "Post" action = "Table.php" >
Enter a number between 2 and 20 to see its tables:
<input type = "text" name = "number" />
<input type = "hidden" value = "true" name = "checker" />
</form>
<?PHP
if ( isset($_POST['checker'])) {
$number = $_POST['number'];
switch ($number) {
case 2:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 3:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 4:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 5:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 6:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 7:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 8:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 9:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
case 10:
for ( $counter = 1 ; $counter <= 10 ; $counter++ ) {
$temp = $number * $counter ;
echo "$number x $counter = $temp
";
}
break;
default:
echo "Please enter a number between 2 and 10";
}
}
?>


texts: Displaying hierarchical comments for movies

texts:
I have written a function which fetches all comments for a given movie. Since comments can be nested (e.g. someone replied to a comment) I am fetching them recursively (based on the parent comment id). Currently, my function looks like this:

<?php
$movieid = $this->movieid;

        function display_comments($movieid, $comment_parent_id=0, $level=0) {

        if(!$comments = CommentModel::FetchAllComments($movieid, $comment_parent_id)){
            return false;
        }
          foreach($comments as $comment) {
                $comment_id = $comment->comment_id;
                $user_id = $comment->user_id;
                $comment_content = $comment->comment_content;
                $comment_timestamp = $comment->comment_creation_datetime;
                $comment_is_deleted = $comment->comment_is_deleted;
                $comment_parent_id = $comment->comment_parent_id;

      ?>

              <a href="<?php echo Config::get('URL'); ?>profile/showProfile/<?php echo $user_id; ?>"><?php echo UserModel::getPublicProfileOfUser($user_id)->user_name; ?>, <?php echo $comment_timestamp; ?>

          <?php echo $comment_is_deleted == 0 ? $comment_content : 'Deleted' ?>

            <form action="<?php echo Config::get('URL'); ?>comment/addComment" method="post">

                Comment: <input type="text" class="form-control" name="comment_contet" required />

            <input type="hidden" name="csrf_token" value="<?= Csrf::makeToken(); ?>" />
            <input type="hidden" name="movie_id" value="<?php echo $movieid; ?>" />
            <input type="hidden" name="parent_comment" value="<?php echo $comment_id; ?>">

            <input type="submit" class="btn btn-default" value="Submit" />

        </form>

              <?php if(Session::get("user_account_type") == 7) : ?>
              <a href="<?php echo Config::get('URL').'comment/softDelete/'.$comment_id.'/'. $movieid ?>"><?php echo $comment_is_deleted == 0 ? 'Delete' : 'Undelete' ?>
              <?php endif;

        //Recurse
        display_comments($movieid, $comment_id, $level+1); ?>

   <?php }

}
    display_comments($this->movieid);
?>

It is working, but it seem very ugly!

Right now, I'm not fetching anything from the controller apart from the $movieid.

A thought:

Is there any way to change this function, so the controller fetches the comments:

public function view($movieid)
{
    $this->View->render('comment/view', array(
        'comments' => CommentModel::FetchAllComments($movieid),
        'movieid' => $movieid
    ));
}

And then a foreach function can output the comments, recursively, something like (very sorry for pseudo code):

    foreach($this->comments as $comment){
echo '
';
       if($comment->comment_parent_id){
           foreach($comment->comment_parent_id as $comment){
             echo '
'.$comment->comment_content . 'this is a parent comment
';
           }
        }
    echo $comment->comment_content . 'the "main" comment
';
    }

Now display_comments is running itself over and over, wouldn't it be correct to fetch all comments, then arrange them in the right order?

My question:

How can i improve my recursive comment function?


texts: for_each_cons and for_each_slice, variants of std::for_each working on sliding windows

texts:
My goal was to replicate Ruby's each_cons and each_slice:

(0..5).each_cons(3) {|a, b, c| print a, b, c, "\n"}
012
123
234
345

I made two functions, for_each_cons, and for_each_slice. They work similarly to their Ruby counterparts, except the slice is always passed to separate arguments. The slice size is deducted from the passed function's number of arguments.

const std::vector<int> vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for_each_cons(vec, [](int a, int b, int c){
    printf("%d %d %d\n", a, b, c);
});

for_each_slice(vec, [](int a, int b, int c){
    printf("%d %d %d\n", a, b, c);
});

Outputs:

0 1 2
1 2 3
2 3 4
3 4 5

0 1 2
3 4 5

And here's the implementation. For simple code it seems to generate similar assembly to manual implementations, although it's largely because it requires random access iterators.

#include <utility>

namespace detail
{
    template <typename Fun>
    struct function_params
        : public function_params<decltype(&Fun::operator())>
    {};

    template <typename Class, typename Ret, typename... Args> // for lambdas
    struct function_params<Ret(Class::*)(Args...) const> {
        static constexpr int n_args = sizeof...(Args);
    };

    template <typename Class, typename Ret, typename... Args> // for mutable lambdas
    struct function_params<Ret(Class::*)(Args...)> {
        static constexpr int n_args = sizeof...(Args);
    };

    template <typename Ret, typename... Args> // for function pointers
    struct function_params<Ret(*)(Args...)> {
        static constexpr int n_args = sizeof...(Args);
    };

    template<typename It, typename Fun, int N = function_params<Fun>::n_args, std::size_t... I>
    void for_each_cons_impl(It first, It last, Fun f, std::index_sequence<I...>) {
        for(auto it = first; it + N - 1 < last; ++it)
            f(*(it + I)...);
    }

    template<typename It, typename Fun, int N = function_params<Fun>::n_args, typename Indices = std::make_index_sequence<N>>
    void for_each_cons(It first, It last, Fun f) {
        for_each_cons_impl(first, last, f, Indices());
    }

    template<typename It, typename Fun, int N = function_params<Fun>::n_args, std::size_t... I>
    void for_each_slice_impl(It first, It last, Fun f, std::index_sequence<I...>) {
        for(auto it = first; it + N - 1 < last; it += N)
            f(*(it + I)...);
    }

    template<typename It, typename Fun, int N = function_params<Fun>::n_args, typename Indices = std::make_index_sequence<N>>
    void for_each_slice(It first, It last, Fun f) {
        for_each_slice_impl(first, last, f, Indices());
    }
}

template<typename It, typename Fun>
void for_each_cons(It first, It last, Fun f) {
    detail::for_each_cons(first, last, f);
}

template<typename Rng, typename Fun>
void for_each_cons(Rng &&rng, Fun f) {
    for_each_cons(rng.begin(), rng.end(), f);
}

template<typename It, typename Fun>
void for_each_slice(It first, It last, Fun f) {
    detail::for_each_slice(first, last, f);
}

template<typename Rng, typename Fun>
void for_each_slice(Rng &&rng, Fun f) {
    detail::for_each_slice(rng.begin(), rng.end(), f);
}

Any hints and criticism are welcome.


texts: Python program to solve matrix-chain multiplication

texts:
An assignment at school required me to write a Python program for this task:

  In the matrix-chain multiplication problem, we are given a sequence of
  matrices A(1), A(2), …, A(n). The aim is to compute the product
  A(1) …, A(n) with the minimum number of scalar multiplications.
  Thus, we have to find an optimal parenthesization of the matrix
  product A(1) …, A(n) such that the cost of computing the product is
  minimized.

Here is my solution to this task:

def matrix_product(p):
    """
    Return m and s.

    m[i][j] is the minimum number of scalar multiplications needed to compute the
    product of matrices A(i), A(i + 1), ..., A(j).

    s[i][j] is the index of the matrix after which the product is split in an
    optimal parenthesization of the matrix product.

    p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i].
    """
    length = len(p) # len(p) = number of matrices + 1

    # m[i][j] is the minimum number of multiplications needed to compute the
    # product of matrices A(i), A(i+1), ..., A(j)
    # s[i][j] is the matrix after which the product is split in the minimum
    # number of multiplications needed

    m = [[-1]*length for _ in range(length)]
    s = [[-1]*length for _ in range(length)]

    matrix_product_helper(p, 1, length - 1, m, s)

    return m, s

def matrix_product_helper(p, start, end, m, s):

    """
    Return the minimum number of scalar multiplications needed to compute the
    product of matrices A(start), A(start + 1), ..., A(end).

    The minimum number of scalar multiplications needed to compute the
    product of matrices A(i), A(i + 1), ..., A(j) is stored in m[i][j].

    The index of the matrix after which the above product is split in an optimal
    parenthesization is stored in s[i][j].

    p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i].
    """
    if m[start][end] >= 0:
        return m[start][end]

    if start == end:
        q = 0
    else:
        q = float('inf')
        for k in range(start, end):
            temp = matrix_product_helper(p, start, k, m, s) \
                   + matrix_product_helper(p, k + 1, end, m, s) \
                   + p[start - 1]*p[k]*p[end]
            if q > temp:
                q = temp
                s[start][end] = k

    m[start][end] = q
    return q

def print_parenthesization(s, start, end):
    """
    Print the optimal parenthesization of the matrix product A(start) x
    A(start + 1) x ... x A(end).

    s[i][j] is the index of the matrix after which the product is split in an
    optimal parenthesization of the matrix product.
    """
    if start == end:
        print('A[{}]'.format(start), end='')
        return

    k = s[start][end]

    print('(', end='')
    print_parenthesization(s, start, k)
    print_parenthesization(s, k + 1, end)
    print(')', end='')

n = int(input('Enter number of matrices: '))
p = []
for i in range(n):
    temp = int(input('Enter number of rows in matrix {}: '.format(i + 1)))
    p.append(temp)
temp = int(input('Enter number of columns in matrix {}: '.format(n)))
p.append(temp)

m, s = matrix_product(p)
print('The number of scalar multiplications needed:', m[1][n])
print('Optimal parenthesization: ', end='')
print_parenthesization(s, 1, n)

Here is an example output:

Enter number of matrices: 3
Enter number of rows in matrix 1: 10
Enter number of rows in matrix 2: 100
Enter number of rows in matrix 3: 5
Enter number of columns in matrix 3: 50
The number of scalar multiplications needed: 7500
Optimal parenthesization: ((A[1]A[2])A[3])

Here is the time taken for this output:

  0:00:15.332220 seconds.

So, I would like to know whether I could make this program shorter and more efficient.


texts: Determining whether a number is a palindrome

texts:
Can someone improve this for me? It seems ugly.

The method should test whether an incoming number is a palindrome and return a Boolean result.

private static bool IsPalindrome(int value)
{
    var inverseValue = string.Concat(value.ToString().Reverse());
    return inverseValue == value.ToString();
}


texts: Turning multiple PHP arrays into one array ready for conversion to Javascript

texts:
I am creating a multiple choice quiz game with PHP and Javascript. Questions can have 2 to 6 answers. I have been using the PHP queries in the code below to get arrays of the questions of a quiz, and the answers for each questions.

I now want to use this data in Javascript, and want to make it so each time a user clicks next question, a question and corresponding answers are displayed.

I think (but am not sure) that the best way to do this is to combine the arrays into one where the question array contains the answers arrays before converting to a javascript array.

Is this really the way I should do this, and if so how do I do so?

$thisquizid = $_POST['quizidvalue'];
    for ($j = 0; $j < $questionrows; ++$j)
        {
            $questionresult = pg_fetch_array($questionquery);
            $answerquery = pg_query($db_handle, "SELECT * FROM answer WHERE questionid = '$questionresult[0]'");
            $answerrows = pg_num_rows($answerquery);

        for ($i = 0; $i < $answerrows; ++$i)
            {
                $answerresult = pg_fetch_array($answerquery);
            }

    }


texts: Aho-Corasick algorithm to scan through a list of strings

texts:
This is a follow-up to my previous question about finding min and max values of an iterable.
Aho-Corasick algorithm was suggested to solve the problem. Below is my solution with the use of ahocorapy library.

Short re-cap of the problem:

  You are given 2 arrays (genes and health), one of
  which have a 'gene' name, and the other - 'gene' weight (aka
  health). You then given a bunch of strings, each containing values m and n, which denote the start and end of the slice to be applied
  to the genes and health arrays, and the 'gene'-string, for which
  we need to determine healthiness. Then we need to return health-values
  for the most and the least healthy strings.

I think there might be something off with the code, but not sure what. It works quite fine for small testcases, giving more or less same timing as previous versions of the solution showed, but when it comes to large testcases, my PC basically hangs.

Example of a small testcase:

genes = ['a', 'b', 'c', 'aa', 'd', 'b']
health = [1, 2, 3, 4, 5, 6]
gene1 = "1 5 caaab" (result = 19 = max)
gene2 = "0 4 xyz" (result = 0 = min)
gene3 = "2 4 bcdybc" (result = 11)

Large testcase (2 lists 100K elements each; testcase 41K+ elements): txt in my dropbox (2,80 MB) (too large for pastebin)

So, I have 2 questions: 1) What is wrong with my code, how can I impore its performace
2) How do I apply the Aho-Corasick without turning to any non-standard library (because, most likely, it cannot be installed on HackerRank server)

def geneshealth(genes, health, testcase):
    from ahocorapy.keywordtree import KeywordTree
    import math

    min_weight = math.inf
    max_weight = -math.inf

    for case in testcase:
        #construct the keyword tree from appropriately sliced "genes" list
        kwtree = KeywordTree(case_insensitive=True)
        fl, ceil, g = case.split()
        for i in genes[int(fl):int(ceil)+1]:
            kwtree.add(i)
        kwtree.finalize()
        #search the testcase list for matches
        result = list(kwtree.search_all(g))

        hea = 0
        for gn, _ in result:
            for idx, val in enumerate(genes):
                if val == gn:
                    hea += health[idx]

        if hea < min_weight:
            min_weight = hea
        if hea > max_weight:
            max_weight = hea
    return(min_weight, max_weight)


texts: Prevent search changes from spamming history

texts:
This is my solution to my SO question. My requirements are:

use links inside of the angular app
when following a link with the same path (i.e., differing in the search only), do not add it to the browser history

.run(function($rootScope, $location) {
    var replacing;

    $rootScope.$on("$locationChangeStart", function(event, newUrl, oldUrl) {
        if (oldUrl === newUrl) {
            return; // Nobody cares.
        }

        // Make urls relative.
        var baseLength = $location.absUrl().length - $location.url().length;
        newUrl = newUrl.substring(baseLength);
        oldUrl = oldUrl.substring(baseLength);

        // Strip search, leave path only.
        var newPath = newUrl.replace(/\?.*/, "");
        var oldPath = oldUrl.replace(/\?.*/, "");

        // Substantial change, history should be written normally.
        if (oldPath !== newPath) {
            return;
        }

        // We're replacing, just let it happen.
        if (replacing) {
            replacing = false;
            return;
        }

        // We're NOT replacing, scratch it ...
        event.preventDefault();

        // ... and do the same transition with replace later.
        $rootScope.$evalAsync(function() {
            $location.url(newUrl).replace();
            replacing = true;
        });
    });
})


texts: Calculating population standard deviation

texts:
This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic.

from math import sqrt

def mean(lst):
    """calculates mean"""
    sum = 0
    for i in range(len(lst)):
        sum += lst[i]
    return (sum / len(lst))

def stddev(lst):
    """calculates standard deviation"""
    sum = 0
    mn = mean(lst)
    for i in range(len(lst)):
        sum += pow((lst[i]-mn),2)
    return sqrt(sum/len(lst)-1)

numbers = [120,112,131,211,312,90]

print stddev(numbers)


texts: Checking whether a string contains a substring only once

texts:
I want to check if a string contains only a single occurrence of the given substring (so the result of containsOnce("foo-and-boo", "oo") should be false). In Java, a simple and straightforward implementation would be either

boolean containsOnce(final String s, final CharSequence substring) {
    final String substring0 = substring.toString();
    final int i = s.indexOf(substring0);
    return i != -1 && i == s.lastIndexOf(substring0);
}

or

boolean containsOnce(final String s, final CharSequence substring) {
        final String substring0 = substring.toString();
        final int i = s.indexOf(substring0);
        if (i == -1) {
            return false;
        }

        final int nextIndexOf = s.indexOf(substring0, i + 1);
        return nextIndexOf == 0 || nextIndexOf == -1; // nextIndexOf is 0 if both arguments are empty strings.
}

Can you suggest a simpler/more efficient implementation?


texts: Get all members from country depending on multiple tables

texts:
I have 4 tables, filled with some example data

user table

id | name  | idAddress |
------------------------
1  | Bernd | 1         |
2  | Max   | 2         |
3  | Tom   | 3         |
4  | Bob   | 4         |
5  | Alice | 5         |

address

id | country |  zip  |
----------------------
1  | DE      | 39213 |
2  | CH      | 13847 |
3  | NL      | 38472 |
4  | DE      | 94872 |
5  | MT      | 54682 |
6  | US      |  4682 |
7  | DE      | 45853 |
8  | NA      | 12144 |

orga2Address

idOrga   | idAddress |
------------------
1        | 6         |
1        | 7         |
2        | 7         |
2        | 8         |

orga2User

idUser | idOrga |
-----------------
1      | 1      |
1      | 2      |
2      | 1      |
3      | 2      |
4      | 2      |

I want to select all user names that have address in 'DE' in the user table or that are in an orga which has an address in 'DE' in orga2Address.

I was able to get the result with the UNION command like this (see this SQLFiddle):

SELECT `name`, `country` FROM (SELECT `user`.`name`, `address`.`country` from `user`
INNER JOIN `address` ON `user`.`idAddress` = `address`.`id`
UNION
SELECT  `user`.`name` from `user`
INNER JOIN `orga2User` `o2U` ON `o2U`.`idUser` = `user`.`id`
INNER JOIN `orga2Address` `o2A` ON `o2A`.`idOrga` = `o2U`.`idOrga`
INNER JOIN `address` `a` ON `a`.`id` = `o2A`.`idAddress`) as `U` WHERE `U`.`country`="DE";

The result

name   |
--------
Bernd  |
Max    |
Tom    |
Bob    |

Is there a quicker and better way to get the wanted result?


texts:
This is a code I wrote for solving the famous nqueens problem. It returns only the first solution. I would like your reviews and comments and ways to convert it to a solution which will return a set of all solutions are welcome.
So, here I go:

#include <stdio.h>
#include <stdlib.h>

int isSafe(int** matrix, long long row, long long col, long long matrixDim) {
    //check col
    for (long long i = 0; i < row; i++) {
        if (matrix[i][col] == 1) {
            return 0;
        }
    }
    //check upper left diagonal
    for (long long i = row, j = col;;) {
        i--; j--;
        if (i < 0 || j < 0) {
            break;
        }
        if (matrix[i][j] == 1) {
            return 0;
        }
    }
    //check upper right diagonal
    for (long long i = row, j = col;;) {
        i--; j++;
        if (i < 0 || j == matrixDim) {
            break;
        }
        if (matrix[i][j] == 1) {
            return 0;
        }
    }
    //check lower left diagonal
    for (long long i = row, j = col;;) {
        i++; j--;
        if (i == matrixDim || j < 0) {
            break;
        }
        if (matrix[i][j] == 1) {
            return 0;
        }
    }
    //check lower right diagonal
    for (long long i = row, j = col;;) {
        i++; j++;
        if (i == matrixDim || j == matrixDim) {
            break;
        }
        if (matrix[i][j] == 1) {
            return 0;
        }
    }
    return 1;
}

void printSqMatrix(int** matrix, long long Dim) {
    for (int i = 0; i < Dim; i++) {
        for (int j = 0; j < Dim; j++) {
            printf("%d ", matrix[i][j]);
        }
        puts("");
    }
}

int solve(int** chessBoard, long long row_index, long long boardSize) {
    if (row_index == boardSize) {
        return 1;
    }
    long long j;
    for (j = 0; j < boardSize; j++) {
        if (isSafe(chessBoard, row_index, j, boardSize)) {
            chessBoard[row_index][j] = 1;
            int retVal = solve(chessBoard, row_index + 1, boardSize);
            if (retVal == 1) {
                return 1;
            }
            else if (retVal == -1) {
                puts("Something seriously wrong with execution");
                exit(1);
            }
            chessBoard[row_index][j] = 0;
        }
    }
    if (j == boardSize) {
        return 0;
    }
    return 1;   //never reaches here (written to solve a warning saying not all codepaths return a value
}

int main(void) {
    int** board = NULL;
    long long sizeOfBoard = 0;
    printf("Enter the size of the board: ");
    scanf("%lld", &sizeOfBoard);
    board = malloc(sizeof(int*) * sizeOfBoard);
    for (long long i = 0; i < sizeOfBoard; i++) {
        board[i] = malloc(sizeof(int) * sizeOfBoard);
        for (long long k = 0; k < sizeOfBoard; k++) {   //if I don't write this loop, the 0s get printed as 3452816845....Why???
            board[i][k] = 0;
        }
    }
    solve(board, 0, sizeOfBoard);
    printSqMatrix(board, sizeOfBoard);
}


texts:
What do you think about such an object function?

const stc = {
  delayTimer: {},
  sleep: (m, name) => new Promise(r => stc.delayTimer[name] = setTimeout(r, m)),
  sleepProlong: async (ms, name)=> {
    if (stc.delayTimer[name])
      clearTimeout(stc.delayTimer[name]);
    delete stc.delayTimer[name];
    return await stc.sleep(ms, name);
  }
}

It is used to make a delay, but additionally when you call it again before the set time expires, it clears the counter and counts from the beginning, does not release the function any further.

async function s (){
  console.log("wy");
  await stc.sleepProlong(5000, "mek");
  console.log("my");
}

For example, when in the console you will start s() before 5 seconds elapses from the previous firing, "we" will not appear. when you stop, it will complete the last counting and "we" will be displayed.

What do you think? Can you do it better?


texts:
This is my first website. I would like to make sure that:

I am using HTML5 sectioning elements correctly.
I didn't forgot anything important for HTML5 compatibility like html5shiv, for example.

Any other advice?

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>DEdesigns</title>

    <link rel="stylesheet" href="style.css">

DEdesigns

Home

About

Services

Contact

About Me

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged

My Work

rem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500

rem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500

rem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500

Services

one

two

three

Contact Me

some contact me stuff goes here

This is my fotter


texts: Finding the Least Common Ancestor of a Binary Tree

texts:
Input a binary tree (the root node) and 2 other nodes that need to be assessed for finding the least common ancestor (LCA)
Code:
a. Finding the nodes first with either breadthFirstSearch or depthFirstSearch
b. If they both exist, find the LCA.
What searching mechanism would be best here? Using breadthFirst for now.

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Stack;

    class Treenode {
      public int value;
      public Treenode right;
      public Treenode left;
      public Treenode(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
    }
    public class SearchTree {
     static boolean v1=false,v2=false;
    public static void main(String[] args) {
    Treenode n1 = new Treenode(5);
    Treenode n2 = new Treenode(2);
    Treenode n3 = new Treenode(4);
    Treenode n4 = new Treenode(1);
    Treenode n5 = new Treenode(3);
    n1.left = n2;
    n1.right = n3;
    n2.left = n4;
    n2.right = n5;
    System.out.println("Found BFS? :"+ breadthFirstSearch(n1, 14));

    System.out.println("Found DFS? :"+ depthFirstSearch(n1, 5));
    System.out.println();

    System.out.println("LCA "+" is "+lca(n1,5,50));

    }
    public static boolean breadthFirstSearch(Treenode root, int value){
    if(root==null){
        return false;
    }
    Queue<Treenode> q1 = new LinkedList<Treenode>();
    q1.add(root);
    while(!q1.isEmpty())
    {
        Treenode temp = q1.peek();

        if(temp!=null) {
            q1.remove();
            if (temp.value == value) return true;
            if (temp.left != null) q1.add(temp.left);
            if (temp.right != null) q1.add(temp.right);
        }
    }
    return false;
    }
    public static boolean depthFirstSearch(Treenode root, int value){
    if(root==null){
        return false;
    }
    Stack<Treenode> s1 = new Stack<Treenode>();
    s1.add(root);

    while(!s1.isEmpty()){
       Treenode temp = s1.peek();
        if(temp!=null){
            s1.pop();
            if (temp.value == value) return true;
            if (temp.right != null) s1.push(temp.right);
            if (temp.left != null) s1.push(temp.left);

        }
        }
        return false;
        }

    public static Treenode lcaHelper(Treenode head, int x,int y){

    if(head==null){
        return null;
    }

    if(head.value == x || head.value ==y){
        if (head.value == y){
            v2 = true;
            return head;
        }
        else {
            v1 = true;
            return head;
        }
    }

    Treenode left = lcaHelper(head.left, x, y);
    Treenode right = lcaHelper(head.right,x,y);

    if(left!=null && right!=null){
        return head;
    }
    return (left!=null) ? left:right;
    }

    public static int lca(Treenode head, int h1, int h2) {
    v1 = breadthFirstSearch(head, h1);
    v2 = breadthFirstSearch(head,h2);
    if(v1 && v2){
        Treenode lca = lcaHelper(head,h1,h2);
        return lca.value;
    }
    return -1;
    }
    }


texts:
This is a little program to show how a WAVe-File Generator could be written.
It use a Function-Object "SinFunction" to calculate the value of any point of the amplitude in time. This object and two floats are given to the constructor of the generator object. The two floats are the frequency and the duration of the created signal.

You could give it other Function-Objects to produce the function of any expression you can write in C++. Or you could give SinFunction different frequency and/or duration values.

#include <iostream>     /* Write File */
#include <fstream>
#include <string>       /* File Name Parameter */
#include <math.h>       /* sin */

using namespace std;

class SinFunction{

public:

    float operator() (float x){

        return sin(x);

    }
};

template <class Funk>
class WaveFileWriter{

private:
void longWrite(long x, ofstream &myfile)
{
  long i = x;
  int i1 = i % 256;
  i = i - i1;
  i = i / 256;
  int i2 = i % 256;
  i = i - i2;
  i = i / 256;
  int i3 = i % 256;
  i = i - i1;
  i = i / 256;
  int i4 = i;

  unsigned char a = (unsigned char)i1;
  unsigned char b = (unsigned char)i2;
  unsigned char c = (unsigned char)i3;
  unsigned char d = (unsigned char)i4;

  myfile << a;
  myfile << b;
  myfile << c;
  myfile << d;
}

void integerWrite(unsigned int x, ofstream &myfile)
{
  unsigned int i = x;
  int i1 = i % 256;
  i = i - i1;
  i = i / 256;

  unsigned char a = (unsigned char)i1;
  unsigned char b = (unsigned char)i;

  myfile << a;
  myfile << b;

}

float Frequency; // Frequency of playing Tone
float Duration ; // Duration on playing Tone
Funk Funktion;

public:
WaveFileWriter(string FileName, float Frequenz, float Duratione) : Frequency{Frequenz}, Duration{Duratione} {
  ofstream myfile;

  // Definition on File Name: "MeinTest.wav"
  myfile.open (FileName.c_str(), ios::out | ios::binary);

  // empty Char declaration
  char h = 0;
  // +++++++ Header ++++++
  // ----- WAV-Header ----
  // Chunk Name "RIFF"
  char RIFF[] = "RIFF";
  myfile << RIFF;

  // Chunk Lange
  longWrite(220000, myfile);

  // RIFF-Typ "WAVE"
  char WAVE[] = "WAVE";
  myfile << WAVE;
  // ----- FMT CHUNK ------

  // CHUNK-NAME 'FMT
  char FMT[] =  "fmt ";
  myfile << FMT;

  // CHUNK Länge 10H
  longWrite(0x10, myfile);
  // Audio-Format
  integerWrite(1, myfile);

  // Kanalzahl
  integerWrite(2, myfile);

  // Samplerate (Hz) = 44 000
  long SampelsPerSecond = 44100;
  longWrite(SampelsPerSecond, myfile);

  // Bytes pro Sekunde = 44 000
  longWrite(176000, myfile);

  // Bytes pro Sampel
  integerWrite(4, myfile);

  // Bits pro Sampel
  integerWrite(16, myfile);

  // CHUNK-Name 'data'
  char data[] = "data";
  myfile << data;
  // CHUNK Lange
  int Time = 5;
  long DataLeng = (long)SampelsPerSecond * Time;
  longWrite(DataLeng, myfile);
  // +++++ DATA ++++
  float result;
  float value;
  unsigned int f;
  for(float m = 0; m <= DataLeng; m++)
  {
    // 1. Chanel
    result = Funktion(M_PI*2*(m/SampelsPerSecond)*Frequency);
    value = (result * 32767 ) + 32767;
    f = (unsigned int)value;
    integerWrite(f, myfile);

    //2. Chanel
    result = Funktion(M_PI*2*(m/SampelsPerSecond)*Frequency);
    value = (result * 32767 ) + 32767;
    f = (unsigned int)value;
    integerWrite(f, myfile);

    // myfile << (char)value;
  }

  //  File is writen so close
  myfile.close();
}
};

int main( int argc, const char* argv[] )
{
    WaveFileWriter<SinFunction> File1{"MyTest.wav", 1000, 5};
    return 0;
}

I'm looking for ideas to refactor it, to make it perfect.


texts: TypeScript fetch wrapper class with localStorage cache

texts:
I'm learning TypeScript while doing my portfolio, and I wrote a class to make a fetch request to the API that holds my data.
It is working fine. I use localStorage to set a cache to avoid calling the API often as the data won't change.
I know I could improve this a lot, and haven't used many TypeScript features, so it would be great to have some pointers on how to improve this class generally, and also how to improve it by adding some more TypeScript features.
This is the class:
export interface PortfolioData {
  basics: Basics;
  projects?: Project[];
}

interface Cache {
  portfolio: PortfolioData;
  expiration: number;
}

class Portfolio {
  private url = 'https://gitconnected.com/v1/portfolio/mauriciorobayo';
  private cacheDurationInMilliseconds: number;

  constructor(cacheDurationInMinutes: number) {
    this.cacheDurationInMilliseconds = cacheDurationInMinutes * 60 * 1000;
  }

  private getCache(): Cache | undefined {
    const data = localStorage.getItem('portfolio');

    if (!data) {
      return;
    }

    const cache = JSON.parse(data);

    if (Date.now() > cache.expiration) {
      return;
    }

    return cache;
  }

  private setCache(data: Cache) {
    localStorage.setItem('portfolio', JSON.stringify(data));
  }

  async getPortfolio(): Promise<PortfolioData> {
    const cache = this.getCache();

    if (cache) {
      return cache.portfolio;
    }

    const response = await fetch(this.url);
    if (response.ok) {
      const portfolio = await response.json();

      this.setCache({
        portfolio,
        expiration: Date.now() + this.cacheDurationInMilliseconds,
      });

      return portfolio;
    }
    throw new Error(response.statusText);
  }
}

export default Portfolio;


texts:
I wanted to create a class that encrypts provided clear text using Caesar Cipher. Do you find my implementation clean? Any suggestions?

package biz.tugay.caesarcipher;

import java.util.Locale;

/*
    Encyrpts a clear text using Caeser Cipher (https://en.wikipedia.org/wiki/Caesar_cipher)
    with given shift amount.

    Provided shift amount (i.e. key) must be a positive integer less than 26.
    Only English alphabet is supported and encyrpted text will be in uppercase.

    Shift amount 0 will return the same clear text.
 */
public final class CaesarCipher {

    private final String clearText;
    private final int key;

    public CaesarCipher(final String clearText, final int key) {
        if (clearText == null) {
            throw new UnsupportedOperationException("Clear text to be encrypted can not be null!");
        }

        if (key < 0 || key > 26) {
            throw new UnsupportedOperationException("Key must be between 0 and 26");
        }

        this.clearText = clearText;
        this.key = key;
    }

    public String encryptText() {
        final StringBuilder cipherTextBuilder = new StringBuilder();

        final String clearTextUpperCase = clearText.toUpperCase(Locale.US);
        final char[] clearTextUpperCaseCharArray = clearTextUpperCase.toCharArray();

        for (final char c : clearTextUpperCaseCharArray) {
            if (c < 65 || c > 90) { // If the character is not between A .. Z, append white space.
                cipherTextBuilder.append(" ");
                continue;
            }
            final Character encryptedCharacter = encryptCharacter(c);
            cipherTextBuilder.append(encryptedCharacter);
        }

        return cipherTextBuilder.toString();
    }

    private Character encryptCharacter(final char c) {
        final int initialShift = c + key;
        final int finalShift;

        if (initialShift > 90) {
            // This is the case where we go beyond Z, we must cycle back to A.
            finalShift = (initialShift % 90) + 64;
        } else {
            // We are in the boundries so no need to cycle..
            finalShift = initialShift;
        }

        return (char) finalShift;
    }
}

and I have 2 simple tests:

package biz.tugay.caesarcipher;

import org.junit.Assert;
import org.junit.Test;

public class CaesarCipherTest {

    @Test
    public void shouldReturnBCDForClearTextABCAndKey1() {
        final String clearText = "abc";
        final CaesarCipher caesarCipher = new CaesarCipher(clearText, 1);
        final String encryptedText = caesarCipher.encryptText();
        Assert.assertTrue(encryptedText.equals("BCD"));
    }

    @Test
    public void shouldReturnAForZAndKey1() {
        final String clearText = "Z";
        final CaesarCipher caesarCipher = new CaesarCipher(clearText, 1);
        final String encryptedText = caesarCipher.encryptText();
        Assert.assertTrue(encryptedText.equals("A"));
    }
}


texts: Grouping filenames by basename and extension

texts:
I have created a function that parses a directory tree, and returns a list of lists that groups specific files within for later program specific parsing.  I feel like it could be done better, considering I've used dummy variables, and was hoping some of you could help.

def get_output_files(path) -> list:
    """
    This routine crawls through a directory tree, and checks for groups of job files, and groups based on:
        .sh   - run script file
        .hin  - hamiltonian creation input file
        .in   - iterate input file
        .hout - hamiltonian creation output file
        .out  - iterate output file
    to be used for parsing.

    Checks for grouping based on base name of file, if file suffix does not exist, then returns None in place.
    Example:  directory "/home/test" contains the following files:
        run.sh
        run.hin
        run2.in
        run.hout
        run2.out

    will return the following list:
        [
        [run.sh, run.hin, None, run.hout, None],
        [None, None, run2.in, None, run2.out]
        ]
    """
    jobs = []
    suffixes = ['.sh', '.hin', '.in', '.hout', '.out']
    for root, dirs, files in os.walk(path):
        for file in files:
            base, end = file.rsplit('.', 1)
            dummy_list = []
            for suffix in suffixes:
                if base + suffix in files:
                    dummy_list.append(os.path.join(root, base + suffix))
                else:
                    dummy_list.append(None)
            jobs.append(dummy_list)
    real_jobs = []
    for num, job in enumerate(jobs):
        if not all(element is None for element in job):
            real_jobs.append(job)
    return jobs


texts: Handling objects and arrays simply in this tagging library

texts:
I have written this little tagging module to make it easier to generate small html snippets on the fly. The examples below show how this make things a bit easier. My question is about the handling of tags that contain either a single element like text or a list of other elements, like the tr element in the second example. At the moment, the code has to jump though some unpythonic loops to handle the different cases. How do I write code that handles either a single thing or a list of those things with one function in an elegant way?

""" Supplies some utilities for creating html documents manually

>>> print(h1('test'))

test

>>> print(table([tr([td('d1'), td('d2')]), tr()]))

d1

d2

"""
from __future__ import print_function

class tag:
    """ represents an html tag - specifically used to create outputs for web pages

    Basic usage - create a "test" tag:

    >>> print(tag('test'))
    <test />

    Attributes can be specified as a dictionary

    >>> print(tag('test', attributes={'prop': 'value'}))
    <test prop='value' />

    The real benefit - tags can be nested, allowing the python interpreter to track closing tags:

    >>> print(tag('test', tag('inner')))
    <test>
    <inner />
    </test>
    """
    def __init__(self, name, contents=[], attributes={}):
        self.name = name
        self.contents = contents
        self.attributes = attributes
    def __str__(self):
        tagcontents = self.name
        if len(self.attributes) > 0:
            attrstring = " ".join("%s='%s'" % kv for kv in self.attributes.items())
            tagcontents += " " + attrstring

        if self.contents:
            if hasattr(self.contents, '__iter__') and not hasattr(self.contents, 'strip'):
                contentstring = "\n".join(str(i) for i in self.contents)
            else:
                contentstring = str(self.contents)
            return "<%s>\n%s\n</%s>" % (tagcontents, contentstring, self.name)
        else:
            return "<" + tagcontents + " />"
    def __repr__(self):
        return "tag(%s, contents=%s, attributes=%s)" % (self.name, self.contents, self.attributes)

def namedtag(t):
    """ create a named tag class - useful for standard html tags

    >>> mytag = namedtag('mytag')
    >>> print(mytag())
    <mytag />

    """
    class n(tag):
        def __init__(self, contents=[], attributes={}):
            tag.__init__(self, t, contents, attributes)
    return n

h1, h2, p, table, td, th, tr, a = (namedtag(t) for t in ("h1", "h2", "p", "table", "td", "th", "tr", "a"))


texts:
Okay, So I have this method I made that searches a 2d array of user input column length and row length comprised of integers. The method is suppose to find 4 alike numbers in rows, columns, and both major and minor diagonals throughout the entire array. The array can be as large as the user would like. My method works, however it is extremely ugly and feels redundant. I feel like there should be a better way to compact my code that I just am not seeing. Can anyone tell me how I may accomplish this? I am trying to self teach myself so I don't really have any help but my own. Please dont bash my ugly code :) haha. My main issue is the check diagonals part... It seems like it could be shorter.

public static boolean isConsecutiveFour(int[][] values) {
    int count = 0;
    int currentElement = 0;

    //count rows
    for (int x = 0; x < values.length; x++) {
        count = 0;
        currentElement = values[x][0];
        for (int y = 0; y < values[x].length; y++) {
            if (currentElement == values[x][y])
                count++;
            currentElement = values[x][y];
        }
        if (count >= 4)
            return true;
    }

    //count columns
    for (int x = 0; x < values[0].length; x++) {
        count = 0;
        currentElement = values[0][x];
        for (int y = 0; y < values.length; y++) {
            if (currentElement == values[y][x])
                count++;
            currentElement = values[y][x];
        }
        if (count >= 4)
            return true;
    }

    //count diagonals
    for (int x = 0; x < values.length; x++) {
        int increaseRow = x;
        for (int y = 0; y < values[x].length; y++) {
            int currentMajElement = values[x][y], currentSubElement = values[x][y];
            int majCount = 0, subCount = 0;
            int increaseColumn = y, decreaseColumn = y;

            //Check major diagonals
            while (increaseRow < values.length && increaseColumn < values[x].length) {
                if (currentMajElement == values[increaseRow][increaseColumn])
                    majCount++;
                currentMajElement = values[increaseRow][increaseColumn];
                increaseColumn++;
                increaseRow++;
            }
                increaseRow = x;
            //Check minor diagonals
            while (increaseRow < values.length && decreaseColumn >= 0)  {
                if (currentSubElement == values[increaseRow][decreaseColumn])
                    subCount++;
                currentSubElement = values[increaseRow][decreaseColumn];
                increaseRow++;
                decreaseColumn--;
            }
            if (majCount >= 4 || subCount >= 4)
                return true;
        }
    }
return false;
}


texts: Getting data correctly from  tag with beautifulsoup and regex

texts:
I am scraping an online shop page, trying to get the price mentioned in that page. In the following block the price is mentioned:

&#x20B9;&nbsp;999

I am using Beautiful Soup to get this tag and using a regular expression to get the price:

# -*- coding: utf8 -*-

import re
import requests
from bs4 import BeautifulSoup

hs18_test_urls = ['http://www.homeshop18.com/diary-wimpy-kid-hard-luck/author:jeff-kinney/isbn:9780141350677/books/juvenile-fiction/product:30926027/cid:10065/?it_category=HP&it_action=BO-R01001&it_label=HP-R01001-140121094603-30926027-PR-BO-RM-OT-RT01_BooksFlat40PercentOff-RL02-160120&it_value=0',
            'http://www.homeshop18.com/apple-ipad-air-wi-fi-16gb-space-grey/computers-tablets/tablets/product:31228967/cid:16327/',
            'http://www.homeshop18.com/reebok-men-black-yellow-sandals-j97184/footwear/men/product:30795219/cid:15067/',
            'http://www.homeshop18.com/american-swan-women-shirt-pink/clothing/women/product:31225645/cid:15021/',
            'http://www.homeshop18.com/diva-fashion-art-silk-saree-parrot-green/clothing/women/product:31514557/cid:15011/?it_category=hs18bot&it_action=recentlySoldProducts&it_label=31225645&it_value=1']

hs18_expected_test_results = [u'210', u'35900', u'1499', u'479', u'1199']

def get_homeshop18_product_meta(url):
    reg = ur'^ ₹? (\d+)'
    response = requests.get(url)
    if response.status_code == requests.codes.ok:
        soup = BeautifulSoup(response.text)
        product_name = soup.find('meta', {'property' : 'og:title'})['content']
        product_url = soup.find('meta', {'property' : 'og:url'})['content']
        product_img_url = soup.find('meta', {'property': 'og:image'})['content']
        product_price_tag_element = soup.find('span', {'id': 'hs18Price', 'itemprop': 'price'})
        product_price_match = re.match(reg, product_price_tag_element.text)
        if product_price_match:
            product_price = product_price_match.group(1)
        else:
            product_price = None
        return (product_url, product_name, product_img_url, product_price)
    return None

if __name__ == '__main__':
    assert(map(lambda x: x[3], map(get_homeshop18_product_meta, hs18_test_urls)) == hs18_expected_test_results)

Questions:

With beautiful soup I can get contents within that span tag. Is there any way to just get the content of the outer span and ignoring whatever is within the inner span tag? i.e. it should give me only &nbsp; 210.
If the above is not possible, then is there any further improvements you suggest with regards to re or the code in general?
I am using a unicode character(\U20B9) in my script.  Should I be doing that?  I couldn't get re to match even after sending re.UNICODE flag.

reg = r'^ \U20B9? (\d+)'

product_price_match = re.match(reg, product_price_tag_element.text, re.UNICODE)

For the reason mentioned in #3, I am using -*- coding: utf8 -*- at the start. Is that okay? Is this the pythonic way? or any suggested way?


texts:
I have an array of objects with, let's say, two properties. One of those properties can have bad values, in the form on a -9999 value.

The aim is to calculate the average of each property, without the bad values.

I am looking to improve my code,  I feel especially wrong about the two loops.

var array = [
{item1: 50, item2: 10},
{item1: 70, item2: -9999},
{item1: 60, item2: 5},
{item1: 40, item2: 7},
]

var avg1 = array.reduce(function(sum, a,i,ar) { sum += a.item1;  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

document.getElementById("avg1").innerText = avg1;

var badvalues = 0;

for (var i=0; i<array.length; i++){
if (array[i].item2 == -9999){badvalues++;}
}

var avg2 = array.reduce(function(sum, a,i,ar) {
sum += (a.item2 == -9999? 0: a.item2);
return i==ar.length-1?(ar.length==0?0:sum/(ar.length-badvalues)):sum},0);

document.getElementById("avg2").innerText = avg2;


texts:
I've written this relatively simple class to help with managing arrays of anonymous objects in my scripts.

/**
* AoHandler - accepts an array of objects or creates a new array
* @param {array} ao
*/
function AOHandler(ao)
{
    this.ao = typeof ao === 'object' ? ao : [];

    /**
    * pluck()
    * @param {object} search
    * @param {boolean} retKey
    */
    this.pluck = function (search, retKey)
    {
        for (i = 0; i < this.ao.length; i++ )
        {
            var tmpObj = this.ao[i];

            if (tmpObj[search.key] == search.value)
            {
                return (retKey === true) ? i : tmpObj;
            }
        }
        return false;
    }
}

/**
* get()
* @param {object} search
* @return first matching object in ao array or false on failure
*/
AOHandler.prototype.get = function(search)
{
    return this.pluck(search);
}

/**
* add()
* @param {object} pushObj
* @return false on failure
*/
AOHandler.prototype.add = function(pushObj)
{
    return typeof pushObj === 'object' ? this.ao.push(pushObj) : false;
}

/**
* update()
* @param {object} search
* @param {object) updObj
* @param {boolean} merge
*/
AOHandler.prototype.update = function(search, updObj, merge)
{
    var key = this.pluck(search, true);

    if (merge === true && key !== false)
    {
        $.extend(this.ao[key], updObj);

        return true;
    }
    else if (key !== false)
    {
        this.ao[key] = updObj;

        return true;
    }

    return false;
}

/**
* remove()
* Finds the array item and removes it from the array
* @param {object} search
* @return first matching object in ao array
*/
AOHandler.prototype.remove = function(search)
{
    var key = this.pluck(search, true);

    return key !== false ? this.ao.splice(key, 1) : false;
}

Usage

var aoArray = new AOHandler();

aoArray.add({
    id : '50ef3ac',
    name : 'example',
});

aoArray.add({
    id : '50ef3ad',
    name : 'A new object'
});

var searchFor = {
    key : 'id',
    value : '50ef3ad'
}

console.log(aoArray.get(searchFor);

I'm unhappy with the one jQuery call with $.extend() but this proved the easiest way to accomplish an object merge and I use jQuery quite predominantly in the majority of my projects. Despite that can anyone suggest a different way to do this?

While this works fine I know it's far from perfect as it's limited to one search term. My thought was to add in another loop within pluck() but I'd prefer to avoid doing that, my second thought was to map the object and perform the lookup once I'd found an object with the first property match. Again any suggestions on how I might accomplish this whilst keeping the script clean and fast I'd really appreciate it.

Any other suggestions welcome, thank you for taking a look. :)


texts: How to refactor that content_tag adding method?

texts:
How to get rid of that duplicaiton in if conditional?

def set_caption(result)
  if result.respond_to?(:app_name)
    content_tag(:div, result.type_name, class: 'type-name') +
      content_tag(:div, result.app_name, class: 'app-name')
  else
    content_tag(:div, result.type_name, class: 'type-name')
  end
end


texts: Overriding the mouseout handler for an image when a button is clicked

texts:
I had posted this question in Stack Overflow and they told me it would be better served on Code Review.

Is there a more effecient way of changing the mouseout state when a button is clicked? When a button is clicked I want the image in the click event to take precedence over the image in the mouseout event. The following code works but I'm not sure if nesting events is a good practice.

$("#targetBtn").on({
  "mouseover" : function() {
    $(this).find('img').attr('src', 'images/_hover.png');
  },
 "mouseout" : function() {
    $(this).find('img').attr('src', 'images/_mouseout.png');
 },
 "click" : function() {
   $(this).find('img').attr('src', 'images/_selected.png');
   $(this).mouseout(function() {
      $(this).find('img').attr('src', 'images/_selected.png');
   });
  }
});

If anyone could refactor this code and show me a better way of doing this it would be greatly appreciated. Also if someone could explain why nesting events is bad (if indeed it is) I would appreciate that as well.


texts:
This program attempts to solve the following challenge:

  There is a 2D grid of cells containing N lamps. Each lamp illuminates its own cell as well as its eight neighbours.  How many lamps can you possibly remove such that each cell that was originally illuminated remains illuminated?

My code:

import java.util.*;

class test
{
    public static void main(String[] ar)
    {
        int use = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the dimensions: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int[][] f = new int[a][b];
        System.out.print("Enter the no. of lamps: ");
        int n = sc.nextInt();
        int[][] l = new int[n][2];
        //System.out.print("Enter the coordinates : ");
        for(int i = 0; i < n; i++)
        {
            int t1,t2;
            do
            {
            t1 = l[i][0] = (int)(Math.random()*a);
            t2 = l[i][1] = (int)(Math.random()*b);
            f[t1][t2] = 1;
        }while(f[t1][t2] == 0);
        }
        print(f);
        light(f);
        for(int i = 0; i < l.length; i++)
        {
            int[][] f1 = new int[a][b];
            for(int j = 0; j < l.length; j++)
            {
                if(i == j)
                    continue;
                int x = l[j][0];
                int y = l[j][1];
                if(x < 0)
                    continue;
                f1[x][y] = 1;
            }
            light(f1);
            if(!same(f,f1))
                use++;
            else
            {
                l[i][0] = -1;
                l[i][1] = -1;
            }
        }
        System.out.println("Usefull : " + use);

    }

    public static boolean same(int[][] a, int[][] b)
    {
        for(int i = 0; i < a.length; i++)
        {
            for(int j = 0; j < a[i].length ; j++)
            {
                if(a[i][j] != b[i][j])
                    return false;
            }
        }
        return true;
    }

    public static void print(int[][] a)
    {
        for(int i = 0; i < a.length ; i++)
        {
            for(int j = 0; j < a[i].length; j++)
                System.out.print(a[i][j] + " ");
            System.out.println();
        }
        System.out.println();
    }

    public static void light(int[][] a)
    {
        for(int i = 0;i < a.length; i++)
        {
            for(int j = 0; j < a[i].length; j++)
            {
                if(a[i][j] == 1)
                    light(a,i,j);
            }
        }
        convert(a);
    }

    public static void light(int[][] a, int i, int j)
    {
        for(int p = i - 1; p <= i + 1; p++)
        {
            for(int q = j - 1; q <= j + 1; q++)
            {
                try
                {
                    if(a[p][q] != 1)
                        a[p][q] = 2;
                }catch(Exception e){}
            }
        }
    }

    public static void convert(int[][] a)
    {
        for(int i = 0; i < a.length; i++)
        {
            for(int j = 0; j < a[i].length; j++)
            {
                if(a[i][j] == 2)
                    a[i][j] = 1;
            }
        }
    }
}

Please help to improve my code.


texts: Temperature converter in Rust with input error handling

texts:
I started learning Rust a few hours ago with the Rust Book (2018 edition) and as part of one of the exercises decided to make a temperature converter. I wanted to make sure it handled all inputs properly in an idiomatic fashion. The code is as follows:

use std::io;
use std::io::Write;
use std::str::FromStr;

fn main() {
    println!("Welcome to the temperature converter!");

    println!("Pick a conversion:");
    println!("[1] Fahrenheit to Celsius");
    println!("[2] Celsius to Fahrenheit");

    let choice: u32 = loop {
        let value = read_value_from_input("> ", "Please enter a valid integer!");

        if value == 1 || value == 2 {
            break value;
        }
        println!("Please enter a valid choice (0 or 1)!");
    };

    if choice == 1 {
        let temperature: f64 = read_value_from_input("Enter the temperature to convert: ",
            "Please enter a valid floating point variable!");

        println!("{:.2} °F is {:.2} °C.", temperature, (temperature - 32f64) * 5f64 / 9f64);

    } else if choice == 2 {
        let temperature: f64 = read_value_from_input("Enter the temperature to convert: ",
            "Please enter a valid floating point variable!");

        println!("{:.2} °C is {:.2} °F.", temperature, temperature * 9f64 / 5f64 + 32f64);

    } else {
        println!("{} was not a valid choice!", choice);
    }
}

fn read_value_from_input<T: FromStr>(prompt: &str, error_message: &str) -> T {
    let result: T = loop {
        print!("{}", prompt);
        io::stdout().flush().expect("Unable to flush STDOUT!");

        let mut input_value = String::new();

        io::stdin().read_line(&mut input_value)
            .expect(error_message);

        match input_value.trim().parse() {
            Ok(value) => break value,
            Err(_) => {
                println!("{}", error_message);
                continue;
            }
        }
    };
    result
}

Here are the things I want to know from this code review:

Is my code idiomatic Rust? Does it follow its coding conventions, style, etc.?
Does my code handle all erroneous inputs properly?
Can the code be shortened or optimized in any way?


texts: Custom strcat() with different arguments

texts:
I am teaching myself C, and feel like I am just starting to get the hang of pointers and arrays (I come from Python, where everything is magic).  I'm looking for reviews, especially if I'm doing anything wrong.  In this code I wrote my own strcat() function, though it needs 3 args instead of the standard 2 (I couldn't figure out how to do it with just 2 without overrunning allotted memory).

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

char* cat(char *dest, char *a, char*b)
{
    int len_a = strlen(a);
    int len_b = strlen(b);
    int i;
    for(i = 0; i < len_a; i++)
    {
        dest[i] = a[i];
    }
    puts("");
    int j;
    for(j = 0;j < len_b; i++, j++)
    {
        dest[i] = b[j];
    }
    dest[i] = '\0';
    puts("FUNCTION FINISHED");
}

int main()
{
    char strA[] = "I am a small ";
    char strB[] = "cat with whiskers.";
    char strC[strlen(strA) + strlen(strB) + 1];
    printf("length A: %lu, B: %lu, C: %lu\n", strlen(strA), strlen(strB), strlen(strC));
    printf("sizeof A: %lu, B: %lu, C: %lu\n", sizeof(strA), sizeof(strB), sizeof(strC));
    printf("A: '%s'\nB: '%s'\n", strA, strB);
    cat(strC, strA, strB);
    printf("c: '%s'\n", strC);
    printf("length A: %lu, B: %lu, C: %lu\n", strlen(strA), strlen(strB), strlen(strC));

    return 0;
}


texts: Python: improve in elegant way (code saving) a function in order to avoid several statements

texts:
I wrote this function to read Las file and save a shapefile. The function creates a shapefile with 8 fields. What I wish insert a parse element in the function in order to select the fields I wish to save LAS2SHP(inFile, outFile=None, parse=None). If parse=None all fields are saved. If  parse="irn" the fields intensity, return_number, and number_of_returns are saved, following the legend:

"i": p.intensity,
"r": p.return_number,
"n": p.number_of_returns,
"s": p.scan_direction,
"e": p.flightline_edge,
"c": p.classification,
"a": p.scan_angle,

I wrote a solution if....ifelse....else really code consuming (and not elegant). Thanks for all helps and suggestions for saving code.

Here is the original function in Python:

import shapefile
from liblas import file as lasfile

    def LAS2SHP(inFile,outFile=None):
        w = shapefile.Writer(shapefile.POINT)
        w.field('Z','C','10')
        w.field('Intensity','C','10')
        w.field('Return','C','10')
        w.field('NumberRet','C','10')
        w.field('ScanDir','C','10')
        w.field('FlightEdge','C','10')
        w.field('Class','C','10')
        w.field('ScanAngle','C','10')
        for p in lasfile.File(inFile,None,'r'):
            w.point(p.x,p.y)
            w.record(float(p.z),float(p.intensity),float(p.return_number),float(p.number_of_returns),float(p.scan_direction),float(p.flightline_edge),float(p.classification),float(p.scan_angle))
        if outFile == None:
            inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
            inFile_name = os.path.splitext(inFile_name_ext)[0]
            w.save("{0}\\{1}.shp".format(inFile_path,inFile_name))
        else:
            w.save(outFile)


texts: Generating 2 comma-separated lists from list of key value pairs

texts:
Could this code:

var a = new StringBuilder();
var b = new StringBuilder();
var kvps = new List<KeyValuePair<Guid, object>>
{
    new KeyValuePair<Guid, object>(Guid.NewGuid(), 1),
    new KeyValuePair<Guid, object>(Guid.NewGuid(), "hello")
};
for (var c = 0; c < kvps.Count; c++)
{
    a.Append(kvps[c].Key);
    b.Append(kvps[c].Value);
    if (c >= kvps.Count - 1) continue;
    a.Append(",");
    b.Append(",");
}

be improved in terms of performance to achieve this:

a = e1b7978c-127f-4a5f-a17b-737e03484172,cbbd1573-950c-4ca4-94b7-72a08b4a61d0
b = 1,hello


texts: Composing and executing a customer search

texts:
I was wondering if someone could help me refactor this code. Although I know this looks bad, it works. Now I would like to refactor it so I would respect the open/closed principle in SOLID. Let's say the client wants a new search field to search data on, then I need to come to this method and add it in and this breaks the O/C principle. How would you guys change this?

public List<Customer> Search(Search searchData){
using(context)
{
    var query = context.Customers;

    if(!string.NullOrEmpty(searchData.FirstName)
        query.Where(c => c.FirstName == searchData.FirstName);

    if(!string.NullOrEmpty(searchData.LastName)
        query.Where(c => c.LastName == searchData.LastName);

    if(!string.NullOrEmpty(searchData.StreetName)
        query.Include(c => c.Address);
        query.Where(c => c.Address.StreetName == searchData.StreetName);

    if(!string.NullOrEmpty(searchData.PostCode)
        query.Include(c => c.City);
        query.Where(c => c.City.PostCode == searchData.PostCode);

    var customers = query.ToList();
    return customers;
}    }


texts:
For a school project, I had to make a keylistener that would output whatever you typed to the screen. A JFrame would be initialized to have the focus required for the listener to work. It uses delete and shift methods to determine what to type/delete. Is there any way to make this more efficient, since I have two methods that I don't use and just take up space? Any and all help is appreciated!

import javax.swing.*;
import java.awt.event.*;

public class KeyHandler implements KeyListener {
    /*
     * KEY FUNCTIONS:
     * k.getKeyCode() returns ascii number
     * k.getKeyChar() returns char typed
     *
     * KEY CODES:
     * [delete] 8
     * [shift] 16
     */
    private String output;

    public KeyHandler() {
        this.output = "";
    }

    public void keyPressed(KeyEvent k) {
        if(k.getKeyCode() != 8) {
            if(k.getKeyCode() != 16) {
                this.output += k.getKeyChar();
            }
        } else {
            if(this.output.length() - 1 < 0) {
                //do nothing
            } else {
                this.output = this.output.substring(0,this.output.length() - 1);
            }
        }
        this.print();
    }
    public void keyReleased(KeyEvent k) {}
    public void keyTyped(KeyEvent k) {}

    public void print() {
        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.output);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("KeyEvent Handler");
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(new KeyHandler());
        frame.setVisible(true);
    }
}