texts:
I'm workin on this code that will be a licensing class integrated with an electron app. For now it's a simple object who will generate and check for a licence stored inside the electron app folder. I want to improve it before implementing it inside my projects. Using this class it's simple: It will check for a valid licence file inside a predefined folder, if the file not exist, the class will generate one for using a trial version of the app. It's not perfect, but for now it work as expected. Any suggestion will be appreciated.

<?php
if(!defined('ABSPATH')){
  define('ABSPATH', __DIR__);
}

class Activator{

  private $uuid;
  private $licence_code;
  private $machine_uuid;
  private $current_date;
  private $start_date;
  private $end_date;
  private $timezone;

  public static function generateLicence($uuid){

    if(!file_exists(ABSPATH.'/DataStorage/.licence')){
      $timezone    = new DateTimeZone('Europe/Rome');
      $start_date  = new DateTime("now", $timezone);
      $end_date  = new DateTime("+30 days", $timezone);
      $machine_uuid = $uuid;
      $licence_code = hash('sha384', $machine_uuid);

        $licence_file = array(
          'uuid' => $machine_uuid,
          'activation_date' => $start_date->format('d-M-Y'),
          'expire_date' => $end_date->format('d-M-Y'),
          'trial_version' => true,
          'licence_code' => $licence_code
        );

        $w = file_put_contents(ABSPATH.'/DataStorage/.licence' ,json_encode($licence_file));
        echo $w;
    }

  }

  public function checkLicence($uuid){
    if(!file_exists(ABSPATH.'/DataStorage/.licence')){

      return;
    }
    else{
      $current_date  = new DateTime('now');
      $licence_file = json_decode(file_get_contents(ABSPATH.'/DataStorage/.licence'), true);
      $licence_code = $licence_file['licence_code'];
      $licence_check = hash_equals($licence_code, hash('sha384', $uuid));
        if($licence_check){
          if($current_date->format('d-M-Y') != $licence_file['expire_date']){
            return 'OK';
          }
          else{
            return 'EXPIRED';
          }
        }
    }
  }

}
// usage example with an AJAX call:
if(isset($_POST['uid'])){
  $system_id = $_POST['uid'];
  echo Activator::checkLicence($system_id);

}

?>


texts: Merging IEnumerable and removing duplicates

texts:
I have a method that exacts data from an XML and returns an IEnumerable<Foo>.  I am trying to create a method that will merge the results from 2 different XML's files into a single IEnumerable and remove any duplicate data that may be found

A duplicate in this case is defined as 2 Foo objects that have the same Name property even if the other data is different.  If there is a duplicate, I always want to keep the Foo from the first IEnumerable and discard the 2nd.

Am I on the right track with this LINQ query, or is there a better way to accomplish what I am trying to do?

public IEnumerable<Foo> MergeElements(XElement element1, XElement element2)
{
    IEnumerable<Foo> firstFoos = GetXmlData(element1); // get and parse first set
    IEnumerable<Foo> secondFoos = GetXmlData(element2); // get and parse second set

    var result = firstFoos.Concat(secondFoos)
                          .GroupBy(foo => foo.Name)
                          .Select(grp => grp.First());

    return result;
}

The biggest concern I have with this code is that I am not certain the duplicate filtering rules I want will be guaranteed.  I know Concat will just append secondFoos to the end of firstFoos, but when calling GroupBy(), will the resulting IGrouping object always have elements in the same order as the source data?


texts: Calling a global popup from nested vue components

texts:
I have tons of nested Vue components that need to be able to open a global modal. To avoid having tons of listeners and emitters snaking their way all through the app, I am using VueX. The main App has a modal which gets shown if the modal state is not undefined.

Root app template

<template>
   <components></components>
   <popup v-if="popupImage" :image="popupImage"></popup>
</template>

Root app script

import { State } from 'vuex-class'
@State(state => state.popupImage) popupImage:string

Nested component

From within a component I set the popup string, which will trigger the global modal:

this.$store.commit("setPopup", "bla.jpg")

It all works fine, but does it seem a bit overkill to add VueX ONLY for a modal window? The rest of the app doesn't use VueX at all. What is the recommended way to open a modal from anywhere in a Vue app?


texts: Repeatedly keep removing 2 smallest elements and add its sum back to the list and return newly inserted elements' total

texts:
I have a list of unsorted numbers. Each time, I need to remove 2 smallest numbers and insert back its sum into the list. Repeatedly do this till the 1 final element is remaining in the list.

Return the total sum of newly inserted elements

My logic was to use heap sort, remove 2 elems, insert elems sum back - repeat.

This program of input of 10 elements has called heapify function 310 times!

Link: http://cpp.sh/8vkjd

How do I optimize this scenario?

Use Binary Search Tree?
Use Heap Sort on LinkedList?
Is this possible with graphs?
Since there are several insertions, I'm trying to only restrict to O(N) or \$O(\log N)\$ or \$O(n \log N)\$ insertion.
Can this be done with 2 lists?
Since the elements will be sorted after the 1st iteration, is there a good insertion algorithm that does faster insertion?

#include <iostream>
#include <sstream>
#include <vector>
int count = 0; // A global variable to keep track of number of time heapify function is called
void heapify(std::vector<int> &arr, int n, int i)
{
   count++;
   int largest = i;
   int l = 2*i + 1;
   int r = 2*i + 2;

   if(l<n && arr[l] >arr[largest])
       largest = l;

   if(r<n && arr[r] > arr[largest])
       largest = r;

   if(largest != i)
   {
       std::swap(arr[i], arr[largest]);
       heapify(arr, n, largest);
   }
}

void heapSort(std::vector<int> &arr, int n)
{
   for(int i=n/2 -1 ; i>=0 ; i--)
   {
       heapify(arr,n,i);
   }

   for(int i=n-1 ; i>=0 ; i--)
   {
       std::swap(arr[0],arr[i]);
       heapify(arr,i,0);
   }

}

void printArray(std::vector<int> &arr, int n)
{
   for(int i=0 ; i<n ; i++)
   {
       std::cout << arr[i] << " ";
   }
   std::cout << std::endl;
}

int main()
{
   std::vector<int> arr{1,2,3,4,5,6,7,8,9,10};
   int n = arr.size();
   printArray(arr,n);
   heapSort(arr,n);

   int ans=0;
   int tempEle=0;
   while(arr.size()>1)
   {
       heapSort(arr,n);
       tempEle = arr[0]+arr[1];
       arr.erase(arr.begin(),arr.begin()+2);
       ans+=tempEle;
       arr.push_back(tempEle);
       printArray(arr,arr.size());
   }
   ans+=arr[0];

   std::cout << "Repeatedly adding all elements, 2 small elements at a time and reducing it to a single number : " << ans << std::endl;

   std::cout << "Heapify was called " << count << " times" << std::endl;
   return 0;
}

And for an input of 5000 numbers, the heapify() func is being called 246 million times.


texts: Recursive function to get all Zendesk tickets

texts:
I'm developing a Python library to consume the Zendesk search API.
Problem is, Zendesk limits search results to 1000 items. Thus in order to get all the results if they are greater than 1000 I need to call the endpoint several times with a recursive function storing the latest created datetime for a ticket once the 1000 limit is reached.

My code at the moment works but it feels wrong. Could you help me to improve this recursive function? For instance I'd prefer not to declare an empty list at the constructor but instead inside the function.

Here is the code:

init.py

import requests
import base64
from zdesktools.lib.api import SearchApi, TicketsApi

class ZdeskTools(object):
    def __init__(self, zendeskApiUrl=None,
                 username=None,
                 password=None):
        session = self._begin_session(username, password)
        config = {
            'zendeskApiUrl': zendeskApiUrl,
            'session': session
        }
        self.search = SearchApi(**config)
        self.tickets = TicketsApi(**config)
        # self.metrics = MetricsApi(**config)

    def _begin_session(self, username, password):
        session = requests.Session()
        username_password = f'{username}/token:{password}'
        encoded_bytes = base64.b64encode(username_password.encode('utf-8'))
        encoded_string = str(encoded_bytes, 'utf-8')
        headers = {
            'Authorization': f'Basic {encoded_string}'
        }
        session.headers.update(headers)
        return session

api.py

from urllib.parse import urlencode
import json
import pprint

class SearchApi(object):
    def __init__(self, **config):
        self.session = config.get('session')
        self.url = config.get('zendeskApiUrl')+'/search.json?'
        self.created_at = []
        self.tickets = []

    def get_ticket_numbers(self, search_params):
        response = self.session.get(f'{self.url}{urlencode(search_params)}')
        data = response.json()
        if 'results' in data:
            for result in data['results']:
                self.created_at.append(result['created_at'])
                self.tickets.append(result['id'])
        if 'next_page' in data:
            if data['next_page'] is not None:
                self.url = data['next_page']
                self.get_ticket_numbers(search_params)
        else:
            self.url = self.url[:self.url.index('?')+1]
            search_params['query'] = search_params['query'] + \
                f' created_at>={self.created_at[-1]}'
            self.get_ticket_numbers(search_params)
        return self.tickets


texts:
I have the code below and I am looking for input as to how I can improve it.

The main question here is should the code at the top in razor brackets be moved to the Controller and returned via a ViewModel?

The underlying question being, particularly when the code isnt controling styling is should the endeavour be to have as much as the C# code inside the controller as much as possilble, which i feel i am good at doing, and getting better at despite a few areas of lazyness.

@{
    var show = ViewBag.ShowBasket == "true";

    var visiblityLg = show ? "visible-lg" : "hidden hidden-lg";
    var visiblityMd = show ? "visible-md" : "hidden hidden-md";
    var visiblitySm = show ? "visible-sm" : "hidden hidden-sm";
    var visiblityXs = show ? "visible-xs" : "hidden hidden-xs";
}

    &nbsp;Shopping Basket


texts: REST API calls to BIG-IP LTM to get the status of pool members

texts:
This code calls the iControl REST API provided by BIG-IP LTM. Trying to get the list of the pools, it's current status and the pool members associated with the pool.

My code works like this, based on three calls:

Get the pool names (/mgmt/tm/ltm/pool)
Based on the pool names (path), get its status (mgmt/tm/ltm/pool/~pool~name/stats)
Based on the pool names (path), get its pool members (/mgmt/tm/ltm/pool/~pool~names/members)

If I do only the first call, I get the output within milliseconds. After adding the second call, it becomes worse. With a third call, it takes good amount of time (more than 6 minutes) to get all the output for about 400 pools.

How can I optimize this code?

import requests
from requests.auth import HTTPBasicAuth

BASE_URL = "https://localhost/mgmt/tm"
username = "admin"
password = "admin"

def makeRequest(username, password, url):
    response_data = requests.get(url, auth = HTTPBasicAuth(username, password), verify = False)

    return response_data.json()

pool_data = makeRequest(username, password, BASE_URL + "/ltm/pool")

for pools in pool_data['items']:
    print pools['name']
    tildPath = pools['fullPath'].replace('/','~')

    #GET the Pool stats
    pool_stats = makeRequest(username, password, BASE_URL + "/ltm/pool/" + tildPath + "/stats")
    print pool_stats['entries']['status.availabilityState']['description']

    #GET the Pool Members
    pool_members = makeRequest(username, password, BASE_URL + "/ltm/pool/" + tildPath + "/members")

    for members in pool_members['items']:
        print members['name'] +" " + members['address'] + " " + members['state']


texts:
I'm using the following function to process API parameters for an specific endpoint. Using SQLAlchemy and Flask, I want to get feedback in terms of simplifying calling SQL code and nested statements.

date_filter = r'\d{4}-((1[0-2]|[1-9])|0[1-9])-((3[01]|[12][0-9]|[1-9])|0[1-9])'

def bits_filter(request):
    """

    :param request:
    :return:(Model.Bits) List of bits
    """
    # Get parameters.
    log.info('/bits request: %s', request)
    # Date parameters.
    date_value = request.args.get('date')
    # Bit or newsletter.
    bit_type_value = request.args.get('bit_type')

    # Process parameters.
    date_value = date_value or settings.DATE_VALUE
    bit_type = bit_type_value or settings.BIT_TYPE
    log.info('bit_type: %r', bit_type)

    if date_value and isinstance(date_value, unicode):
        # Bit type.
        if date_value.lower() == u'latest':
            return Model.Bits.query.filter(Model.Bits.bit_type == bit_type).order_by(
                Model.Bits.published.desc()).limit(settings.max_bits).all()
        # Dated format.
        elif re.match(date_filter, date_value):
            return Model.Bits.query.filter(
                Model.Bits.bit_type == bit_type & Model.Bits.published == date_value).limit(
                settings.max_bits).all()
        else:
            log.error('Invalid date value parameter: %r', date_value)
            return None
    else:
        return Model.Bits.query.filter(Model.Bits.bit_type == bit_type).order_by(
            Model.Bits.published.desc()).limit(settings.max_bits).all()


texts:
I have a Character model that has a CharClass and ClassPerks child.

Currently I am duplicating my logic a lot by manually assigning data.

My Character index and create:

def index

    @campaign = Campaign.find_by_id(params[:campaign_id])
    @characters = @campaign.characters
    render json: {
        characters: @characters
    }
end

def create
    @campaign = Campaign.find_by_id(params[:campaign_id])
    @charClass = CharClass.find_by_id(params[:character_char_class_id])
    @character = @campaign.characters.new(character_params)
    @character.char_class_id = params[:character_char_class_id]

    if @character.save!
        render status: 201, json: {

            message: "Successfull added this character to the campaign!",
            character_name: @character.character_name + ' the ' + @charClass.class_name,
            character_class: @charClass.class_name,
            character_level: @character.character_level,
            character_experience: @character.character_experience,
            character_gold: @character.character_gold,
            character_perks: get_names(@character.character_perks),
            character_image: @character.character_image

        }
    else
        render status: 404, json: {
            message: "Something went wrong: Check line 24 of the Character Controller"
        }
    end
end

I am manually assigning character_class and character_image despite both of these ALWAYS being the same based on their character_class.

Inside of the character.rb I am doing this to assign them post-create:

    after_create :add_perks, :save_class

    def add_perks
        self.class_perks.each do |perk|
            self.character_perks.create(class_perk_id: perk.id)
        end
    end

    def save_class()
        case self.char_class_id
            when 1 # Mindthief
                self.character_image = "https://gloomhavenil.files.wordpress.com/2017/12/11849117_616974988445216_217288420_n.jpg?w=480"
                self.character_class = "Mindthief"
                self.save
            when 2 # Tinkerer
                self.character_image = "http://www.cephalofair.com/wp-content/uploads/2015/04/Quatryl-Tinkerer.jpg"
                self.character_class = "Tinkerer"
                self.save
            # when 'Sawbones'
            # else
        end
    end
end

It is working, but I am unsure how to do this better/appropriately. I removed useless fields but you'll see below I have the relations set up appropriately.

  create_table "char_classes", force: :cascade do |t|
    t.string "class_name"
    t.string "class_image"
    t.string "class_perks"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

 create_table "characters", force: :cascade do |t|
    t.string "character_class"
    t.string "character_image"
    t.integer "char_class_id"
    t.index ["campaign_id"], name: "index_characters_on_campaign_id"
    t.index ["char_class_id"], name: "index_characters_on_char_class_id"
  end

I can do Character.first.char_class.class_name and I will get the appropriate result; so I am back to assuming this method I'm following is very incorrect.


texts: Running an UPDATE SQL QUERY within VBA using DAO

texts:
I have a macro in Excel that updates a recordset using WHERE a primary key in MS Access matches a primary key in a UserForm label value. The macro is called from a Userform command button, this command button also writes about 10 different UserForm textbox values back to MS ACCESS and to a Sheet in Excel. My query in MS ACCESS is using PARAMETERS as well.

I find that at times my UPDATE query takes a little longer to run, and Excel will freeze. Experts, is there anything missing from my code that I should be executing?

UPDATE SQL MACRO

Sub ClientUpdate ()
Dim db As Database
Dim qdf As QueryDef

Application.StatusBar = "Connecting to PBS Database......"
Set db = OpenDatabase("M:\Admin Vision\PBS BackUP Database\Database15.mdb")
Set qdf = db.QueryDefs("pbsupdate")

Application.StatusBar = "Uploading Client Data to PBS server...."
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

    qdf!pbskey = dialer.key
    qdf!pbsclient = dialer.client
    qdf!pbspriority = dialer.priority_
    qdf!pbssource = dialer.priority
    qdf!pbslastcontact = dialer.contact
    qdf!pbsresult = dialer.result
    qdf!pbsnextsteps = dialer.segmentType
    qdf!pbsattempts = dialer.Label11 + 1
    qdf!pbsnotes = dialer.notes

 Application.CalculateUntilAsyncQueriesDone

         qdf.Execute dbFailOnError

qdf.Close
db.Close
Application.StatusBar = "Upload Successful!"

Set qdf = Nothing
Set cdb = Nothing

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

USERFORM CODE

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim Ws As Worksheet: Set Ws = wb.Sheets("clientmenu")
Dim lastrow As Long
Dim CellRow As Integer    ' create a variable to hold the cell row

CellRow = ActiveCell.Row
x = Me.lblRow
CurrentRow = ActiveCell.Row

    If contact.Value <> "" And result.Value = vbNullString Then
        MsgBox "Please enter a result"
        result.BorderColor = vbRed
        result.BackColor = vbYellow
        result.DropDown

    Exit Sub

    ElseIf contact.Value = vbNullString And result.Value <> "" Then

        MsgBox "Please enter a date"
        contact.BorderColor = vbRed
        contact.BackColor = vbYellow

Exit Sub
End If

    ClientUpdate '///calling UPDATE SQL MACRO

    Unload Me

With Sheet3
lastrow = Sheet3.Range("A" & Rows.Count).End(xlUp).Row + 1

If Me.priority_ = vbNullString Then

    .Cells(x, 2).Interior.Color = vbWhite
    .Cells(x, 2).Font.Color = RGB(0, 0, 0)

ElseIf Me.priority_ = "None" Then

    .Cells(x, 2).Interior.Color = vbWhite
    .Cells(x, 2).Font.Color = RGB(0, 0, 0)
    .Cells(x, 3).Value = vbNullString

ElseIf Me.priority_ = "High" Then

    .Cells(x, 2) = Me.priority_.Text
    ElseIf Me.priority_ = "Medium" Then

    .Cells(x, 2) = Me.priority_.Text
    ElseIf Me.priority_ = "Low" Then

    .Cells(x, 2) = Me.priority_.Text

End If

        .Cells(x, 2) = Me.client.Text
        .Cells(x, 4) = Me.priority.Text
        .Cells(x, 9) = Me.notes.Text
        .Cells(x, 7) = Me.segmentType.Text

If Me.contact.Value = vbNullString Then

    Exit Sub
Else

    .Cells(x, 5) = Me.contact.Value

End If

    .Cells(x, 6) = Me.result.Text

If Me.contact = vbNullString Then

    ElseIf Me.contact <> vbNullString Then

    .Cells(x, 8) = .Cells(x, 8) + 1

End If

    End With

    callbyMonth 'filters call by months
    callsByDay  'filters calls by day
    callsByWeek 'filters calls by week

Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub


texts:
I have come up with an idea for adding privacy support in JavaScript. I haven't found something similar in the net, so I'm thinking it's probably because the idea is bad, but yet, I want to see some response, just to be sure.

var util = {
    s4: function() {
        return Math.floor((1 + Math.random()) * 0x10000)
                    .toString(16)
                    .substring(1);
    },

    guid: function() {
        return util.s4() + util.s4() + '-' + util.s4() + '-' + util.s4() + '-' +
                util.s4() + '-' + util.s4() + util.s4() + util.s4();
    }
};

// template
var Class = (function() {
    var privates = {};
    var getPrivates = function(obj) {
        return privates[ obj.getGUID() ];
    };

    function Class() {
        var guid = util.guid();
        privates[guid] = {};
        this.getGUID = function() {
            return guid;
        };
    };

    return Class;
})();

var MyClass = (function() {
    var privates = {};
    var getPrivates = function(obj) {
        return privates[ obj.getGUID() ];
    };

    function MyClass(a, b) {
        var guid = util.guid();
        privates[guid] = {};
        this.getGUID = function() {
            return guid;
        };

        var private = getPrivates(this);
        private.a = a;
        this.b = b;
    };

    return MyClass;
})();

var obj = new MyClass("private", "public");
console.log(obj.a, obj.b);


texts: This snippet of scheme calculates a value in pascal's triangle

texts:
I'm working through SICP and have implemented exercise 1.11 (Pascal's Triangle). What I'm curious about here is performance considerations by defining functions within the main function. I would assume they get reassigned with each invocation of the function. In saying that, this style appeals to me, as the functionality is scoped to the main function, and lexical scoping is used to effect. Obviously I'm a scheme noob so please go nuts in tearing this code apart.

(define (pascal-value row elem)

  (define (out-of-range?)
    (or (> elem row) (< elem 1)))

  (define (edge?)
    (or (= row elem) (= elem 1)))

  (cond ((edge?) 1)
        ((out-of-range?) 0)
        (else (+ (pascal-value (- row 1) (- elem 1))
                 (pascal-value (- row 1) elem)))))


texts: Using finally with return statement or not

texts:
I was wondering if it is the proper way to always put the return statement of a function with a try-catch clause in the finally clause.

I have for example this function which returns the version of an sql server:

public String getVersion() {
        String version = new String();
        final String query = "Select VERSION()";
        Connection con = null;
        Statement stmt = null;

        try {
            Helper.println("Getting driver...");
            Class.forName(_driver);

            Helper.println("Connecting to database...");
            con = DriverManager.getConnection(_url, _user._username, _user._password);
            stmt = con.createStatement();

            Helper.println("Executing query...");
            ResultSet rs = stmt.executeQuery(query);
            rs.next();
            version = rs.getString(1);
        } catch (SQLException se) {
            Helper.printErrln("SQL Error: " + se.getErrorCode() + ' ' + se.getMessage());
        } catch (ClassNotFoundException e) {
            Helper.printErrln("Driver Error: " + e.getMessage());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se) {
            }
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException se) {
            }
            return version;
        }
    }

I return the version variable always in the finally clause in situations like these and it particularly convenient when I need to return a list because if something went wrong then I will just be left with an empty list which I prefer. For example:

public List<String> getDatabases() {
        List<String> databases = new ArrayList<>();
        Connection con = null;
        Statement stmt = null;

        try {
            Helper.println("Getting driver...");
            Class.forName(_driver);

            Helper.println("Connecting to database...");
            con = DriverManager.getConnection(_url, _user._username, _user._password);
            stmt = con.createStatement();

            Helper.println("Finding Databases...");
            ResultSet rs = con.getMetaData().getCatalogs();

            while (rs.next()) {
                databases.add(rs.getString("TABLE_CAT"));
            }
        } catch (SQLException se) {
            Helper.printErrln("SQL Error: " + se.getErrorCode() + " " + se.getMessage());
        } catch (ClassNotFoundException e) {
            Helper.printErrln("Driver Error: " + e.getMessage());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se) {
            }// do nothing
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException se) {
            }
            return databases;
        }
    }

So first of all my question is: Is what I am doing proper or can it cause problems that I have not anticipated? Also what if I wanted to encapsulate the function and have it trow the exception to the parent class for handling, how would the return be handled then?


texts: Converting string elements of an array to upper and lower case, maintaining names of keys

texts:
I'm just going through some array exercises in PHP on w3resource. I have just completed:

Sample array :
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
Expected Output :
Values are in lower case:
Array ( [A] => blue [B] => green [c] => red )
Values are in upper case:
Array ( [A] => BLUE [B] => GREEN [c] => RED )

Here is my answer:
<?php
    echo "
";

    $Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');

    echo "Sample array:
";
    print_r($Color);

    function toLower($value)
    {
        return strtolower($value);
    }

    function toUpper($value)
    {
        return strtoupper($value);
    }

    echo "
Values are in lower case:
";
    print_r(array_map("toLower", $Color));

    echo "
Values are in upper case:
";
    print_r(array_map("toUpper", $Color));

    echo "
";
?>

And its output:
Sample array:
Array
(
    [A] => Blue
    [B] => Green
    [c] => Red
)

Values are in lower case:
Array
(
    [A] => blue
    [B] => green
    [c] => red
)

Values are in upper case:
Array
(
    [A] => BLUE
    [B] => GREEN
    [c] => RED
)

Some questions:

Originally I thought about using implode to convert the elements to a string and then set the case of the entire string before explodeing back to an array; but of course this loses the names of the keys (A, B, c). Is there any possible way to somehow use implode and explode to get around this (convert to string while somehow keeping key names in memory)?

As the questions call explicitly for a function rather than a program, should this sort of operation be done with one function rather than the two which I have implemented here?

Is this an appropriate usage of array_map?

w3resource's sample answer makes use of statements involving is_array. Is it good practise to implement such guard conditions in my own code at this point?

Is there anything about my code which looks strange to you, or could easily be improved?


texts: Recreate Mario's half-pyramids using hashes (#) from CS50

texts:
I currently working on CS50. There is a problem where we need to recreate half-pyramids using hashes (#). The hashes are to substitute blocks like in Mario.
This is also the first time I'm using Python. I don't really know Python. So I just try to calculate myself based on my experience from C language.
from sys import exit
from cs50 import get_int

def main():
    while True:
        num = get_int("Height: ")
        if num >= 1 and num <= 8:
            break

    print_pyramid(num)
    exit(0)

def print_pyramid(n):
    for i in range(n):
        print_spaces(i, n)              # calling two function that print spaces and hash
        print_hash(i)                   # after print every spaces and hash in each row,
        print()                         # print new line for new row

def print_spaces(i, n):
    for j in range(n-(i+1)):            # those calculation means that we print space one less than the height      ......#  (seven spaces)
        print(" ", end="")              # if height = 8     8-(i+1)     'i' is increment from above function        .....##  (six spaces)

def print_hash(i):
    for l in range(i+1):                # print the hash by increasing it   (i+1)
        print("#", end="")              # i = 0  # / i = 1  ##

    l = 1                               # there's two spaces between two pyramid. at the print_spaces function range(n - i+1)
    n = 4                               # so initialize l = 1 and n = 4, would always give (4-(1+1)) = 2
    print_spaces(l, n)

    for l in range(i+1):                # print rigth hash 'pyramid'
        print("#", end="")

main()

I always love to work with complicated idea using a lot of function for their different purpose.
I also got a 98% score from CS50.
What do you think of my code? Since this is my first time using Python, are there any Pythonic ways to simplify my program? (especially using function like I did).
Height: 4
       #  #
      ##  ##
     ###  ###
    ####  ####


texts: Titleize words in a sentence but with some conditions

texts:
Below is the code I have written to capitalize all the words of a sentence except if

The words belong to the littleWords list.
The word would be capitalized if it's the first word of the sentence even if it is in the littleWords list.

def titleize(sentence)
    littleWords = ["end", "over", "and", "the"]
    words = sentence.split(/^(\w+)\b/)
    sentence = if words[2]
        words[2].split(" ").map do |word|
            littleWords.include?(word) ? (" " + word) : (" " + word.titleize)
        end
    end
    words[1].titleize + (sentence||[]).join("")
end

SPEC

describe "titleize" do
it "capitalizes a word" do
  titleize("jaws").should == "Jaws"
end

it "capitalizes every word (aka title case)" do
  titleize("david copperfield").should == "David Copperfield"
end

it "doesn't capitalize 'little words' in a title" do
  titleize("war and peace").should == "War and Peace"
end

it "does capitalize 'little words' at the start of a title" do
  titleize("the bridge over the river kwai").should == "The Bridge over the River Kwai"
end
end

I am new to ruby/script and am coming from Java. The code above doesnt looks as nice and clean as I think could be done with ruby.


texts: Array find min value with user-defined comparison compare function

texts:
My user defined comparison compare function is defined with an array:

$boardkey_to_values=Array(19=>2601248,23=>2601248,39=>2603445,
    43=>2256319,47=>2632006,59=>2603445,63=>2232152,67=>2260713,71=>2632006,...)

so 23>19 EDIT:23=19, 39>19, 39<23,...

I have an array of values $board_id, and I want to get the array of all the keys for the minimum values.

Here's my solution, but I don't think it is really intuitive.

$min_key=Array(0);
foreach ($board_id as $key => $value) {
if ($boardkey_to_values[$board_id[$min_key[0]]]>$boardkey_to_values[$value])
    $min_key=Array($key);
if ($boardkey_to_values[$board_id[$min_key[0]]]==$boardkey_to_values[$value] && $min_key[0]!=$key)
    $min_key[]=$key;
}

Here is an example to show how this should behave:

say $board_id = [19,23,39,47,71]

it will look at the values corresponding to this numbers [2601248,2601248,2603445,2632006,2632006]

it looks for the smallest value: 2601248

so the result ($min_key should be [19,23])


texts: Extracting a conversation from a Skype sqlite database

texts:
I've made this code to extract a conversation from a Skype database file with a certain user ID, all this being specified as a command line argument.

Since Skype uses SQLite to store the messages I can use the sqlite3 Python module to retrieve the messages.

The code first checks for the database file, opens it if it exists, parses it and finally outputs the chat either to stdout or a specified output file (it uses the partner's ID by default if nothing is provided). The output looks somewhat like what you would expect from an IRC conversation.

I'm quite satisfied with the script in general however  I had several issues with unicode characters which made me have to use some "cheats". I'm not satisfied with all these unicode() conversions, and the fact I have to specify once more at the end via encode('utf-8') that I am indeed going to output other things than ASCII. I also think this code could be made more elegant, especially with the SQL query. If I ever want to add more options, such as sorting, I feel like putting everything in the SQL query looks ugly.

#!/usr/bin/env python2
# charset=utf-8

from __future__ import print_function

import sys
import sqlite3
import os.path
import datetime
import HTMLParser

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def eprint_use():
    eprint("usage : " + sys.argv[0] + " <file.db> <partner's skype ID> [output file]")

# actual code here
# first of all check argv and print the help message if it's wrong

if not len(sys.argv) in [3, 4]:
    eprint_use()

else:
    database_path = sys.argv[1]
    partner_id = sys.argv[2]
    output_path = sys.argv[3] if len(sys.argv) == 4 else partner_id + '.txt'

    if not os.path.isfile(database_path):
        sys.exit('the file %s does not exist' % (database_path))

    output_file = sys.stdout if output_path == '-' else open(output_path, 'w')

    connection = sqlite3.connect(database_path)
    cursor = connection.cursor()

    parser = HTMLParser.HTMLParser()

    cursor.execute("""
    SELECT timestamp,from_dispname,body_xml
    FROM Messages
    WHERE dialog_partner='""" + partner_id + """'
    ORDER BY timestamp
    """)

    for row in cursor.fetchall():
        timestamp = unicode(datetime.datetime.utcfromtimestamp(int(row[0])).strftime('%Y-%m-%d %H:%M:%S'))
        name_tag = unicode(row[1])
        message_body = unicode(parser.unescape(unicode(row[2])))

        output = "[%s] <%s> %s\n" % (timestamp, name_tag, message_body)

        output_file.write(output.encode('utf-8'))

Please keep in mind that I've barely been actively programming in Python for about a year and a half. I try to make my code as pythonic as possible, but as primarily being a C programmer I tend to neglect some of the aspects of the python language in favour of "C-tricks". If you see any such thing, please tell me as well.


texts: Best way to create a daemon in a JavaWeb application

texts:
I have a purpose for an application to run a daemon in my web application.

The application is running with Struts1 on a tomcat7 server using Java7.

This is what it does:

Launch itself when the application is loaded
every minutes does a task (the sysout in the code)
when the application stops, it stops the timer and let the task 10 sec max to finish its process if needed

In the web.xml file i have these lines to launch the process:

<listener>
    <listener-class>com.toto.tata.applicationlayer.BiuDeamon</listener-class>
</listener>

And here is the code:

package com.toto.tata.applicationlayer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class BiuDeamon implements ServletContextListener {
    private static boolean isDaemonWorking = false;
    private static Timer timer;
    private static TimerTask timerTask;

    static {
        timerTask = new TimerTask(){
            public void run() {
                if (!isDaemonWorking) {
                    try {
                        isDaemonWorking = true;

                        System.out.println("I RUN");

                        isDaemonWorking = false;
                    } catch (Throwable e) {
                        ex.printStackTrace();
                    }
                }
            }
        };
    }

    public BiuDeamon() {
        super();
    }

    public void contextInitialized(ServletContextEvent a_event) {
        timer = new Timer();
        timer.schedule(timerTask, new Date(), 60000);
    }

    public void contextDestroyed(ServletContextEvent a_event) {
        // we stop the timer
        timer.cancel();
        // we let the timertask 10 sec to stop its processing
        int i=0;
        for (; i<10; i++) {
            if (isDaemonWorking) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch(InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            } else {
                break;
            }
        }
        // we kill it if needed
        if (i==10)
            timerTask.cancel();
    }
}

I know my code is working because I have tested it, but I wonder if there is a better way to achieve what I want.

Any comments / examples will be appreciated :)


texts: Ranking lines of a file according to number of occurrences

texts:
I recently dived into Ruby, so I want to improve this code. Is this good enough?

def ranksystem
    logfile = IO.readlines("some_logfile.log")
    logfile.each do |value|
      value.gsub!(/[\n]+/, "")
    end
    logfile.delete("")

    logcount = Hash.new(0)

    logfile.each do |v|
      logcount[v] += 1
    end

    logarray = logcount.sort_by {|k,v| v}.reverse

    finalreturn = ""

    logarray.each_with_index do |value, index|
      finalreturn = finalreturn + "Rank #{index+1} : #{value[1]} (#{value[0]})\n"
    end

    finalreturn

end

This code reads each line in log file like this:

apple
orange
apple
apple
apple
apple
orange
orange
banana
banana

and converts like this:

Rank 1 : 4 (apple)
Rank 2 : 3 (orange)
Rank 3 : 2 (banana)


texts:
I have an SDL_Wrapper which is working perfectly (it is not broken)! Please suggest how I could improve performance, and how I could make my unique_ptr(s) dispose automatically.

So far, I call my class like this:

CWindow window = std::make_unique<CWindowWrap>("title", 0, 0, 140, 100, 0)

Is it the best way to do it? Will my unique_ptr dispose automatically?

Here's the SDL_Wrapper class:

 #include "LogManager.h"
 #include <memory>
 #include <SDL.h>

 //SDL_Renderer wrapper

 ////SDL_Window wrapper !

 class CWindowWrap
 {

 public:
     CWindowWrap(const char* title, int xpos, int ypos, int width, int height, int flags)
         : ptr_window(SDL_CreateWindow(title, xpos, ypos, width, height, flags))
     {
        LOG("SDL_Window Wrapper", "Constructed Window !");
    }
     virtual ~CWindowWrap()
     {
         if (ptr_window != nullptr){
            SDL_DestroyWindow(ptr_window);
            LOG("SDL_Window Wrapper", "Destroyed Window !");
        }
        else
             LOG("SDL_Window Wrapper", "Window doesn't need to be destroyed !");
     }

     //disable copy constructor
     CWindowWrap(CWindowWrap const&) = delete;
    CWindowWrap& operator=(CWindowWrap const&) = delete;

    //allow move
    CWindowWrap(CWindowWrap&& move)
        : ptr_window(nullptr)
    {
         using std::swap;
         swap(ptr_window, move.ptr_window);
    }

     CWindowWrap& operator=(CWindowWrap&& move){
         using std::swap;
         swap(ptr_window, move.ptr_window);
     }

     operator SDL_Window*() { return ptr_window; } // implicite conversion between CWindowWrap ---> SDL_Window*;

 private:
     SDL_Window* ptr_window = nullptr;
 };

 typedef std::unique_ptr<CWindowWrap> CWindow;

 class CRendererWrap
 {
 public:

     CRendererWrap(CWindowWrap window, int x, int y)
         : ptr_renderer(SDL_CreateRenderer(window, x, y))
     {}
    ~CRendererWrap()
     {
        if (ptr_renderer != nullptr){
            SDL_DestroyRenderer(ptr_renderer);
        }
     }

     //disable copy constructor
     CRendererWrap(CRendererWrap const&) = delete;
     CRendererWrap& operator=(CRendererWrap const&) = delete;

     //allow move
     CRendererWrap(CRendererWrap&& move)
        : ptr_renderer(nullptr)
     {
        using std::swap;
        swap(ptr_renderer, move.ptr_renderer);
     }

     CRendererWrap& operator=(CRendererWrap&& move){
        using std::swap;
        swap(ptr_renderer, move.ptr_renderer);
    }

     operator SDL_Renderer*() { return ptr_renderer; } // implicite conversion between CRendererWrap ---> SDL_Renderer*;

 private:
      SDL_Renderer* ptr_renderer = nullptr;
 };

 typedef std::unique_ptr<CRendererWrap> CRenderer;

 struct Window_param
 {
     const char* title;
     const int width;
     const int height;
     const int xPos;
     const int yPos;
     const int flags;
 };


texts: Python program to find the subarray with maximum sum

texts:
An assignment at school required me to write a program for this task using Kadane's algorithm (explained here):

  Define the function find_max_subarray that takes a list as an argument and two indices, start and end. It finds the maximum subarray in the
  range [start, end – 1].
  The function find_max_subarray returns the tuple (l, r, m) where l and r are the left and right indices of the maximum subarray and m is its
  sum.
  The function uses a loop to keep track of the maximum subarray ending at index i. That is, the maximum subarray that has the element
  at index i as its last element.
  Then the maximum subarray will simply be the maximum of all these subarrays.
  The maximum subarray ending at index i + 1 is given by max(list[i] + maximum sum of subarray ending at i, list[i]).
  The function keeps track of the maximum sum of the subarray seen so far and its left and right indices as the loop iterates.

Here is my solution to this task (using Python):

def find_max_subarray(alist, start, end):

    max_ending_at_i = max_seen_so_far = alist[start]
    max_left_at_i = max_left_so_far = start
    max_right_so_far = start + 1
    for i in range(start + 1, end):
        if max_ending_at_i > 0:
            max_ending_at_i += alist[i]
        else:
            max_ending_at_i = alist[i]
            max_left_at_i = i
        if max_ending_at_i > max_seen_so_far:
            max_seen_so_far = max_ending_at_i
            max_left_so_far = max_left_at_i
            max_right_so_far = i + 1
    return max_left_so_far, max_right_so_far, max_seen_so_far

alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {} and has sum {}.'.format(start, end - 1, maximum))

Here are some example outputs:

Enter the list of numbers: 3 -2 4 -6 7 8 -10 4
The maximum subarray starts at index 4, ends at index 5 and has sum 15.

Enter the list of numbers: 4 5 -2 0 -5 15
The maximum subarray starts at index 0, ends at index 5 and has sum 17.

Enter the list of numbers: 3
The maximum subarray starts at index 0, ends at index 0 and has sum 3.

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

Any help would be highly appreciated.


texts:
Yes, I know we have a lot of these.

I'm new to Clojure, but not to lisps. After the recent (javascript?) parentheses-balancing Q, I decided to do an implementation in Clojure for practice with the language. (It also happened to make a nice accompaniment to my rant about students learning what is and isn't possible with regular expressions.)

I chose to use (reduce) over recursion mostly because I am a fan of letting functions do the work of creating loops and recursion for me, but in this case I am not sure how "elegant" I consider the :false handling.

Code

(ns parens)

(def str->chars (partial map identity))

(defn mk-balanced?
  "makes a balanced? checker from table, which maps closing characters to
  opening characters.

  see also: balanced?"
  [table]
  (fn [s]
    (let [opens (set (vals table))
          closes (set (keys table))]
      (empty?
        (reduce
          (fn [stack cur]
            (if (not= (peek stack) :false)
              (condp contains? cur
                opens (conj stack cur)
                closes (if (and (seq stack)
                                (= (peek stack) (table cur)))
                         (pop stack)
                         [:false])
                stack)
              [:false]))
          []
          (str->chars s))))))

(def balanced?
  (mk-balanced? {\) \(
                 \] \[
                 \} \{}))


texts: Rust - Need help making code idiomatic and clean (with lifetimes)

texts:
This is the first real program I have written in rust. What started as a clean piece of rust code, turned into a lifetime monstrosity when I decided to make my enums and structs use &str instead of String. The algorithm implemented is irrelevant; I just need help making my code more idiomatic and clean. Here is (quite simple) my code:
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

#[derive(Debug, PartialEq, Eq)]
struct BasicBlock<'a> {
    block_id: u32,
    code: Vec<IRCode<'a>>,
    preds: Vec<Box<BasicBlock<'a>>>,
    succs: Vec<Box<BasicBlock<'a>>>,
}

#[derive(Debug, PartialEq, Eq)]
enum IRCode<'a> {
    Basic {
        value: &'a str,
        btype: Type,
        id: u32,
    },
    Quadruple {
        op: Op,
        params: Vec<IRCode<'a>>,
        location: Storage<'a>,
    },
    // and some more...
}

#[derive(Debug, PartialEq, Eq)]
enum Type {
    TVarRef,
    // and some more...
}

#[derive(Debug, PartialEq, Eq)]
enum Storage<'a> {
    Temp { name: &'a str },
}

#[derive(Debug, PartialEq, Eq)]
enum Op {
    Add,
    Sub,
}

impl<'a> Hash for BasicBlock<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.block_id.hash(state);
    }
}

#[derive(Debug)]
struct SSA<'a> {
    count: HashMap<&'a str, u32>,
    current_def: HashMap<&'a str, HashMap<Box<&'a BasicBlock<'a>>, Box<IRCode<'a>>>>,
}

impl<'a> SSA<'a> {
    fn new() -> SSA<'a> {
        SSA {
            count: HashMap::new(),
            current_def: HashMap::new(),
        }
    }

    fn new_variable(&mut self, name: &'a str, block: &'a BasicBlock<'a>) -> &Box<IRCode<'a>> {
        // If `name` is not in `count`, insert `(name, 0)`; else increment the count
        *self.count.entry(name).or_insert(0) += 1;
        self.current_def.entry(name).or_insert(HashMap::new());
        self.current_def.get_mut(&name).unwrap().insert(
            Box::new(block),
            Box::new(IRCode::Basic {
                value: name,
                btype: Type::TVarRef,
                id: *self.count.get(&name).unwrap(),
            }),
        );
        self.current_def.get(&name).unwrap().get(&block).unwrap()
    }
}

fn main() {
    // very simple test case
    let mut ssa = SSA::new();
    let bb0 = BasicBlock {
        block_id: 0,
        code: vec![],
        preds: vec![],
        succs: vec![],
    };
    println!("{:?}", ssa.new_variable("foo", &bb0));
    println!("{:?}", ssa);
}

Thanks!


texts:
I am a C++ student (1.5 months into it). Please give feedback to this different way I have thought of for Fibonacci series. If there are any improvements needed, please suggest them also.

#include<iostream>
using namespace std;
void fibseries(long int n)
{
    double x=0;double y=1;
    for (long int i=1;i<=n;i++)
     {
        if(i%2==1)
         {
            cout<<x<<" ";
            x=x+y;
         }
        else
         {
            cout<<y<<" ";
            y=x+y;
         }
     }
}
main()
{
    long int n=0;
    cout<<"The number of terms ";
    cin>>n;
    fibseries(n);
    return 0;
}


texts:
I've written this "little" typeof extension for my JS. What do you think about it?

Its aim is to provide a single reliable typeof in JavaScript, consistent between native vars and objects. I've tested it both in FF 4+, IE 7+, Chrome 12, Safari 5. Also, if you have a different browser (also the version), can you test it?

typeOf = function(e) {
  if (typeof e === "undefined") {
    return "undefined";
  } else if (typeof e === "object") {
    if (e === null) {
      // null è un oggetto
      return "null";
    } else if (e instanceof String) {
      return "string";
    } else if (e instanceof Number) {
      return "number";
    } else if (e instanceof Boolean) {
      return "boolean";
    } else if (e instanceof Date) {
      return "date";
    } else if (e instanceof RegExp) {
      return "regexp";
    } else if (e instanceof Error) {
      return "error";
    } else if (e.isArray
                || e instanceof Array) {
      return "array";
    } else if (e instanceof Window) {
      return "window";
    } else if (e.nodeType) {
      switch (e.nodeType) {
        case 1:
          return "element";
        case 2:
          return "attribute";
        case 3:
          return "text";
        case 9:
          return "document";
      }
    } else if (e.call) {
      return "function";
    }
  } else if (typeof e === "function") {
    if (e.call) {
      return "function";
    } else if (e instanceof RegExp) {
      // V8
      return "regexp";
    }
  }

  return typeof e;
};


texts: Filter a list of persons by age and write the results to a relevant file

texts:
Let's say I have a class:

class Data
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public Data(string name, string lastname, int age)
    {
        Name = name;
        LastName = name;
        Age = age;
    }
}

I want to get the age of a person, if it's <18 then print all the data to Kids.csv, else I want it to be printed to Adults.csv.

I know it's simple and I managed to do that, but the teacher said that my code didn't look like objective programming. He told me that I need to use method to return array and create other method for writing the array to file or something.

static void Main(string[] args)
    {
        People[] people = new People[MaxPeople];
        people = ReadData();

        WriteKids(people);
        WriteAdults(people);
    }

static void WriteKids(Data[] people)
{
File.WriteAllText(@"Kids.csv", String.Empty);
using (StreamWriter writer = new StreamWriter(@"Kids.csv", true, Encoding.Default))
{
    for (int i = 0; i < Count; i++)
    {
        if (people[i].Age < 18)
        {
            writer.WriteLine("{0};{1};{2}", people[i].Name,              people[i].LastName, people[i].Age);
        }
    }
}

static void WriteAdults(Data[] people)
{
        File.WriteAllText(@"Adults.csv", String.Empty);
        using (StreamWriter writer = new StreamWriter(@"Adults.csv", true, Encoding.Default))
        {
            for (int i = 0; i < Count; i++)
            {
                if (people[i].Age => 18)
                {
                    writer.WriteLine("{0};{1};{2}", people[i].Name, people[i].LastName, people[i].Age);
                }
            }
        }
 }


texts: Smart way to shorten the current working directory in pure Bash

texts:
I'm trying to create a shell prompt that displays the $PWD in a "smart" way. I want to display the top two directories rather than the full path. If $HOME is the parent (or parent of the parent) directory, I want to show it like ~.

Assuming my $HOME is "/home/user", here are a few test cases with expected output according to several $PWD values:

/                  -> /
/home              -> /home
/home/user         -> ~
/home/user/foo     -> ~/foo
/home/user/foo/bar -> foo/bar
/usr/local         -> /usr/local
/usr/local/games   -> local/games
/home/userr        -> /home/userr

Currently, my solution is as follow:

path=$PWD

# $n is the number of "/" in the path indicating that there is more than 2 dirs
# In such case, the path should be truncated
# If the path contains root / (like "/home/usr"), 3 "/" implies 3 dirs
# If the path is "~/foo" then only 2 "/" are required
# If ${PWD} starts with ${HOME}, we can replace this part with "~"
# A slash need to be appended to "${HOME}" to avoid false positive
n=3
if [[ ${path}/ == ${HOME}/* ]]; then
  path=~${path:${#HOME}}
  n=2
fi

# Count the number of "/" in the path
# If there is more than $n "/", this means the path contains more than 2 dirs
# In this situation, we need to extract the two last dirs only from the path
slashes=${path//[^\/]}
if [[ ${#slashes} -ge $n ]]; then
  dir=${path##*/}
  parentpath=${path%/*}
  parentdir=${parentpath##*/}
  path=$parentdir/$dir
fi

echo $path

This function is intended to be used in my bash shell prompt. As this will be issued each time I type a command in my terminal, and as I will keep this in my .bashrc for probably several years to come, I'm looking to "optimize" this function.

Could the solution have been implemented otherwise, or could this function be improved in some way in order to minimize it's overall "footprint"?


texts: Updating the presentation of a credit card field as the card type becomes known

texts:
The goal here is to, add a credit card image, and remove all other credit card images, of a certain input field.
I had a even larger code, with a lot of addClass() and removeClass()... then, I shrink it until I have this.
Still, I feel it's still a huge block of code.

The point here is to short things up, but NOT until it's hard to understand what's going on.

if (event.isValid) {

    if (event.card.type == 'visa') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-visa'));

    } else if (event.card.type == 'master-card') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-master-card'));

    } else if (event.card.type == 'e-american-express') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-american-express'));

    } else if (event.card.type == 'diners-club') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-diners-club'));

    } else if (event.card.type == 'discover') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-discover'));

    } else if (event.card.type == 'jcb') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-jcb'));

    } else if (event.card.type == 'unionpay') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-unionpay'));

    } else if (event.card.type == 'maestro') {

        $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, 'e-maestro'));
    }

} else {

    $("#card-number").removeClass(CREDIT_CARD_LIST);
}


texts: Java code to delete comments from an input string

texts:
I wrote this code to delete comments from an input string (such as a Java file converted to string) and it works great. For simple curiosity, I was wondering if there was a more elegant way of presenting the function that I wrote.

I'm looking for some advice on presenting the code, and how to condense the code.

Here's the function:

public static String deleteComments(String myString) {
    String newString = "";

    if (myString.contains("\"")) {
        if (myString.indexOf("\"") != 0) {

            String[] stringParts = myString.split("\"");

            for (int i = 0; i < stringParts.length; i++) {

                if ((i & 1) == 0) {
                    Pattern commentaryPattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

                    Matcher m = commentaryPattern.matcher(stringParts[i]);

                    newString += m.replaceAll("");
                } else {
                    newString += "\"" + stringParts[i] + "\"";
                }
            }
        }
    } else {
        Pattern commentaryPattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

        Matcher m = commentaryPattern.matcher(myString);

        newString += m.replaceAll("");
    }

    return newString;
}

Note: the regex pattern comes from another Stack Overflow link. It does most of the work but also deletes comments inside a string
(eg: String myString = "bob said, \"Hi //To his friendly neighbor\".";) which, according to the java doc, is not a comment.


texts: Class decorator in Python to set variables for the constructor

texts:
I personally don't like the boilerplate of most __init__ methods:

self.a = a
self.b = b
...

So I thought this would be a nice opportunity to learn a bit more about decorators. As this is my first attempt on a class decorator I'm sure there is a lot to improve so fire away:

Implementation

from collections import namedtuple

def autofill(*args, **kwargs):
    """ This class decorator declares all attributes given into the constructor
    followed by a call of __init__ without arguments (beside reference to self).
    Order is the same than namedtuple with the possibility of default elements.
    Note that in this decorator alters the existing class instance instead of
    returning a wrapper object. """

    def filler(cls, *args, **kwargs):
        """ This is our custom initialization method. Input sanitation and
        ordering is outsourced to namedtuple. """

        for key, val in InputSanitizer(*args, **kwargs)._asdict().items():
            setattr(cls, key, val)

        filler.super_init(cls)

    def init_switcher(cls):
        filler.super_init = cls.__init__
        cls.__init__ = filler
        return cls

    # Taken from http://stackoverflow.com/questions/11351032/named-tuple-and-
    # optional-keyword-arguments
    InputSanitizer = namedtuple('InputSanitizer', args + tuple(kwargs.keys()))
    InputSanitizer.__new__.__defaults__ = tuple(kwargs.values())

    return init_switcher

Some test cases

import unittest

class TestAutoFill(unittest.TestCase):
    @autofill('a', b=12)
    class Foo(dict):
        pass

    def test_zero_input(self):
        with self.assertRaises(TypeError):
            self.Foo()

    def test_one_input(self):
        bar = self.Foo(1)
        self.assertEqual(bar.a, 1)
        self.assertEqual(bar.b, 12)

        bar = self.Foo(a=1)
        self.assertEqual(bar.a, 1)
        self.assertEqual(bar.b, 12)

        with self.assertRaises(TypeError):
            self.Foo(b=1)

        with self.assertRaises(TypeError):
            self.Foo(c=12)

    def test_two_input(self):
        bar = self.Foo(1, 2)
        self.assertEqual(bar.a, 1)
        self.assertEqual(bar.b, 2)

        bar = self.Foo(b=2, a=1)
        self.assertEqual(bar.b, 2)
        self.assertEqual(bar.a, 1)

    def test_other_object_functions(self):
        bar = self.Foo(1)
        bar.c = 3
        bar['key'] = 4

        self.assertEqual(bar.a, 1)
        self.assertEqual(bar.b, 12)
        self.assertEqual(bar.c, 3)
        self.assertEqual(bar['key'], 4)

if __name__ == '__main__':
    unittest.main()


texts:
Exercise: Using Arraylists create a program that makes divisions between two very large numbers (numbers greater than 10 digits).

I did it (the code works), but could my code be improved?

public class Main {

    static void division(List<Integer> lista, List<Integer> listb) {

        List<Integer> listResult = new ArrayList<>();

        if (lista.size() <= 10 || listb.size() <= 10) {
            System.out.println("The numbers must be bigger than 10");
        } else {double a = 0, j = 0;
            String Stringnumber = "";
            String Stringnumber2 = "";

            for (int number : lista) {
                Stringnumber += String.valueOf(number);
            }

            for (int number : listb) {
                Stringnumber2 += String.valueOf(number);
            }

            double test = Double.parseDouble(Stringnumber2);
            double test2 = Double.parseDouble(Stringnumber);

            double dividend = 0, divisor = 0;

            if (test >= test2) {
                dividend = test;
                divisor = test2;
            } else {
                dividend = test2;
                divisor = test;
            }

            for (int i = 9; i > 0 && j != 1; i--) {
                if (i * divisor <= dividend) {
                    listResult.add(i);

                    a = dividend - (i * divisor);
                    if (a >= divisor) {
                        i = 9;
                    } else {
                        j = 1;
                    }
                }
            }

            System.out.println("The result is:");
            for (int i = 0; i < listResult.size(); i++) {
                System.out.println(listResult.get(i));
            }

        }
    }

    public static void main(String[] args) {

        Scanner x = new Scanner(System.in);

        List<Integer> lista = new ArrayList<>();
        List<Integer> listb = new ArrayList<>();

        System.out.println("Give a number");
        for (char digit : x.nextLine().toCharArray()) {
            lista.add(digit - '0');
        }

        System.out.println("Give another number");
        for (char digit : x.nextLine().toCharArray()) {
            listb.add(digit - '0');
        }
        x.nextLine();

        division(lista, listb);
    }

}


texts: Is a unit test which uses LINQ to check multiple values acceptable?

texts:
I'm writing unit tests for a library which parses colors from user input (example: the user input “#f00” gives a red color; the user input “60,100%,100%” gives a yellow color, etc.)

One of the conditions is that the method Parse returns null when there is actually nothing to parse, i.e. when the input is either an empty string or its length is inferior to four characters. Those are the two unit tests:

[TestMethod]
public void SubmitEmptyText()
{
    var actual = new ColorParser().Parse(string.Empty);
    Assert.IsNull(actual);
}

[TestMethod]
public void SubmitShortText()
{
    Assert.IsTrue(new[]{"#", "#f", "#ff"}.All(c => !new ColorParser().Parse(c).HasValue));
}

Is the second method doing too much?
Am I expected to create three method? Seriously?!
Is the usage of functional programming here justified, or should I instead stick to the most basic way to write the tests?


texts: Boyer Moore Horspool Search Algorithm in Go

texts:
I am practicing Go and try to implement Boyer Moore Horspool Algorithm in Go, It returns all ocurrance of a "phrase" in a given text. This code is working, but I would be pleased to have any feedback and suggestions from Go Gurus, about all aspect of my code.

package boyer_moore_horspool_search

type badMatchTable struct{
    table [256]int
    pattern string
}

func newBadMatchTable(pattern string) *badMatchTable{
    b := badMatchTable{
        pattern: pattern,
    }

    b.table = [256]int{}
    b.table = b.generateTable()

    return &b
}

func (b *badMatchTable) generateTable() [256]int{

    for i := 0; i < 256 ; i++  {
        b.table[i] = len(b.pattern)
    }

    lastPatternByte := len(b.pattern) - 1

    for i := 0; i < lastPatternByte ; i++  {
        b.table[int(b.pattern[i])] = lastPatternByte - i
    }

    return b.table
}

func Search(text string, pattern string) []int{

    var indexes []int
    byteText := []byte(text)
    bytePattern := []byte(pattern)

    textLength := len(byteText)
    patternLength := len(bytePattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength{
        return indexes
    }

    lastPatternByte := patternLength - 1

    mt := newBadMatchTable(pattern)
    index := 0
    for index <= (textLength - patternLength)  {
        for i := lastPatternByte ; byteText[index + i] == bytePattern[i]; i-- {
            if i == 0{
                indexes = append(indexes, index)
                break
            }
        }

        index += mt.table[byteText[index + lastPatternByte]]
    }

    return indexes
}

And this is the test file:

import (
    "fmt"
    "testing"
)

func TestSearch(t *testing.T) {

    indexes := Search("Hello, we want to find word Guru, so this #phrase has the word Guru.", "word Guru")

    fmt.Printf("Occurance: %v\n", len(indexes))
    for _, i := range indexes  {
        fmt.Printf("Index: %v\n", i)
    }

}


texts: Perform a predetermined set of operations on a large sequence

texts:
This is a programming challenge.

I have been given the following input:

  \$n\$ where n is size of sequence
  \$k\$ is an integer
  a sequence \$A_0, A_1, A_2, \ldots A_{n-1}\$

I need to perform for each index from 0 to (k-1) inclusive

find a,b
where a = A[i % n] and b = A[n - (i % n) - 1]
then set A[i % n] = a XOR b

and output the final sequence, separated by spaces

The inputs are within the ranges:

  \$n \leq 10^4\$
  \$k \leq 10^{12}\$
  \$A_i \leq 10^7\$

I have applied the following naive approach

n,k=map(int,input().split())
arr=list(map(int,input().split())) #read input sequence and store it as list type
for i in range(k): #iterate over 0 to (k-1)
    t=i%n          #module of i wrt n
    arr[t]=arr[t]^arr[n-(t)-1]  #xor between two list elements and then set result to the ith list element
for i in arr:
    print(i,end=" ")  #print the final sequence

This code runs in 2 seconds when \$K \leq 10^6\$, but it shows Time Limit exceeded for large test cases.
I am looking for an alternate suggestion for the problem


texts: How can I display the results of mysql_fetch_assoc in a dynamic table?

texts:
I have a MySQL database with several columns and two rows of data, so far. I'm using mysql_fetch_assoc to return the data in database, but I don't know how to put it all together in a table so that I can display it in another file.

Here is the code of the file that does the process (query.php):

<?php

// Configure connection settings

$db = 'scorecard';
$db_admin = 'root';
$db_password = '********';
$tablename = 'scoreboard';

// Title

//echo "DIV!";

// Connect to DB

$sql = mysql_connect("localhost", $db_admin, $db_password)
or die(mysql_error());

mysql_select_db("$db", $sql);

// Fetch the data

$query = "SELECT * FROM $tablename";
$result = mysql_query($query);
echo mysql_error();

echo "
\n";
echo "
\n";

// Return the results, loop through them and echo

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$codcliente = $row['codcliente'];
$nombre = $row['nombre'];
$ejecutivo = $row['ejecutivo'];
$banca_as400 = $row['banca_as400'];
$banca_real = $row['banca_real'];
$ingresos = $row['ingresos'];
$ciiu = $row['ciiu'];
$division = $row['division'];
$actividad = $row['actividad'];
$riesgo_industria = $row['riesgo_industria'];
$riesgo_cliente = $row['riesgo_cliente'];
$fecha = $row['fecha'];
$analista = $row['analista'];
echo "
$codcliente	$nombre	$ejecutivo	$banca_as400	$banca_real	$ingresos	$ciiu	$division	$actividad	$riesgo_industria	$riesgo_cliente	$fecha	$analista
\n";
echo "
$codcliente	$nombre	$ejecutivo	$banca_as400	$banca_real	$ingresos	$ciiu	$division	$actividad	$riesgo_industria	$riesgo_cliente	$fecha	$analista
\n";
echo "
\n";
}

And this is the result from the page that displays the process (index.php):

CAN'T DISPLAY SINCE I DON'T HAVE ENOUGH REPUTATION POINTS :(

As you can see, I have a table already in place and I would like the results to fall below as additional rows, but they come out all squashed together. I've tried several mysql_fetch types, but nothing works. The query results are displayed in a JavaScript DIV that is automatically refreshed by an AJAX script from another file (ajax.js). If you need to see the code for index.php or ajax.js, I could provide it.

Thanks!


texts:
This technique is more general than just for config files which is why I'm not using Config::Any in this example.

I have a config file with lines like this:

userid foo-admin # foo-comment
directory /some/dir # bar-comment

And I'm using some very awkward code to get the values.

my @userline = grep /userid/, <$configfh>;
my @userparts = split(' ', $userline[0]);
my @user = $userparts[1];

seek($configfh, 0, 0);
my @pathline = grep /directory/, <$configfh>;
my @pathparts = split(' ', $pathline[0]);
my $path = $pathparts[1];

It works! But man, is it ugly. There's got to be a clearer way to extract the values I want from the file.


texts:
I've implemented a simple vector-like structure.  I would appreciate all criticism relevant to code, style, flow, camelCase vs underscore, and so forth.

template <class T>
class  Vector {
public:

    typedef T* Iterator;

    Vector();
    Vector(unsigned int size);
    Vector(unsigned int size, const T & initial);
    Vector(const Vector<T>& v);
    ~Vector();

    unsigned int capacity() const;
    unsigned int size() const;
    bool empty() const;
    Iterator begin();
    Iterator end();
    T& front();
    T& back();
    void push_back(const T& value);
    void pop_back();

    void reserve(unsigned int capacity);
    void resize(unsigned int size);

    T & operator[](unsigned int index);
    Vector<T> & operator = (const Vector<T> &);
    void clear();
private:
    unsigned int _size;
    unsigned int _capacity;
    unsigned int Log;
    T* buffer;
};

template<class T>
Vector<T>::Vector() {
    _capacity = 0;
    _size = 0;
    buffer = 0;
    Log = 0;
}

template<class T>
Vector<T>::Vector(const Vector<T> & v) {
    _size = v._size;
    Log = v.Log;
    _capacity = v._capacity;
    buffer = new T[_size];
    for (unsigned int i = 0; i < _size; i++)
        buffer[i] = v.buffer[i];
}

template<class T>
Vector<T>::Vector(unsigned int size) {
    _size = size;
    Log = ceil(log((double) size) / log(2.0));
    _capacity = 1 << Log;
    buffer = new T[_capacity];
}

template <class T>
bool Vector<T>:: empty() const {
    return _size == 0;
}

template<class T>
Vector<T>::Vector(unsigned int size, const T& initial) {
    _size = size;
    Log = ceil(log((double) size) / log(2.0));
    _capacity = 1 << Log;
    buffer = new T [_capacity];
    for (unsigned int i = 0; i < size; i++)
        buffer[i] = initial;
}

template<class T>
Vector<T>& Vector<T>::operator = (const Vector<T> & v) {
    delete[] buffer;
    _size = v._size;
    Log = v.Log;
    _capacity = v._capacity;
    buffer = new T [_capacity];
    for (unsigned int i = 0; i < _size; i++)
        buffer[i] = v.buffer[i];
    return *this;
}

template<class T>
typename Vector<T>::Iterator Vector<T>::begin() {
    return buffer;
}

template<class T>
typename Vector<T>::Iterator Vector<T>::end() {
    return buffer + size();
}

template<class T>
T& Vector<T>::front() {
    return buffer[0];
}

template<class T>
T& Vector<T>::back() {
    return buffer[_size - 1];
}

template<class T>
void Vector<T>::push_back(const T & v) {
    /*
        Incidentally, one common way of regrowing an array is to double the size as needed.
        This is so that if you are inserting n items at most only O(log n) regrowths are performed
        and at most O(n) space is wasted.
    */
    if (_size >= _capacity) {
        reserve(1 << Log);
        Log++;
    }
    buffer [_size++] = v;
}

template<class T>
void Vector<T>::pop_back() {
    _size--;
}

template<class T>
void Vector<T>::reserve(unsigned int capacity) {
    T * newBuffer = new T[capacity];

    for (unsigned int i = 0; i < _size; i++)
        newBuffer[i] = buffer[i];

    _capacity = capacity;
    delete[] buffer;
    buffer = newBuffer;
}

template<class T>
unsigned int Vector<T>::size() const {
    return _size;
}

template<class T>
void Vector<T>::resize(unsigned int size) {
    Log = ceil(log((double) size) / log(2.0));
    reserve(1 << Log);
    _size = size;
}

template<class T>
T& Vector<T>::operator[](unsigned int index) {
    return buffer[index];
}

template<class T>
unsigned int Vector<T>::capacity()const {
    return _capacity;
}

template<class T>
Vector<T>::~Vector() {
    delete[] buffer;
}

template <class T>
void Vector<T>::clear() {
    _capacity = 0;
    _size = 0;
    buffer = 0;
    Log = 0;
}


texts: Performance optimization for Linq To SQL

texts:
I have been working with C# for quite some time but relatively new to the concepts of lambdas and Linq. I was working with a Linq To SQL example and trying to write a generic solution for executing a search against a collection of entities (eg. list of Customer objects) where the search parameter will be specified by passing a partially filled object of the entity class itself. I was doing this just to ensure that a person does not have to go on specifying different overloads for different searches based on the entity class attributes and trying to write a generic solution which will cater to any entity class.

Hence I used reflection and an array of predicates to successively apply the Where clauses to the collection.

Client App

using (CustomerManager oCustomerManager = new CustomerManager())
{
   IEnumerable<Customer> customers = oCustomerManager.Load();

   Customer oSearchCustomer = new Customer();
   oSearchCustomer.City = "London";
   oSearchCustomer.ContactName = "Thomas Hardy";

   IEnumerable<Customer> customerList = oCustomerManager.Search(oSearchCustomer);

   foreach (Customer customer in customerList)
   {
      Console.WriteLine(customer.ToString());
   }
}

Manager Class

public IEnumerable<Customer> Search(Customer searchObject)
{
    IEnumerable<Customer> customers = DataContext.Customers;
    List<Func<Customer, bool>> result =

    DataContext.Customers.GenerateFilterClause<Customer>(searchObject);

    foreach (var item in result)
    {
        customers = customers.Where(item);
    }

    return customers;
 }

Extension Method Utility Class

public static class UtilityExtensions
{
   public static List<Func<T, bool>> GenerateFilterClause<T>(this IEnumerable<T>
          collection, T searchEntity)
   {
        List<Func<T, bool>> whereFilterList = new List<Func<T, bool>>();
        Func<T, bool> predicate = null;

        var propertyList = searchEntity.GetType().GetProperties();

        foreach (PropertyInfo p in propertyList)
        {
            if (p.GetCustomAttributes(false).OfType<ColumnAttribute>().Count() > 0)
            {
               string propName = p.Name;
               var searchVal =

               searchEntity.GetType().GetProperty(propName).GetValue(searchEntity,null);
               if (searchVal != null)
               {
                  predicate = new Func<T, bool>(entity => propertyWhereClause(entity,
                         searchEntity, propName, searchVal));
                  whereFilterList.Add(predicate);
               }
            }
         }

         return whereFilterList;
     }

      private static bool propertyWhereClause<T>(T obj, T searchEntity, string    propertyName, object searchVal)
     {
           return obj.GetType().GetProperty(propertyName).GetValue(obj,
                                   null).Equals(searchVal);
      }
  }

While the solution is working, I have two specific questions:

What are the drawbacks of this solution? I was hoping to have inputs regarding performance and cleaner way to rewrite the code.
Can anyone suggest a more efficient and better solution? That would help me to understand the proper way to utilize the power of lambdas and Linq.


texts: Google Analytics tracking for HTML 5 video player

texts:
The jQuery code is for html5 video event GA tracking and I want to make it a little bit more shorter and cleaner. The code works: I am getting all the events, but would like to make it more simple.

function videoEnd() {
    console.log("Finished");
    ga('send', 'event', 'Videos', 'Finished', 'omegavideo');
}
$(document).ready(function() {
    var a = 0;
    var b = 0;
    var c = 0;
    var j = 0;

    /* Video Watched */
    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.25 * (this.duration)) {
            if (i < 1) {
                console.log("watched 25%");
                ga('send', 'event', 'Videos', 'Watched 25%', 'Video     1');
            }
            a = a + 1;
        }
    });

    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.50 * (this.duration)) {
            if (w < 1) {
                console.log("watched 50%");
                ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
            }
            b = b + 1;
        }
    });

    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.75 * (this.duration)) {
            if (z < 1) {
                console.log("watched 75%");
                ga('send', 'event', 'Videos', 'Watched 75%', 'Video 1');
            }
            c = c + 1;
        }
    });

    /* Video Finished, Thanks */
    $("#videoplayer").bind("ended", function() {
        if (j < 1) {
            console.log("Finished 100%");
            ga('send', 'event', 'Videos', 'Finished 100%', 'Video 1');
        }
        j = j + 1;
    });

})


texts: A simple implementation of the Unix find command written in Rust

texts:
I'm a C++ developer trying to learn Rust for fun and XP.
I decided to implement some of the Unix tools for practice.

Below is a simplified implementation of the find command.  The program takes 0 to 2 arguments: The first being the file to find, the second being the directory to start searching (I'm aware that the args aren't very robust).

I get the feeling there is a more succinct way to do what I'm trying to accomplish.

use std::env;
use std::io;
use std::collections::VecDeque;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::exit;

fn find(query: &String, start: &OsString) -> io::Result<Vec<PathBuf>> {
    let start = PathBuf::from(start);
    let mut dirs = VecDeque::from(vec![start]);
    let mut result = Vec::new();

    while let Some(dir) = dirs.pop_front() {
        for entry in dir.read_dir()? {
            let path = entry?.path();
            if path.is_dir() {
                dirs.push_back(path.clone());
            }
            if let Some(name) = path.file_name() {
                if query.is_empty() || query.as_str() == name {
                    result.push(path.clone());
                }
            }
        }
    }
    Ok(result)
}
fn main() {
    let query = match env::args().nth(1) {
        Some(query) => query,
        None => String::new(),
    };
    let start = match env::args().nth(2) {
        Some(start) => OsString::from(start),
        None => OsString::from("."),
    };

    match find(&query, &start) {
        Ok(paths) => {
            for path in paths {
                if let Some(p) = path.to_str() {
                    println!("{}", p);
                }
            }
        },
        Err(err) => {
            eprintln!("Error: {}", err);
            exit(1);
        },
    };
}


texts: Multicolumn iterations with cucumber data tables in Ruby

texts:
Cucumber is not designed to support multi-column iterations, but it is possible to make it work. Here, I want to try each combination of path and role.

This is the Cucumber Gherkin:

  Scenario: cannot access paths
    When I access "path" as "role" then I should see an error
      | /path1 | user1 |
      | /path2 | user2 |
      | /path3 | user3 |
      | /path4 |       |

And this is the Cucumber step_definition:

When(/^I access "path" as "role" then I should see an error$/) do |table|
  paths, roles = table.raw.transpose.map { |e| e.reject(&:blank?) }
  roles.each do |role|
    step "I am logged in as #{role}"
    paths.each do |path|
      p "#{role} user visiting #{path}"
      visit path
      step 'I should see the privileges error'
    end
  end
end

table.raw looks like:

[
    [0] [
        [0] "/path1",
        [1] "user1"
    ],
    [1] [
        [0] "/path2",
        [1] "user2"
    ],
    [2] [
        [0] "/path3",
        [1] "user3"
    ],
    [3] [
        [0] "/path4",
        [1] ""
    ]
]

and table.raw.transpose produces:

[
    [0] [
        [0] "/path1",
        [1] "/path2",
        [2] "/path3",
        [3] "/path4"
    ],
    [1] [
        [0] "user1",
        [1] "user2",
        [2] "user3",
        [3] ""
    ]
]

I like the line with transpose, but is it possible to make it any more succinct?

See Reference Cucumber for documentation related to Cucumber


texts:
I'm making the very common example of Factory design pattern which creates a factory of cars and return an instance of a car. I found a example here https://refactoring.guru/design-patterns/factory-method/php/example and decided to make my own factory. My question is why do I need a Creator for each car?
<?php

interface Car
{
    public function drive();
}

<?php
require_once('Car.php');

class Audi implements Car
{
    public function drive()
    {
        return "driving an Audi";
    }
}

<?php
require_once('Car.php');

class Mercedes implements Car
{

    public function drive()
    {
       return "driving an Mercedes";
    }
}

<?php

abstract class CarFactory
{
    abstract public function factoryMethod(): Car;

    public function someOperation(): string
    {
        // Call the factory method to create a Product object.
        $product = $this->factoryMethod();
        // Now, use the product.
        $result = "I want to drive something..... " .
            $product->drive();

        return $result;
    }
}

<?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Audi.php');

class AudiCreator extends CarFactory
{

    public function factoryMethod(): Car
    {
        return new Audi();
    }
}

<?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Mercedes.php');

class MercedesCreator extends CarFactory
{

    public function factoryMethod(): Car
    {
       return new Mercedes();
    }
}

<?php

require_once('car/AudiCreator.php');
require_once('car/MercedesCreator.php');

function clientCode(CarFactory $carFactory)
{
    // ...
    echo "Client: "
        . $carFactory->someOperation();
    // ...
}

echo "The client .
";
clientCode(new AudiCreator());
echo "\r\n";
echo  "
";
echo  "
";

clientCode(new MercedesCreator());


texts: Organizing a Python list of lists as function of number of occurances

texts:
I am having a Python list of lists, that I get as an output of python-igraph (membership to clusters). The integers represent an association of a vertex to a certain cluster at a certain subgraph. I would like to organise this list in a way that the biggest cluster in the whole (unconnected) graph is getting the lowest integer - 0, and then the smaller the cluster the higher the integer that is assigned to it. For now I do it in a very cumbersome way:

import numpy as np
def organize_in_decreasing_order(membership_list):
        conlist = np.concatenate(membership_list)
        count=np.bincount(conlist)
        ordered_list = []
        for i in range(len(count)):
            ordered_list.append(np.argmax(count))
            count[np.argmax(count)]=0
#        print ordered_list
        maxvalue = max(conlist)
        locations = []
        for number in range(maxvalue+1):
            locs = []
            for i in range(len(membership_list)):
                for j in range(len(membership_list[i])):
                    if membership_list[i][j]==number:
                        locs.append((i,j))
            locations.append(locs)
        for i,value in enumerate(ordered_list):
            for location in locations[value]:
                membership_list[location[0]][location[1]]=i
        return membership_list

You can check it over the following list:

memlist =
[[0,
  1,
  2,
  1,
  3,
  3,
  1,
  4,
  1,
  4,
  5,
  5,
  4,
  4,
  5,
  5,
  3,
  6,
  7,
  5,
  0,
  2,
  5,
  6,
  7,
  4,
  4,
  5,
  1,
  1,
  2,
  2,
  8,
  2,
  4,
  2,
  2,
  2,
  7,
  5,
  2,
  2,
  5,
  2,
  2,
  7,
  7,
  2,
  5,
  5,
  2,
  5,
  3,
  8,
  8,
  2,
  5,
  5,
  7,
  4,
  8,
  8,
  8,
  4,
  8,
  5,
  8,
  8,
  6,
  5,
  5,
  5,
  4,
  2,
  4,
  7,
  4,
  7,
  5,
  8,
  5,
  5,
  5,
  4,
  5,
  5,
  5,
  2,
  5,
  4,
  4],
 [9, 9, 9],
 [10],
 [11],
 [12]]

If you have an idea how to do it more efficiently I will be happy to hear!


texts:
Project Euler problem 7 says:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.  What is the 10001st prime number?

I believe that my code is working, but very very slowly. I guess the increment divisor can be changed, but I'm not sure how.

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

namespace p7
{
    //    By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
    //    What is the 10001st prime number?

    class Program
    {
        //          - SET 'divisor' TO 13
        //          - WHILE( divisor <= ceil[ sqrt(number) ] )
        //          - IF number%divisor == 0 && number != divisor THEN
        //          - Not prime / divisible by 'divisor'
        //          - ELSE IF ceil[ sqrt(number) ] == divisor THEN
        //          - PRIME!!!
        //          - ELSE increment divisor by 2
        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            int count = 6; // we already know 6 primes: 2,3,5,7,11,13
            long x = 14; // so can look for a prime after number 13

            while (count < 10001)
            {
                if (IsPrime(x, 13))
                {
                    count++;
                    x++;
                }
            }
            Console.WriteLine(x);
            Console.WriteLine("Time used (float): {0} ms", sw.Elapsed.TotalMilliseconds);
            Console.WriteLine("Time used (rounded): {0} ms", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
        static bool IsPrime(Int64 p, Int64 divisor)
        {
            Int64 sqrt = (Int64)Math.Ceiling(Math.Sqrt(p));
            while (divisor <= sqrt)
           {
                if (p % divisor == 0)
                    return false;
                else if (sqrt == divisor)
                    return true;
                divisor += 2;
            }
            return true;
        }
    }
}


texts: Using Custom Attributes to Populate Members from IDataReader

texts:
Just learned how to use custom attributes in C# and the first useful thing I did with it was to make a class object representing a database table. The constructor can accept an IDataReader and populate the members based on the custom attribute. Is this a good usage of custom attributes?

[AttributeUsage(AttributeTargets.Property)]
public class DatabaseField: Attribute
{
    public string Name { get; set; }
    public DatabaseField( string name )
    {
        Name = name;
    }
}

public class Employee
{
    [DatabaseField("Employee_ID")]
    public string EmployeeId { get; set; }

    [DatabaseField("LogonId")]
    public string Username { get; set; }

    [DatabaseField("Email")]
    public string EmailAddress { get; set; }

    [DatabaseField("NAME")]
    public string DisplayName { get; set; }

    [DatabaseField("First_Name")]
    public string FirstName { get; set; }

    [DatabaseField("Middle_Name")]
    public string MiddeName { get; set; }

    [DatabaseField("Last_Name")]
    public string LastName { get; set; }

    [DatabaseField("Name_Suffix")]
    public string NameSuffix { get; set; }

    [DatabaseField("Job_Title")]
    public string JobTitle { get; set; }

    [DatabaseField("Department")]
    public string Department { get; set; }

    [DatabaseField("Emp_Type")]
    public string EmployeeType { get; set; }

    [DatabaseField("SupervisorID")]
    public string ManagerId { get; set; }

    public Employee( IDataReader reader )
    {
        foreach( PropertyInfo prop in typeof(Employee).GetProperties() )
        {
            foreach( object attr in prop.GetCustomAttributes(true) )
            {
                DatabaseField field = attr as DatabaseField;
                if( null != field )
                {
                    object value = reader[field.Name];
                    prop.SetValue(this, value == DBNull.Value ? null : value, null);
                }
            }
        }
    }
}


texts:
I am learning Rust and decided to create a simple program to calculate n-th Fibonacci number. It uses a vector for memoization. The program works, but what would you suggest to improve here? Maybe store memo inside fib function as a static variable?
I tried to use u32 everywhere, but 48-th fib number doesn't fit into u32, so I decided to use u64.
use std::io;
use std::io::Write;
use std::str::FromStr;

fn fib(n: u32, memo: &mut Vec<u64>) -> u64 {
    if n < 2 {
        return n as u64;
    }
    else if memo[(n-1) as usize] != 0 {
        return memo[(n-1) as usize];
    }

    memo[(n-1) as usize] = fib(n - 1, memo) + fib(n - 2, memo);
    memo[(n-1) as usize]
}

fn main() {
    loop {
        print!("n = ");
        io::stdout().flush().unwrap();

        let mut str: String = String::new();
        io::stdin().read_line(&mut str)
            .expect("Error getting number");

        str.pop();
        match u32::from_str(&str) {
            Ok(n) => {
                let mut memo: Vec<u64> = vec![0; n as usize];
                println!("fib({})={}", n, fib(n, &mut memo));
                break;
            }
            Err(_e) => {
                println!("Error parsing number.");
                println!("Try again");
            }
        };
    }
}


texts: Recode C -> C++ trampoline function macros using templates

texts:
I'm reworking PyCXX (C++ wrapper for Python).

I'm currently examining the following macro code, and wondering whether there is a way to write it using templates rather than macros.

If so, the question becomes: what is the best way to write it? (I personally favour a concise macro solution over an awkward template solution).

#define PYCXX_NOARGS_METHOD_NAME( NAME ) _callNoArgsMethod__##NAME
#define PYCXX_VARARGS_METHOD_NAME( NAME ) _callVarArgsMethod__##NAME
#define PYCXX_KEYWORDS_METHOD_NAME( NAME ) _callKeywordsMethod__##NAME

// - - -

#define PYCXX_DECLARE_METHOD( THIS_CLASS, METHOD_NAME, Ax, NAME_OF_THIS_STATIC_METHOD, ... ) \
    \
    static PyObject* NAME_OF_THIS_STATIC_METHOD( PyObject* _pyObj_caller, PyObject* _a, PyObject* _k ) \
    { \
        DBG_LINE( Ax << #NAME_OF_THIS_STATIC_METHOD << Ax ); \
        try \
        { \
            Py::PythonClassInstance* base_cxx_obj   = reinterpret_cast< Py::PythonClassInstance* >( _pyObj_caller ); \
            THIS_CLASS*              this_class_obj = reinterpret_cast< THIS_CLASS* >             ( base_cxx_obj->m_pycxx_object ); \
            Py::Object result{  (this_class_obj -> METHOD_NAME)(__VA_ARGS__)  }; /* __VA_ARGS__ uses _a and _k (see below) */ \
            return Py::new_reference_to( result.ptr() ); \
        } \
        catch( Py::Exception & ) \
        { \
            DBG_LINE( "! ! !  Exception in PYCXX_DECLARE_METHOD ! ! !" ); \
            return 0; \
        } \
    }

#define PYCXX_NOARGS_METHOD_DECL(   _class, name ) PYCXX_DECLARE_METHOD( _class, name, "  &  "     , PYCXX_NOARGS_METHOD_NAME(   name ) )
#define PYCXX_VARARGS_METHOD_DECL(  _class, name ) PYCXX_DECLARE_METHOD( _class, name, "  & &  "   , PYCXX_VARARGS_METHOD_NAME(  name ), Py::Tuple{_a} )
#define PYCXX_KEYWORDS_METHOD_DECL( _class, name ) PYCXX_DECLARE_METHOD( _class, name, "  & & &  " , PYCXX_KEYWORDS_METHOD_NAME( name ), Py::Tuple{_a}, _k?Py::Dict{_k}:Py::Dict{} )

... and

#define PYCXX_ADD_METHOD( py_name, method_name, docs, flags ) \
    add_method( \
               #py_name, \
               (PyCFunction)method_name, \
               flags, \
               docs \
               )

#define PYCXX_ADD_NOARGS_METHOD(   py_name, name, docs )  PYCXX_ADD_METHOD( py_name, PYCXX_NOARGS_METHOD_NAME(   name ), docs, METH_NOARGS )
#define PYCXX_ADD_VARARGS_METHOD(  py_name, name, docs )  PYCXX_ADD_METHOD( py_name, PYCXX_VARARGS_METHOD_NAME(  name ), docs, METH_VARARGS )
#define PYCXX_ADD_KEYWORDS_METHOD( py_name, name, docs )  PYCXX_ADD_METHOD( py_name, PYCXX_KEYWORDS_METHOD_NAME( name ), docs, METH_VARARGS | METH_KEYWORDS )

It is used in a class to expose certain methods to Python:

Py::Object new_style_class_func_noargs( void )
{
    std::cout << "new_style_class_func_noargs Called."           << std::endl << std::endl;
    std::cout << "value ref count " << m_value.reference_count() << std::endl << std::endl;
    return Py::None();
}
PYCXX_NOARGS_METHOD_DECL( new_style_class, new_style_class_func_noargs )

static void init_type(void)
{
    :
    PYCXX_ADD_NOARGS_METHOD(    func_noargs , new_style_class_func_noargs,  "docs for func_noargs"  );
}

The reason for this architecture is that Python can only fit "extern C" style functions into its tables.  But this code is attempting to run C++ instance member functions.

Hence it has to trampoline off a static member function (as a static member function type casts to an "extern C" style function).

And we require a separate static member function for each method we wish to expose.

Is there any way to use templates to accomplish this?


texts: Finding closest points without duplicates and given distance threshold

texts:
Given a bunch of latitudes and longitudes stored as Points, I would like to determine the points that are closest to each point given some maximum threshold in meters. This is my first stab at this:

DECLARE @ThresholdInMeters FLOAT = 1000000.0;

IF OBJECT_ID('tempdb..#Points1') IS NOT NULL
    DROP TABLE #Points1
CREATE TABLE #Points1
    (
      PointId INT IDENTITY(1, 1) ,
      Point GEOGRAPHY NULL
    )

DECLARE @LowerLatitude FLOAT;
DECLARE @UpperLatitude FLOAT;
DECLARE @RandomLatitude FLOAT;
DECLARE @LowerLongitude FLOAT;
DECLARE @UpperLongitude FLOAT;
DECLARE @RandomLongitude FLOAT;
DECLARE @Counter INT;

SET @LowerLatitude = -90
SET @UpperLatitude = 90
SET @LowerLongitude = -180
SET @UpperLongitude = 180

SET @Counter = 100;
WHILE ( @Counter > 0 )
    BEGIN
        SELECT  @RandomLatitude = ( ( @UpperLatitude - @LowerLatitude - 1 )
                                    * RAND() + @LowerLatitude );
        SELECT  @RandomLongitude = ( ( @UpperLongitude - @LowerLongitude - 1 )
                                     * RAND() + @LowerLongitude );

        INSERT  INTO #Points1
                SELECT  GEOGRAPHY::Point(@RandomLatitude, @RandomLongitude,
                                         4326)

        SET @Counter = @Counter - 1;
    END

SELECT
    Points1.PointId AS StartPointId,
    Points2.PointId AS EndPointId,
    Points1.Point.STDistance(Points2.Point) AS Distance
FROM #Points1 AS Points1
INNER JOIN #Points1 AS Points2 ON Points1.PointId <= Points2.PointId
WHERE Points1.Point.STDistance(Points2.Point) < @ThresholdInMeters

Any ideas on how to potentially improve this, especially in performance? All indices are already set.


texts: Mail service implementation using Razor engine a MailMessage

texts:
This is a very basic Mailer service that I put together after finding out that MVC Mailer doesn't play nice with MVC 5.

public class MailerService
{
    private const string domainEmail = "admin@mydomain.com";
    private void Send(MailMessage mailMessage)
    {
        using (var smtpClient = new SmtpClient())
        {
            smtpClient.SendAsync(mailMessage,mailMessage);
            smtpClient.SendCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    //save it to nLog
                }
            };
        }
    }

    public void GenerateWelcome(AccountModel model)
    {
        var template = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Mailer/Templates/Welcome.html"));
        var body = Engine.Razor.RunCompile(template, "Welcome", typeof(AccountModel), model);

        this.Send
        (
            new MailMessage(domainEmail, model.Email)
            {
                Body = body,
                IsBodyHtml = true,
                Subject = "Welcome"
            }
        );
    }
}

The class is newed up in a base controller like so:

        public MailerService Mailer
    {
        get { return new MailerService(); }
    }

And then is called inside IHttpAction result with one line:

Mailer.GenerateWelcome(account);

I'm really looking to learn and improve regarding building my own custom implementations of such things as SMTP client and mail message. What is a better way to implement a mailer service like this, making it more generic and testable? What can go wrong here if lets say a 100 users hit this at the same time?


texts:
Finished my first lone project and I'm wondering if the execution is passable. This is a basic lbs to tons converter. The customer drives on the scale loaded, then dumps the load  and returns unloaded to the scale again. We need to convert the leftover lbs to tons. I am wondering if this is a concise way to perform this task.

loaded weight - unloaded weight = Total lbs in scrap

total lbs * 0.0005  = weight in tons

function calc() {
    let loadedAmount = document.getElementById("loaded").value;
    let unloadedAmount = document.getElementById("unloaded").value;
    let final = document.getElementById("result").value =
Math.round(`${(loadedAmount - unloadedAmount) * 0.0005}` * 100)/100;
    let resultInPounds = document.getElementById("result").value =
Math.round(`${(loadedAmount - unloadedAmount)}`);

    if (!loadedAmount) {
       document.getElementById("loaded").value=alert("waiting for an initial value for loaded");
    } else {
        loadedAmount = parseInt(loadedAmount);
    }
    if (!unloadedAmount) {
        document.getElementById("unloaded").value = alert("waiting for an initial value for unloaded");

    } else {
        unloadedAmount = parseInt(unloadedAmount);
    }
    if (loadedAmount < unloadedAmount) {
        alert("loaded amount must be greater than unloaded amount");
    }
    console.log(`loadedAmount: ${loadedAmount}`);
    console.log(`unloadedAmount: ${unloadedAmount}`);

    document.getElementById("result").innerHTML=final + " Tons or " +
resultInPounds + " lbs";

    console.log(result);

}
<!DOCTYPE html>

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

    Negaunee Iron and Metal

input loaded pounds
            <input type="number"  id="loaded" placeholder="Loaded...">

 input unloaded pounds
            <input type="number" id="unloaded" placeholder="Unloaded" >

        <button type="submit" id="button" onclick="calc()">Click To
Convert</button>