texts:
Each field is prone to throw an exception if not found. If one element not found, then the next should be checked. I have put each element in a separate try/catch. Is this a correct approach or can it be optimized?

def getLinkedinDetails(self, gearman_worker, gearman_job):
    driver = webdriver.PhantomJS('/usr/local/bin/phantomjs')
    user_input = gearman_job.data
    user_input_list = user_input.split()
    if len(user_input_list) == 2:
        first = user_input_list[0]
        last = user_input_list[1]
    elif len(user_input_list) == 1:
        first = user_input_list[0]
        last = ''
    print "https://www.linkedin.com/pub/dir/?first="+first+"&last="+last
    driver.get("https://www.linkedin.com/pub/dir/?first="+first+"&last="+last)
    driver.set_window_size(1124, 850)
    try:
        wait = WebDriverWait(driver, 15)
        wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "content-wrapper")))
    except:
        "print timed out"
    final_result = []
    for s in driver.find_elements_by_class_name('vcard'):
        result = {}
        try:
            name = s.find_element_by_class_name('given-name').text
            result['name'] = name
            surname = s.find_element_by_class_name('family-name').text
            result['surname'] = surname
            fullname = name + ' ' + surname
            if user_input.strip() == user_input.strip():
                pass
            else:
                continue
            title = s.find_element_by_class_name('title').text
            result['title'] = title
            location = s.find_element_by_class_name('location').text
            result['location'] = location
            profile_url = s.find_element_by_tag_name('a').get_attribute('href')
            result['profile_url'] = profile_url
        except:
            pass
        try:
            industry = s.find_element_by_class_name('industry').text
            result['industry'] = industry
        except:
            pass
        try:
            current = s.find_element_by_class_name('current-content').text
            result['current'] = current
        except:
            pass
        try:
            past = s.find_element_by_class_name('past-content').text
            result['past'] = past
        except:
            pass
        try:
            education = s.find_element_by_class_name('education-content').text
            result['education'] = education
        except:
            pass
        try:
            img = s.find_element_by_class_name('photo').get_attribute('src')
            result['img'] = img
        except:
            pass
        print result


texts: Data formatting, splitting objects & deleting key's/values

texts:
I am quite bad at data manipulation and after a lot of time I was finally able to get it working how I wanted. The thing is I don't like all the delete operations, I think the code can be a lot cleaner and the runtime seems somewhat slow on a lot of data. Code readability is very important here but it needs to be small, contained and fast. ES6+ i welcome and of course so are tips and general information.

Input Data:

{
  agency: "",
  agent: "",
  agent_email: "",
  agent_phone: "",
  date_of_birth: "2007-05-30",
  delivery_address: "address - 1",
  delivery_city: "city - 1",
  delivery_country: "PE",
  delivery_state: "state - 1",
  delivery_zipcode: "zip_code - 1",
  facebook: "",
  instagram: "",
  name: "Dustin Peter",
  primary_email: "wagnerpeter@bailey-schroeder.example.com",
  primary_phone_number: "+31622064234",
  residential_address: "address - 0",
  residential_city: "city - 0",
  residential_country: "LC",
  residential_state: "state - 0",
  residential_zipcode: "zip_code - 0",
  secondary_email: "garzajustin@vasquez.example.com",
  secondary_phone_number: "+39349330249",
  shoe_size: "38"
  snapchat: "",
  twitter: "",
  url: "",
  youtube: "",
}

End Result:

Data Set 1:

{
  name: "Dustin Peter",
  primary_email: "wagnerpeter@bailey-schroeder.example.com",
  primary_phone_number: "+31622064234",
}

Data Set 2:

{
  date_of_birth: "2007-05-30",
  delivery_address: {
    address: "address - 1",
    city: "city - 1",
    country: "PE",
    state: "state - 1",
    zip_code: "zip_code - 1",
  }
  residential_address: {
    address: "address - 0",
    city: "city - 0",
    country: "LC",
    state: "state - 0",
    zip_code: "zip_code - 0",
  }
  secondary_email: "garzajustin@vasquez.example.com",
  secondary_phone_number: "+39349330249",
  shoe_size: "38",
}

My Working Code:

const dataSet1 = {
  name: data.name,
  primary_email: data.primary_email,
  primary_phone_number: data.primary_phone_number,
};

const dataSet2 = {};
Object.keys(data).forEach((prop) => {
    if (data[prop]) { dataSet2[prop] = data[prop]; }
});

dataSet2.residential_address = {
    address: dataSet2.residential_address,
    city: dataSet2.residential_city,
    country: dataSet2.residential_country,
    state: dataSet2.residential_state,
    zip_code: dataSet2.residential_zipcode,
};

dataSet2.delivery_address = {
    address: dataSet2.delivery_address,
    city: dataSet2.delivery_city,
    country: dataSet2.delivery_country,
    state: dataSet2.delivery_state,
    zip_code: dataSet2.delivery_zipcode,
};

delete dataSet2.name;
delete dataSet2.primary_email;
delete dataSet2.primary_phone_number;
delete dataSet2.residential_city;
delete dataSet2.residential_country;
delete dataSet2.residential_state;
delete dataSet2.residential_zip_code;
delete dataSet2.delivery_city;
delete dataSet2.delivery_country;
delete dataSet2.delivery_state;
delete dataSet2.delivery_zip_code;


texts:
I have tried to design a class for a complete graph.

Needless to say, disadvantages of my current solution are very visible:

dependent inputs have led to verification headaches.

In this code we rely on 2 inputs set of nodes and edge map. This creates the need to add a special verification function called addEdgeVerification to ensure both these
data structures are in sync.how to avoid this complexity of inter-parameter dependency at the same not burdening the client with headache of providing a complex data structure as input to our code ?
forces illegal states when some functions are invoked out of sequence.

This code returns illegal state if getAdj is called before complete graph has been constructed. How can this illegal state issues be avoided, without the need to force user to provide a complete graph ? Note the name of code is CompleteGraphConstructor. This means users will make use of our code to construct a complete graph. We dont users to take any effort to construct graph themselves. We want them to provide tiny inputs such as edges and nodes, and we should take the pain to join pieces.

But alternatives are also not free from handicaps:

dumping everything in constructor would make it a god constructor

A constructor can help us reduce/eliminate illegal state. But it would result in god constructors.  It does not look like a good option, either.

I am looking for recommendations on code architecture.

public class CompleteGraphConstructor<T> {

    private final Map<T, HashMap<T, Double>> graph;
    private Set<T> nodes;

    public CompleteGraphConstructor() {
        graph = new HashMap<T, HashMap<T, Double>>();
    }

    /**
    * Add the nodes needed to be part of a graph.
    *
    * @param nodes     the set nodes to add in the graph.
    * @return           true if nodes list is set, and false if it is not.
    */
    public boolean addNodes (Set<T> nodes) {
        // prevent overriting the nodes.
        if (this.nodes != null) {
            /**
            * Should exception check be performed inside or outside?
            */
            if (nodes == null) throw new NullPointerException("The node cannot be null.");
            if (nodes.size() == 0) throw new NullPointerException("The size of node cannot be zero.");
            this.nodes = nodes;
            return true;
        }
        return false;
    }

    /**
    * Add all edges of the graph.
    *
    * @param nodeId  if nodeId is not null.
    * @param allEdges   all the edges of input node
    */
    public void addEdges (T nodeId, Map<T, Double> allEdges) {

        addEdgeVerification(nodeId, allEdges);

        graph.put(nodeId, (HashMap<T, Double>) allEdges);
    }

    private void addEdgeVerification(T nodeId, Map<T, Double> allEdges) {
        if (!nodes.contains(nodeId)) throw new NoSuchElementException("The source node: " + nodeId + " does not exist.");

        // making sure that edges include nodes provided in the node Set.
        for (T node : allEdges.keySet()) {
            if (!nodes.contains(node)) throw new NoSuchElementException("The target node: " + nodeId + "  not exist.");
        }

        // make sure that all the nodes in the edge set are included in allEdges
        for (T node : nodes) {
            if (node != nodeId) {
                if (!allEdges.containsKey(nodeId)) throw new IllegalArgumentException("The input map does not contain all edges. ");
                }
            }
        }

    public Map<T, Double> getAdj (T nodeId) {
        if (!nodes.contains(nodeId)) throw new NoSuchElementException("The node " + nodeId + " does not exist.");
        if (!graph.containsKey(nodeId)) throw new IllegalStateException("The graph is not populated with " + nodeId);

        return graph.get(nodeId);
    }
}


texts: Bitmask, How to abstract those callbacks in this implementation

texts:
I've made an POC about a bitmask implementation in order to replace a huge if/else statement.

Those statements are about strings and I have almost 15 /20 string to test. Depends on values the if/else statement was about 1500 lines of code.

After refactoring I was able to have only 20 objects and a map with all my callbacks in a "handler" class.

The code is working well, but I'm sure it can be improved.

<?php
declare(strict_types=1);

namespace App\Api\Application\Service;

abstract class AbstractValue implements BitwiseCallback
{
    protected $flag;
    public static function getFlag($value): BitwiseCallback
    {
        $class = get_called_class();
        $var = new $class();
        $var->bitValue = $value ? $var->flag : 0;
        return $var;
    }
    protected $bitValue;
    public function bitValue(): int
    {
        return $this->bitValue;
    }
}

<?php
declare(strict_types=1);
namespace App\Api\Application\Service;

interface BitwiseCallback
{
    static function getFlag($value): BitwiseCallback;
    public function bitValue(): int;
}

<?php
declare(strict_types=1);
namespace App\Api\Domain\ValueObject;

use App\Api\Application\Service\VarA;
use App\Api\Application\Service\VarB;
use App\Api\Application\Service\VarC;
use App\Api\Application\Service\VarX;

/**
 * Object Calisthenics or how to use lookup map and biwise map to refactor a huge if statement.
 * Class Test
 * @package App\Api\Domain\ValueObject
 */
class Test
{
    public function aMethod($values)
    {
        $a = VarA::getFlag($values[0]);
        $b = VarB::getFlag($values[1]);
        $c = VarC::getFlag($values[2]);

        $x = VarX::getFlag($values[5]);
// and so on

        $flags = $a->bitValue() | $b->bitValue() | $c->bitValue();
        $map = [
            1 => function() use ($a) { $a->doStuff(); },
            3 => function() use ($a, $b) { return $a->doStuff() . $b->doOtherStuff() . $a->toStuffWithB($b);},
            5 => function() use ($a, $c) { return $c->doStuff() . $b->doOtherStuff() . $c->toStuffWithB($b);},

            // and so on
            35 => function() use ($a, $b, $x) { return $x->sendEmailToAdmin($a, $b) ;}
            // and so on
        ];
        $result = $map[$flags];
        return $result();
    }
}

VarA / VarB / VarC/ and so on are like this

<?php
declare(strict_types=1);
namespace App\Api\Application\Service;
class VarA extends AbstractValue
{
    protected $flag = 1;

    public function doStuff()
    {
        return "This is a correct answer ...";
    }

    public function toStuffWithB($b)
    {
        return ' and you earned a bonus point !';
    }
}

<?php
declare(strict_types=1);
namespace App\Api\Application\Service;

use App\Api\Application\Service\VarA;
use App\Api\Application\Service\VarB;

class VarX extends AbstractValue
{
    protected $flag = 32;

    public function sendEmailToAdmin(VarA $a, VarB $b)
    {
// do stuff with varB and varA because VarX has been triggered
        return "We correctly aknowledge your answer, you'll be notify soon by our customer services";
    }
}

I can't show the real code with the proper names but the implementation remains the same. But' the whole thing is about a quiz with a custom baseline to show depends on answers, each stuff to do are very different depends on the bits (store data to a file / send notification to admin / send a mail about an answer given and so on).

So basically my class that handle the callback map is quite huge.

$map = [
            1 => function() use ($a) { $a->doStuff(); },
            3 => function() use ($a, $b) { return $a->doStuff() . $b->doOtherStuff() . $a->toStuffWithB($b);},
            5 => function() use ($c, $b) { return $c->doStuff() . $b->doOtherStuff() . $c->toStuffWithB($b);}
            // and so on
        ];

this part is quite ugly (around 200 lines of code in my code) with a lot of context and $options.


texts: Displaying the total and average for an array input

texts:
I'm currently taking my first class for c++ and our current lab is asking us to:

declare an array with a maximum of 100 integer
display total of all the scores
display the average of scores entered
have a negative as a sentinel since the scores all will be positive (the sentinel is -1)

afterwards We're then supposed to display the entered scores in descending order.

What I currently have is this:

#include <iomanip>
#include <iostream>
using namespace std;

void header();

int main()
{

    const int number = 100; // total number of allocated array inputs.
    int myArray[number], //array set
        counter = 0; // current array input number (1~100)
    double total = 0, // total for all scores added up
        average; // the average point for the scores.

    header(); // for calling title and description.

    cout << "Please enter the test scores you recieved." << endl;
    cout << "Once all scores are in, enter -1 to end input" << endl << endl;

    while (cin >> myArray[counter] && myArray[counter] != -1)
    {
         total += myArray[counter]; // adds all inputs for grand total.
         counter++;
        average = total / counter; // grand total / number of input
    }

    cout << "The total for all the scores is " << total << endl;
    cout << endl << "Average score is " << fixed << average << endl;

    cout << endl << "Program ending, shutting down." << endl;
    return 0;
}

void header() // simple header for lab description.
{
    cout << "***********************************" << endl;
    cout << "Lab 7:score array " << endl;
    cout << "Programmed by: ~~~ " << endl;
    cout << "This array will allow the user to enter up to 100 test scores," << endl;
    cout << "Show the total for the the inputted scores, and display the average score rounded." << endl;
    cout << "***********************************" << endl << endl;
}

It works for the most part, but think that the while loop is probably wrong.

Am I on the right track or is this a mess?


texts:
I am trying to write a program that will read the highest and lowest voltage along with its associated amp and time. I am able to find the max, but I am getting all zeros for the minimum value. I need help. Please and thank you.

Sample of txt file:

Time    Volt    Ampere
0.0001  9.77667 0.147408
0.00015 9.76583 0.147525
0.0002  9.76833 0.147692
0.00025 9.75833 0.147442
0.0003  9.76833 0.147192
0.00035 9.78167 0.1473
0.0004  9.76667 0.147317
0.00045 9.765   0.14715
0.0005  9.75667 0.147
0.00055 9.765   0.14695
0.0006  9.77    0.1471
0.00065 9.7675  0.147417
0.0007  9.7725  0.147417
0.00075 9.755   0.14735
0.0008  9.765   0.147725
0.00085 9.76583 0.147783

Expected Min Output:

Time = 0.00075  Volt = 9.755 Ampere = 0.14735

Expected Max Output:

Time= 0.00035 Volt = 9.78167 Ampere = 0.1473

int main(void)
{
//Declare Variables
string a, b, c;

double time, volt, ampere;
double maxVolt = 0, maxTime, maxAmpere;
double minVolt = 10, minTime, minAmpere;

//Read from the Volts.txt file
ifstream myFile("D:\\tabit\\Documents\\Volts.txt");

//Check if the file can be opened
if (myFile.is_open())
{
    while (myFile >> a >> b >> c)
    {
        time = atof(a.c_str());
        volt = atof(b.c_str());
        ampere = atof(c.c_str());

        if (volt >= maxVolt)
        {
            maxTime = time;
            maxVolt = volt;
            maxAmpere = ampere;
        }
        if (volt < minVolt)
        {
            minTime = time;
            minVolt = volt;
            minAmpere = ampere;
        }
    }
    //Close the file
    myFile.close();
}
//Give error message if the file cannot be opened
else return(1);

//Display the Maximum results
cout << "Max Volt: " << maxVolt << endl;
cout << "Max Time: " << maxTime << endl;
cout << "Max Ampere: " << maxAmpere << endl;

//Display the Minimum results
cout << "Min Volt: " << minVolt << endl;
cout << "Min Time: " << minTime << endl;
cout << "Min Ampere: " << minAmpere << endl;

return 0;
}


texts:
Print the first 10 lines of a file, if it has less than 10 lines, print the whole file.

Any suggestions on any kind of improvement are welcome.

package je3.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by IDEA on 29/01/15.
 */
public class Head {
    public static String[] headLines(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String[] lines = new String[10];
        String line;
        int nLine = 0;
        while((line = reader.readLine()) != null) {
            lines[nLine++] = line;
            if(nLine >= 10) {
                break;
            }
        }
        return lines;
    }

    public static void main(String[] args) throws IOException {
        if(args.length != 1) {
            throw new IllegalArgumentException();
        }
        String[] lines = headLines(args[0]);
        for(String line : lines) {
            if(!line.isEmpty()) {
                System.out.println(line);
            }
        }
    }
}


texts:
I wrote a simple tree data type in Java consisting of nodes which are themselves trees, and where each tree has its own list of children (not a binary tree). I plan on eventually using it in a minimax algorithm where I keep track of future game states in a board game by holding different board states in nodes and holding moves that lead to each state as edges in the tree. Here's my code so far — any suggestions (whether it be conceptual or performance related, or other features I should add) are appreciated:

public class Tree<V, E> {
   private V data;
   //here the edgeVal is the edge leading from the node's parent to the node itself,
   //not from the node to any of its children
   private E edgeVal;
   private Tree<V, E> parent;
   private ArrayList<Tree<V, E>> children;
   public Tree(V data, Tree<V, E> parent, E edgeVal) {
      this.data = data;
      this.edgeVal = edgeVal;
      this.parent = parent;
      this.children = new ArrayList<Tree<V, E>>();
   }
   public void addChild(V childData, E edgeVal) {
      Tree<V, E> child = new Tree<V, E>(childData, this, edgeVal);
      this.children.add(child);
   }
   public Tree<V, E> getParent() {
      return this.parent;
   }
   public ArrayList<Tree<V, E>> getChildren() {
      return this.children;
   }
   public V getData() {
      return this.data;
   }
   public E getEdgeVal() {
      return this.edgeVal;
   }
   public boolean isRoot() {
      return this.parent == null;
   }
   public boolean isLeaf() {
      return this.children.size() == 0;
   }
   public String toString() {
      //assuming type of data has a nicely defined toString() method
      return this.data.toString();
   }
}


texts: Is this correct usage of the "Decorator" Pattern?

texts:
I have a model class Product that gets populated from a service DTO object (using AutoMapper).  The service is used to power many different applications and for each one the Product Model might need to behave a bit differently.  After a bit of research I decided the 'Decorator' pattern might be a good choice to accompany these differences.  Here is how I currently have implemented it.

These classes are part of a library that gets included in each of the applications

public class Product
{
    public virtual string ProductName { get; set; }
    public virtual Decimal Price { get; set; }
    public virtual string ImageUrl { get; set; }

    public virtual string GetImageUrl(){
        return ImageUrl;
    }
}

public abstract class ProductDecorator : Product
{
    private Product decoratedProduct; // the product being decorated

    protected ProductDecorator(Product decoratedProduct)
    {
        this.decoratedProduct = decoratedProduct;
    }

    public override string ProductName
    {
        get
        {
            return decoratedProduct.ProductName;
        }
        set
        {
            decoratedProduct.ProductName = value;
        }
    }
    public override decimal Price
    {
        get
        {
            return decoratedProduct.Price;
        }
        set
        {
            decoratedProduct.Price= value;
        }
    }
    public override string ImageUrl
    {
        get
        {
            return decoratedProduct.ImageUrl;
        }
        set
        {
            decoratedProduct.ImageUrl= value;
        }
    }
}

In each application there may be need to slightly change the model.

public class FooProduct : Model.ProductDecorator
{
    public FooProduct (Model.Product product) :base(product){}

    //we want to serve the image through a cdn
    public override string GetImageUrl()
    {
        return string.Format("cnd.network.com?url={0}", HttpUtility.HtmlEncode(ImageUrl));
    }
}

Usage would be something like this:

 FooProduct prod = new FooProduct(productClient.GetProduct(23213));
 Response.Write(prod.GetImageUrl());

This is my first time using this pattern and I'm not sure if I've got it quite right or if it really applies to this scenario.  Are there any foreseeable issues with this solution?

Update

I think I need to explain a little more how I got here.

I created a class library to encapsulate an wcf service.  The library takes the DTO's returned by the service and using AutoMapper, maps the DTO to the Product class.  The issue is that the product model needs to be a bit different for each of the applications consuming the service.  Just using simple inheritance not quite right because a FooProduct needs to pretty much be exactly the same as a Product but just handle the data a bit differently.

// this returns a Product, but for this site I need a FooProduct
var product = Client.GetProduct(232);

This problem is probably a result of bad design in lower layers and from the use of AutoMapper in Client Library.


texts: Produce the sum of all white space separated integers in a given file

texts:
How's my code?  Works perfectly for what I'm trying to do :)
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<fstream>
#include<assert.h>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

int main() {
    int sum{ 0 }, number;
    vector<int> numbers;
    string word;
    fstream file;
    file.open("file1.txt", fstream::in);

    while (true) {
        file >> number;
        if (file.eof()) {
            numbers.push_back(number);
            break;
        }
        else if (file.fail()) {
            file.clear();
            file >> word;
        }
        else if (file.bad()) exit(1);
        else numbers.push_back(number);
    }

    for (int x : numbers) sum += x;

    cout << sum << "\n";

}

Here's the file I'm reading from:
words 32 jd: 5 alkj 3 12 fjkl: 23 / 32
hey 332 2 jk 23 k 23 ksdl 3
32 kjd 3 klj 332 c 32


texts: Passing around context.Context in Golang

texts:
I am currently "gracefully" handling HTTP server net/http shutdown which works perfectly fine (I am not asking you to review server shutdown). As seen in the code below the context is created first time directly in server package when I run the application. What I've done afterwards is (this is the one I would like you to review please), I've created a context.Background() before calling the server and pass it to server. Is this acceptable/feasible practise in Golang?

Why I want to create a context beforehand while everything is already working fine?

It is because I need a few key-value pair in context so that I can use them throughout the application.

CURRENT IMPLEMENTATION WITH CONTEXT IN SERVER

cmd/auth/main.go

package main

import (
    "github.com/BentCoder/auth/internal/http"
)

func main() {
    srv := http.NewServer(":8011", 10)
    srv.Start()
}

internal/http/server.go

package http

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

type Server struct {
    http    *http.Server
    timeout int64
}

func NewServer(adr string, tim int64) Server {
    return Server{
        http: &http.Server{
            Addr: adr,
        },
        timeout: tim,
    }
}

func (srv *Server) Start() {
    log.Infof("starting HTTP server")

    idle := make(chan struct{})

    go shutdown(srv.http, idle, srv.timeout)

    if err := srv.http.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatalf("failed to start/close HTTP server [%v]", err)
    }

    <-idle

    log.Info("shutdown HTTP server")
}

func shutdown(srv *http.Server, idle chan<- struct{}, tim int64) {
    sig := make(chan os.Signal, 1)

    signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

    <-sig

    log.Infof("shutting down HTTP server in '%d' sec", tim)

    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(tim)*time.Second)
    defer cancel()

    if err := srv.Shutdown(ctx); err != nil {
        log.Fatalf("failed to shutdown HTTP server [%v]", err)
    }

    close(idle)
}

output

INFO[0000] starting HTTP server                          source="server.go:42"
^C
INFO[0004] shutting down HTTP server in '10' sec         source="server.go:82"
INFO[0004] shutdown HTTP server                          source="server.go:54"

THIS IS WHAT I DECIDED TO DO

package main

import (
    "context"
    "github.com/BentCoder/auth/internal/http"
)

func main() {
    ctx := context.WithValue(context.Background(), "SomeKey", "SomeVal")

    srv := http.NewServer(":8011", 10)
    srv.Start(ctx)
}

And update server package (the relevant bit) as seen below.

func shutdown(ctx context.Context, .....
    ...
    ctx, cancel := context.WithTimeout(ctx, time.Duration(tim)*time.Second)
    ...
}


texts: Return correct subclass instance, identified by string

texts:
I have made a function which takes a string which can be any of "triangle", "square" or "rectangle".
Depending on the string I return a pointer to an instance of class Form. My class Form has subclasses Triangle, Square and Rectangle.
My constraints were:

use C++98
no STL library (no map, vector etc)
no friend, and no using namespace std;

#include <iostream>
#define NB_FORMS 3

/**/

class Form
{
  public:
    Form() { }
    virtual ~Form() { }
};

class Square : public Form
{
  public:
    Square() { std::cout << "Squareee!" << std::endl; }
     static Form *createForm(void)
     {
       return (new Square());
     }
};

class Rectangle : public Form
{
  public:
    Rectangle() { std::cout << "Rectangleee!" << std::endl; }
    static Form *createForm(void)
    {
      return (new Rectangle());
    }
};

class Triangle : public Form
{
  public:
    Triangle() { std::cout << "Triangleee!" << std::endl; }
    static Form *createForm(void)
    {
      return (new Triangle());
    }
};

struct        s_makeForms
{
    std::string        formName;
    Form            *(*makeForm)();
};

/* */

Form *func(std::string name)
{
  struct s_makeForms allForms[3] =
  {
      {"triangle",  Triangle::createForm},
      {"rectangle", Rectangle::createForm},
      {"square", Square::createForm}
  };
  for (int i = 0; i < NB_FORMS; i++)
  {
    if (name == allForms[i].formName)
      return (allForms[i].makeForm());
  }
  return (NULL);
}

int main()
{
  Form *myform;

  if (!(myform = func("square")))
  {
    std::cerr << "wrong name" << std::endl;
  }
  delete myForm;
}


texts:
I use the following code
<?php echo $obj->text; ?>
 in while loop.

Is this the best way?

Is there a better way, either to optimize or replace this code?

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){

?>

<?php echo $obj->text; ?>

<?php
    }
?>


texts: Code to change the size of the fields based on that 2 fields are optional inside a contact form

texts:
In my React app using Material UI, I wrote a code to manage the size of the fields of a contact form. Those fields are elements that can be added or removed depending on a configuration.
The code I wrote works as should be but looks ugly and I need help to make it better
let size = 12;
    if (useMediaQuery(theme.breakpoints.up('sm'))) {
      const hasTime = fieldsConfig.some(
        f => f.name === 'preferredContactHours',
      );
      const hasContactType = fieldsConfig.some(
        f => f.name === 'preferredContactWay',
      );
      if (name === 'phone' && (!hasTime || !hasContactType)) size = 7;
      else if (name === 'preferredContactWay' && hasTime) size = 6;
      else if (name === 'preferredContactWay' && !hasTime) size = 5;
      else if (name === 'preferredContactHours' && hasContactType) size = 6;
      else if (name === 'preferredContactHours' && !hasContactType) size = 5;
    }

The size by default is 12 so if any of the conditions are not applicable the field will be full size in the grid.
After the if the hasTime and hasContactType are about that those fields are optional so I need to see if they are present or not.
The rest is the sizing and the conditions about it regarding if I have or not the field then is a specific size.
What I need is to have it better and efficient then all that verbose way if that could be possible.


texts: Append an annual total to all Excel files

texts:
I am new to all this and figured, after doing some tutorials, the best way to get some proper experience is to simply start a little project.

I have yearly folders with Excel files in it, those are roughly the same, only last year I made a change to the structure of them.
My aim was to cycle through them all and add one value of them to a list, and then compare those results.
So far, this all works out as I hoped.
I have not figured out yet however, how to define the part that reads the excel files into a callable object ((?)hope that's the correct term).

My main question is, how efficient, or inefficient is this script I wrote?
I assume, one could reduce the length of this code a lot.

import os
import openpyxl

my_list_2015 = []
my_list_2016 = []
my_list_2017 = []
year_show = 2015

def brutto_total(netto):
    brutto = netto + netto * 0.2
    return '%.2f' %  brutto

def show_result(year):
    global year_show
    print("-" * 14 + str(year_show) + "-" * 14)
    print("Total Sum Netto 2015:   " + str('%.2f' % year))
    print("Total Sum Brutto 2015:  " + str(brutto_total(year)))
    year_show = year_show + 1
    return year_show

for i in os.listdir(os.chdir('path_to_excel_files')):
    if i.endswith(".xlsx"):
        workbook = openpyxl.load_workbook(i, data_only=True)
        sheet = workbook['Blatt1']
        c=sheet['L46'].value
        my_list_2015.append(c)
        my_list_total_2015 = sum(my_list_2015)

for i in os.listdir(os.chdir('path_to_excel_files')):
    if i.endswith(".xlsx"):
        workbook = openpyxl.load_workbook(i, data_only=True)
        sheet = workbook['Blatt1']
        c=sheet['L46'].value
        my_list_2016.append(c)
        my_list_total_2016 = sum(my_list_2016)

for i in os.listdir(os.chdir('path_to_excel_files')):
    if i.endswith(".xlsx"):
        workbook = openpyxl.load_workbook(i, data_only=True)
        sheet = workbook['Zusammen']
        c=sheet['C11'].value
        my_list_2017.append(c)
        my_list_total_2017 = sum(my_list_2017)

show_result(my_list_total_2015)
show_result(my_list_total_2016)
show_result(my_list_total_2017)


texts:
I have a limit of 100 sessions (each session held in an object). Many threads will be requesting sessions, and it is very possible that all 100 sessions could be in use at any time.

I'm a Junior Developer. I saw the Object Pool pattern and decided that it looked appropriate. What do you think? If no sessions are avaible, the thread that requested it will get an Exception back and have to try again.

I'm using IOC with ISessionPool as a singleton. In testing it seems to work well, but I'd appreciate any feedback.

public class SessionPool<T> : ISessionPool<T>
{
    private readonly List<T> _inUse;
    private readonly List<T> _available;
    private readonly Action<T> _cleanerAction;

    /// <summary>
    /// Creates an object pool for objects of type T.
    /// NOTE: All availbale instances are initialised immediately.
    /// </summary>
    /// <param name="instanceCreator">A function that creates objects of type T</param>
    /// <param name="maxInstances">The maximum number of instances</param>
    /// <param name="cleanerAction">An action that cleans up the object before it is returned to the pool</param>
    public SessionPool(Func<T> instanceCreator, int maxInstances, Action<T> cleanerAction)
    {
        _inUse = new List<T>(maxInstances);
        _available = new List<T>(maxInstances);
        _cleanerAction = cleanerAction;

        CreateAllInstances(instanceCreator, maxInstances);
    }

    private void CreateAllInstances(Func<T> instanceCreator, int numberOfInstances)
    {
        for (int i = 0; i < numberOfInstances; i++)
        {
            _available.Add(instanceCreator.Invoke());
        }
    }

    public T GetSession()
    {
        lock (_available)
        {
            if (_available.Count == 0)
            {
                throw new NoAvailableSessionsException("Unable to get session");
            }
            else
            {
                T toReturn = _available[0];
                _inUse.Add(toReturn);
                _available.RemoveAt(0);
                return toReturn;
            }
        }
    }

    public void ReleaseSession(T session)
    {
        // Clean up the object before making it available again
        _cleanerAction.Invoke(session);

        lock (_available)
        {
            _available.Add(session);
            _inUse.Remove(session);
        }
    }

    public int GetAvailableSessionCount()
    {
        lock (_available)
        {
            return _available.Count;
        }
    }
}


texts:
I created a following class to manage multithreading without extra overhead, which exist when I use Parallel TPL class. It is also useful for systems without TPL.

Can it be enchanced?

    public static void Foreach<T>(this ICollection<T> source, Action<T> action)
    {
        var allDone = new ManualResetEventSlim(false);
        int completed = 0;
        foreach (var item in source)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                var closure = (T)state;
                action(closure);
                if (Interlocked.Increment(ref completed) == source.Count)
                    allDone.Set();
            }, item);
        }
        allDone.Wait();
    }

    public static void Do(Action action1, Action action2)
    {
        var firstTask = QueueWaitableTask(action1);
        action2();
        firstTask.Wait();
    }

    public static ManualResetEventSlim QueueWaitableTask(Action action)
    {
        var result = new ManualResetEventSlim(false);
        ThreadPool.QueueUserWorkItem(mse =>
        {
            action();
            ((ManualResetEventSlim) mse).Set();
        }, result);
        return result;
    }


texts:
Usually, AsyncTasks are meant to be one-shot, i.e. you start it, it fetches some data, displays the result and dies. However, I'm now using a long-running AsyncTask to load images as the need arises. So far it's working great, but I'd just like to know if this is good practice & if there's any threading detail that I missed. Here's my slimmed down implementation:

public class ImageLoader extends AsyncTask<Void, Object, Void> {
    private final List<String> pendingURLs = new Vector<String>();
    private Thread backgroundThread;

    @Override
    protected Void doInBackground(Void... params) {
        this.backgroundThread = Thread.currentThread();
        while (!backgroundThread.isInterrupted()) {
            String url = null;
            synchronized(this) {
                if (pendingURLs.size() > 0) {
                    url = pendingURLs.remove(0);
                }
            }
            if (url != null) {
                // fetch image...
                publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component
            }
            try {
                synchronized(this) {
                    if (pendingURLs.size() == 0) {
                        wait();
                    }
                }
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    public syncrhonized void addUrl(String url) {
        pendingURLs.add(url);
        notify();
    }

    public Thread getBackgroundThread() {
        return backgroundThread;
    }

}

Then, in my Fragment#onCreate() I create a new instance and execute it like this:

mLoader = new ImageLoader();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    mLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
    mLoader.execute();
}

Finally, in my Fragment#onDestroy() I do:

if (mLoader != null && mLoader.getBackgroundThread() != null) {
    mLoader.getBackgroundThread().interrupt(); // this will cause it to break out of the while loop and finish the thread
}


texts: Algorithm generating a unique ID based on client name

texts:
Following code is supposed generate a new ID (PID) for a new client based on the client name's first letter and the existing IDs in the range which are stored in a database.

For ex lets say if the new client's name is "Abc" and if last ID in the database starting from  letter A, is A200. Then the new ID should be A201.

This code compiles and runs giving the desired out put but I hope this could be optimized further.

Expecting your suggestions on improving this...

private void GeneratePIDforNewPoint(string pointName)
{
    string firstLetterOfPointName; // variable to hold first letter of "point name" being passed to this method
    string lastExistingPID; // variable to hold the last PID (most recent hence largest) from the list of PIDs retrieved from the database
    int lastDigitOfExistingPID; // variable to hold last digit of the "lastPID" (ex- digit '2' from PID 'F002')
    string finalPID; // variable to hold out put (the generated new PID for the new point)...

    firstLetterOfPointName = pointName[0]; // Get the fist letter of the point name...

    List<string> pidList=_ds.GetPIDs(firstLetterOfPointName); // Calling method to get the pid list from database

    if (pidList.Count >=1) //  At the end of this if block, numeric part of the new PID will be desided
    {
        pidList.Sort();
        lastExistingPID = pidList[pidList.Count - 1];
        lastDigitOfExistingPID = int.Parse(lastExistingPID[lastExistingPID.Length - 1].ToString());
    }
    else
    {
        lastDigitOfExistingPID = 0;
    }

    lastDigitOfExistingPID += 1;

    // Found digit will be converted to the pid format by attaching the starting letter and zeros to make the length.(format --> A001/ B099 / C100 etc.)

    finalPID= firstLetterOfPointName + String.Format("{0:000}", lastDigitOfExistingPID );
    _view.PID = finalPID;
}

 public List<string> GetPIDs(string firstLetterOfPointName)
        {
            string selectStatement = @"SELECT PID FROM point WHERE PID like @PID";
            List<string> pidList = new List<string>(); // List to store all retrived PIDs from the database...

            // Retrieve all existing PIDs starting with "letter" from the database
            using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
                {
                    sqlCommand.Parameters.Add("@PID", SqlDbType.VarChar).Value = firstLetterOfPointName + '%';
                    sqlConnection.Open();
                    using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                    {
                        // If reader has data, are added to the list
                        while (dataReader.Read())
                        {
                            pidList.Add(dataReader.GetString(0).Trim());
                        }
                        return pidList;
                    }
                }
            }
        }


texts: Search a file system for files that match a given pattern

texts:
My concerns with this code:

Is there a more efficient way to find files by pattern in Python?
Does os.walk() work in Windows?
Is this code pythonic?
Should search() be broken down into 2 functions?
Is it stupid to handle IOError exception by printing the error msg to the console?

#!/usr/bin/env python

'''
Finding files by pattern
'''

import os
import fnmatch
from os.path import join

def search(base, patt):
    ''' Yield files that match a given pattern '''
    for root, dirs, files in os.walk(base):
        try:
            for _ in [join(root, _) for _ in files if fnmatch.fnmatch(_, patt)]:
                yield _
        except IOError as error:
            print error

def example_use(d, p):
    ''' Example use of search function '''
    for _ in search(d, p):
        print _

if __name__ == '__main__':
    example_use('/var', '*.log')


texts: Genetic algorithm for the minimum of the Schaffer function

texts:
I have to implement a genetic algorithm in R to optimize the minimum of the Schaffer function. Below I describe each step and I need to create one big function and another loop for 100 iterations (and from 100 iterations choose the best solution) for the Schaffer function. I would be grateful for any tips, where and how I can make a loop and implement everything in one function.

#1. create the size of population - constant
N <- 100
population <- matrix(runif(N*2,min=-100,max=100), N, 2)

#2. count schaffer function - y for each element of population
schaffer_mod <- function(xx,N) {
    x1 <- xx[1:N,1]
    x2 <- xx[1:N,2]

    fact1 <- (sin(x1^2-x2^2))^2 - 0.5
    fact2 <- (1 + 0.001*(x1^2+x2^2))^2

    y <- 0.5 + fact1/fact2
    return(y)
}

y <- schaffer_mod(population,100)
newpopulation <- cbind(population,y)

# 3. sort to achieve best solution (value of y) at the top
newpopulation.sort <-  newpopulation[order( newpopulation[,3]),]

# 4. choose the best 20% of solutions - by the best y
parents <- newpopulation.sort[1:20,1:2] #drop y value

# 5.CROSSING
#random choose the number of raws to take
raw1 <- sample(1:20,100, replace=T)
raw2 <- sample(1:20,100, replace=T)

#average from crossing parents
child1 <- (parents[raw1,1]+parents[raw2,2])/2
child2 <- (parents[raw1,2]+parents[raw2,1])/2
newpopulation <- matrix(c(child1,child2),100,2)

# 6. MUTATION
#choose random 20raws <- it this point I have to implement a loop, but do not know how I can do it correctly
gen20_1 <- sample(1:100,20)
gen20_2 <- sample(1:100,20)
child_gen20_1 <- matrix((newpopulation[gen20_1,1]),20,1)
child_gen20_2 <- matrix((newpopulation[gen20_2,1]),20,1)

# choose random which line to choose
# first operations of counting on first column - first child
nr1 <- sample(1:20,1)

mutation_value <- -100+runif(1)*200
a1 <- child_gen20_1[nr1,1] + mutation_value

if ((a1 > -100) && a1 < 100) #if its true, change the value in the matrix-newpopulation
{
  newpopulation[nr1,1] <- newpopulation[nr1,1]+mutation_value
}

# FOR THE SECOND COLUMN - SECOND CHILD
nr2 <- sample(1:20,1)

mutation_value <- -100+runif(1)*200
a2 <- child_gen20_2[nr2,1] + mutation_value

if ((a2 > -100) && a2 < 100)
{
  newpopulation[nr2,2] <- newpopulation[nr2,2]+mutation_value
}

#mutation should be counted 20 times for each column. would be grateful to advice, how I should create a loop

#7. new population after mutation
population <- newpopulation

#8. new y
y <- schaffer_mod(populacja,100)
population <- cbind(population,y)

#9. sort
newpopulation.sort <- population[order(population[,3]),]

  #10. result
    x1 = newpopulation.sort[1,1]
    x2 = newpopulation.sort[1,2]
    y = newpopulation.sort[1,3]

The aim is to make these 10 steps x100 times and choose x1,x2 for which y was the smallest one - searching for the minimum of the Schaffer function.


texts: Scraper to grab a Stack Overflow profile name

texts:
I've created a script in Python to log into stackoverflow.com using credentials and fetch the profilename once logged in. I've tried to do it using class. I created the methods within that class in such a way so that they work like chain. Should I stick to this design or there is anything better I can pursue? Whatever it is I would like this get_profile() method to be seperated like how it is now.

from bs4 import BeautifulSoup
import requests

class StackOverflowBot(object):

    login_url = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f"

    def __init__(self,session,username,password):
        self.session = session
        self.username = username
        self.password = password
        self.login(self.session,self.username,self.password)

    def login(self,session,username,password):
        session.headers['User-Agent'] = 'Mozilla/5.0'
        req = session.get(self.login_url)
        soup = BeautifulSoup(req.text, "lxml")
        payload = {
            "fkey": soup.select_one("[name='fkey']")["value"],
            "email": username,
            "password": password,
        }
        req = session.post(self.login_url,data=payload)
        return self.get_profile(req.text)

    def get_profile(self,htmlcontent):
        soup = BeautifulSoup(htmlcontent,"lxml")
        item = soup.select_one("[class^='gravatar-wrapper-']").get('title')
        print(item)

if __name__ == '__main__':
    with requests.Session() as session:
        StackOverflowBot(session,"username","password")


texts:
Can you suggest how I might make the following code more efficient:

from collections import Counter

a = [1,1,3,3,1,3,2,1,4,1,6,6]

c = Counter(a)

length = len(set(c.values()))

normalisedValueCount = {}
previousCount = 0
i = 0
for key in sorted(c, reverse=True):
    count = c[key]

    if not previousCount == count:
        i = i+1
        previousCount = count

    normalisedValueCount[key] = i/length

print(normalisedValueCount)

It basically gives a dictionary similar to counter, but instead of counting the number of occurrences, it contains a weighting based on the number of occurrences.

The number 1 is associated with 1.0 (4/length) because it occurs the most often.
2 and 4 occur the least often and are associated with the value 1/length.
6 is the second least occurring value and is associated with 2/length.
3 is the third least occurring value and is associated with 3/length.

Some more examples:

The list a[1,2,3] results in a normalisedValueCount of 1:1.0, 2:1.0, 3:1.0.
The list a[2,1,2] results in a normalisedValueCount of 2:1.0, 1:0.5.
The list a[2,1,2,3] results in a normalisedValueCount of 2:1.0, 1:0.5, 3:0.5.
The list a[2,2,2,2,2,2,2,2,2,2,1,2,3,3] results in a normalisedValueCount of 2:1.0, 3:0.66666, 1:0.33333.


texts: Gathering emails, phones, URIs, and tag related to a room

texts:
I've made a strange method with multiples conditionals, creating a lot of Lists and I was wondering if I could write it in a better and more legible way.

def findRooms(room:Room) = {
    ...
    if(room.id != null && !room.id.isEmpty)
      query+=("_id" -> room.id)
    if(room.members != null && room.members.length > 0){
      val emails = scala.collection.mutable.MutableList[String]()
      val phones = scala.collection.mutable.MutableList[String]()
      val forwardUris = scala.collection.mutable.MutableList[String]()
      for(member <- room.members){
        if(member.email != null && member.email != None)
          emails+=member.email.get
        if(member.forwardUrl != null && member.forwardUrl != None)
          forwardUris+=member.forwardUrl.get
        if(member.phoneNumber != null && member.phoneNumber != None)
          phones+=member.phoneNumber.get
      }

      if(emails.size > 0)
        query+=("members.user.email" -> MongoDBObject("$all" -> emails))

      if(phones.size > 0)
        query+=("members.user.phoneNumber" -> MongoDBObject("$all" -> phones))

      if(forwardUris.size > 0)
        query+=("members.user.forwardUrl" -> MongoDBObject("$all" -> forwardUris))
    }

    if(room.tags != null && room.tags.length > 0){
      val tags = scala.collection.mutable.MutableList[String]()
      for(tag <- room.tags){
        tags+=tag
      }
      if(tags.size > 0){
        query+=("tags" -> MongoDBObject("$in" -> tags))
      }
    }
    ...
}


texts: Most Efficient Solution for USACO: Triangles - Python

texts:
I'm trying to solve this problem with Python 3.8. In my code, I used 3 nested for loops to check every single point and storing the largest area with each set of points. This program works fine, but it's \$ O(n^3) \$ time complexity, and I'm wondering if there are any more elegant/efficient solutions. Is there a more efficient algorithm that doesn't loop through every single point, or is that necessary?
My code:
with open("triangles.in", "r") as file_in:
  lines = [x.strip() for x in file_in.readlines()]
  n, points = lines[0], lines[1:]

def main(points):
  largest = 0

  for corner in points:
    cx, cy = corner.split()
    for leg in points:
      lx, ly = leg.split()
      for width in points:
        wx, wy = width.split()
        if lx == cx and wy == cy:
          area = abs(int(ly)-int(cy)) * abs(int(wx)-int(cx))

          if area > largest:
            largest = area

  return str(largest)

with open("triangles.out", "w+") as file_out:
  file_out.write(main(points))
  file_out.close()

The input file triangles.in:
4
0 0
0 1
1 0
1 2

Problem synopsis:
Given a set of \$ n \$ distinct points \$ (X_1, Y_1) \$ to \$ (X_n, Y_n) \$, find the largest triangle's area multiplied by 2, given that the triangle is a right triangle (one of the lines of the triangle in parallel to the x-axis, and one other parallel to the y-axis).


texts:
I had an interview question like this:

  In a company there are different people. One can measure how well they
  suits for pair coding as follows:

  First, let us compute the PAIRS-value which is the number of letters
  P, A, I, R, S given in two people names. Then compute the sum of
  consecutive digits and sum of digits if the result is over 9.

  Then do the same for the numbers one got in previous step: sum two
  adjacent numbers and again, compute the sum of digits of every number
  if that number is > 10. Repeat this until you have only two digits,
  which measures the goodness of pairs. For example, "Erkki Esimerkki"
  and "Matti Meikäläinen" has PAIRS-value 58:

  First [P = 0, A = 1, I = 6, R = 2, S = 1] and then

[0 + 1 = 1, 1 + 6 = 7, 6 + 2 = 8, 2 + 1 = 3]
[1 + 7 = 8, 7 + 8 = 15 => 1 + 5 = 6, 8 + 3 = 11 => 1 + 1 = 2]
[8 + 6 = 14 => 1 + 4 = 5, 6 + 2 = 8]
[5, 8] = 58%

  Now, there are many worker names given in
  http://reaktor.fi/wp-content/uploads/2014/08/fast_track_generoitu_nimilista.txt
  . Find the number of perfect pairs, i.e. those who have PAIRS-value
  99%.

Is there a faster way to solve as the following code:

import urllib.request

def sum_digits(number):
    while number > 9:
       temp = number
       y1 = number//10
       y2 = temp % 10
       number = y1 + y2
    return number

def compute_percent(pairs):
    x1 = sum_digits(pairs[0] + pairs[1])
    x2 = sum_digits(pairs[1] + pairs[2])
    x3 = sum_digits(pairs[2] + pairs[3])
    x4 = sum_digits(pairs[3] + pairs[4])
    x5 = sum_digits(x1 + x2)
    x6 = sum_digits(x2 + x3)
    x7 = sum_digits(x3 + x4)
    x8 = sum_digits(x5 + x6)
    x9 = sum_digits(x6 + x7)
    return 10*x8+x9

if __name__ == '__main__':
    address1 = 'http://reaktor.fi/wp-content/uploads/2014/08/'
    address2 = 'fast_track_generoitu_nimilista.txt'
    address = address1 + address2
    agents1 = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36'
    agents2 = '(KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
    agents = agents1 + agents2

    req = urllib.request.Request(address, headers={'User-Agent': agents})
    r = urllib.request.urlopen(req)
    datas = r.read().decode('utf8')

    name = ""
    names = list()
    pairs = [0] * 5
    matches = list()
    for i in range(0,len(datas)):
        if (datas[i] == "\n"):
            names.append(name)
            name = ""
        else:
            name += datas[i]

    for i in range(0,len(names)):
        for j in range(i + 1,len(names)):
            common = names[i].lower() + names[j].lower()
            for i in range(0,len(common)):
                if (common[i]) == "p":
                    pairs[0] += 1
                if (common[i]) == "a":
                    pairs[1] += 1
                if (common[i]) == "i":
                    pairs[2] += 1
                if (common[i]) == "r":
                    pairs[3] += 1
                if (common[i]) == "s":
                    pairs[4] += 1
                for i in range(0,len(pairs)):
                    pairs[i] = sum_digits(pairs[i])

                percent = compute_percent(pairs)
                if percent == 99:
                    pari = "" + names[i] + " and " + names[j]
                    matches.append(pari)
    matches = list(set(matches))
    print(len(matches))


texts: Is this good login process in CodeIgniter?

texts:
I'm creating my first login process in CodeIgniter. I'm using the simpleloginsecure library for actual session management but I wrote the controller and model myself and I was hoping if you could see any flaws in it.

My User_model Class

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }

    function login($email, $password) {
        if($this->simpleloginsecure->login($email, $password)) {
            return true;
        }
        return false;
    }
}

?>

My User Controller class

<?php if(!defined('BASEPATH')) exit('No Direct script access allowed');

Class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
    }

    public function index() {
        if($this->session->userdata('logged_in')) {
            redirect('/user/dashboard/', 'location');
        } else {
            $data['message'] = '
You need to be logged in to view the administration area
';
            $this->load->view('user/login', $data);
        }
    }

    public function dashboard() {
        if($this->session->userdata('logged_in')) {
            $data['title'] = 'Welcome';
            $this->load->view('user/dashboard', $data);
        } else {
            $data['message'] = '
You need to be logged in to view the administration area
';
            redirect('/user/login/', 'location');
        }

    }

    public function login() {

        if($this->session->userdata('logged_in')) {
            redirect('/user/dashboard/', 'location');
        }

        $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Wachtwoord', 'trim|required|min_length[4]|max_length[32]');

        if($this->form_validation->run() == FALSE) {
            $this->index();
        } else {
            if($this->user_model->login($this->input->post('email'), $this->input->post('password'))) {
                redirect('/user/dashboard/', 'location');
            } else {
                $this->index();
            }
        }
    }

    public function logout() {
        $this->simpleloginsecure->logout();
        redirect('/user/login/', 'location');
    }

}


texts: Caesar Cipher [The Odin Project-Javascript Exercise]

texts:
Very new to coding, so please don't bully me.

Implement the legendary caesar cipher:

In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.

Question: Write a function that takes a string to be encoded and a shift factor and then returns the encoded string:

caesar('A', 1) // simply shifts the letter by 1: returns 'B' the cipher should retain capitalization:

caesar('Hey', 5) // returns 'Mjd; should not shift punctuation:

caesar('Hello, World!', 5) //returns 'Mjqqt, Btwqi!' the shift should wrap around the alphabet:

caesar('Z', 1) // returns 'A' negative numbers should work as well:

caesar('Mjqqt, Btwqi!', -5) // returns 'Hello, World!'

My Solution:

function caesar(string, num) {
let arr = [];
for(let i=0;i<string.length;i++)
  {if(!(/[a-zA-Z]/.test(string[i])))
    {arr[i]=string[i]; continue;}
  let n = string.charCodeAt(i) + num;
  if (string[i] == string[i].toLowerCase())
    {if(n>122)
      {while(n>122)
        {n-=26;}}
     else
      {while(n<97)
        {n+=26;}
      }
    }
  else
    {if(n>90)
      {while(n>90)
        {n-=26;}
      }
     else
      {while(n<65)
        {n+=26;}
      }
    }
  arr[i]=String.fromCharCode(n);
  }
console.log(arr.join(''));
}
caesar("Hello, World!", 2);
caesar("Hello, World!", 75);

The code is working perfectly as per requirement, but please help me with a better solution if possible.

And if you do, please use comments to extensively explain the working process, as I'm quite the noob.


texts: Download a file given an url to a restricted area and a cookie container

texts:
I have a queue of jobs in an ASP.NET CORE Application. Each of the files are in a restricted area and I have to Login first, thats why I use a Cookie Container for my download request.

The Job is logging into a platform and then starts to download the file, given an URL and a Cookie Container from the Login.

The download method is looking like this and has a Func which reports the progress in 5 % steps:

public async Task DownloadFile(string url, string destination, Func<int, Task> reportStatus)
{
        await reportStatus(0);

        var request = WebRequest.CreateHttp(url);
        request.CookieContainer = m_cookieContainer;
        var response = (HttpWebResponse)await request.GetResponseAsync();
        var requestStream = response.GetResponseStream();

        using (var reader = new BinaryReader(requestStream))
        {
            using (var fileStream = File.OpenWrite(destination))
            {
                const int bufferSize = 2048;
                byte[] bytes;
                short oldPercentage = 4;
                long bytesRead = 0;
                do
                {
                    bytes = reader.ReadBytes(bufferSize);
                    await fileStream.WriteAsync(bytes, 0, bytes.Length);

                    bytesRead += bytes.Length;

                    var percentage = (short)(bytesRead * 100 / response.ContentLength);
                    if (oldPercentage < percentage)
                    {
                        await reportStatus(percentage);
                        oldPercentage = (short)(oldPercentage + 5);
                    }
                } while (bytes.Length != 0);
            }
        }

        await reportStatus(100);
}

Small problems I am currently facing:

Download speed feels quite slow in comparison to my internet connection.
I was wondering if there are better ways downloading a file from a restricted area using .NET Core functionality.


texts: Assign object keys to another object's keys dynamically

texts:
I have an array called viewObject.terms. This array can contain up to 3 items, I need to iterate through this array and save the values into a data object.

ie:

data.term_id_1 = viewObject.terms[0].term_id
data.ticker_1  = viewObject.terms[0].its_ticker

This is what I first tried, but I get the error: Cannot set property '0' of undefined

for (var i=0; i<viewObject.terms.length; i++) {
    data.term_id_[i+1] = viewObject.terms[i].term_id;
    data.ticker_[i+1]  = viewObject.terms[i].its_ticker;
}

So for the moment, I'm just using a switch case to handle this currently (albeit in a super ugly way):

if (viewObject.terms.length > 0) {
    switch(viewObject.terms.length) {
        case 1:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            break;
        case 2:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            data.term_id_2 = viewObject.terms[1].term_id;
            data.ticker_2  = viewObject.terms[1].its_ticker;
            break;
        case 3:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            data.term_id_2 = viewObject.terms[1].term_id;
            data.ticker_2  = viewObject.terms[1].its_ticker;
            data.term_id_3 = viewObject.terms[2].term_id;
            data.ticker_3  = viewObject.terms[2].its_ticker;
            break;
    }
}


texts:
I am very new to PHP. I've only been using it for a few months. I'm currently attempting to build a forum and wanted feedback on some of the code I have so far.
These are two files I feel like could have been done better. There are no errors as far as I can tell. I would just like some feedback on security issues, coding practices, etc.

File 1:

<?php

function dispcategories(){
  include ('../db.php');
  $select = mysqli_query($mysqli, "SELECT * FROM categories");

while($row = mysqli_fetch_assoc($select)){
  echo "<table class = 'category-table'";
  echo "
".$row['category_title']."
	";
  dispsubcategories($row['cat_id']);
  echo "
";
  }
}

function dispsubcategories($parent_id){
  include ('../db.php');
  $select = mysqli_query($mysqli, "SELECT cat_id, subcat_id, subcategory_title, subcategory_descr FROM categories, subcategories
                                 WHERE ($parent_id = categories.cat_id) AND ($parent_id = subcategories.parent_id)");
echo "
Categories	Topics
";

while($row = mysqli_fetch_assoc($select)){
  echo "

                ".$row['subcategory_title']."
";
  echo $row['subcategory_descr']."	";
  echo "".getnumtopics($parent_id, $row['subcat_id'])."
";
  }
}

//Displays categories
 function getnumtopics($cat_id, $subcat_id){
  include ('../db.php');
  $select = mysqli_query($mysqli, "SELECT category_id, subcategory_id FROM topics WHERE ".$cat_id." = category_id
                AND ".$subcat_id." = subcategory_id");
$get = mysqli_num_rows($select);

return $get;
}

//Displays Topics Within categories
  function disptopics($cid, $scid){
   include ('../db.php');
   $select = mysqli_query($mysqli, "SELECT topic_id, author, title, date_posted, views, replies FROM categories, subcategories, topics
                                 WHERE ($cid = topics.category_id) AND ($scid = topics.subcategory_id) AND ($cid = categories.cat_id)
                                 AND ($scid = subcategories.subcat_id) ORDER BY topic_id DESC");

if(mysqli_num_rows($select) != 0) {
  echo "
";
  echo "
Title	Posted By	Date Posted	Views	Replies
";

  while($row = mysqli_fetch_assoc($select)){
    echo "

          ".$row['title']."	".$row['author']."	".$row['date-posted'].".	".$row['views']."
          ".$row['replies']."
";
  }
  echo "
";
} else {
  echo "
This category has no topics yet!  Add a new one!
";
  }

 }

?>

File 2:

 <?php
   /*
   $select = mysqli_query($mysqli, "SELECT * FROM categories");
    while($row = mysqli_fetch_assoc($select)){
      echo  "
", $row['category_title']."
" ;
    }*/

    //disptopics($_GET['cid'], $_GET['scid']);
    if (isset($_GET['cid'], $GET['scid'])){

      disptopics();
    }

     ?>


texts: JUnit test case to check that an exception of type javax.mail.MessagingException is not thrown

texts:
I have a method which will send a text mail using JavaMail API and I am trying to write a test case for this method which will check if an Exception of type javax.mail.MessagingException is not thrown.

If a MessagingException type exception is thrown, the test will fail, else it will pass.

public void sendMail() throws MessagingException{
        final String smtpServer = "smtp.gmail.com";
        final String userAccount = ""; // Sender Account.
        final String password = ""; // Password/Application Specific Password.
        final String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
        final String smtpPort = "587";
        final String PORT = "465";

        final Properties props = new Properties();
        props.put("mail.smpt.host", smtpServer);
        props.put("mail.smtp.user", userAccount);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.debug", "false");
        props.put("mail.smtp.socketFactory.port", PORT);
        props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session connection = Session.getInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(connection);
        connection.setDebug(true);

        final Address toAddress = new InternetAddress(""); // toAddress
        final Address fromAddress = new InternetAddress(userAccount);
        mimeMessage.setContent("This is a test mail...", "text/html; charset=UTF-8");
        mimeMessage.setFrom(fromAddress);
        mimeMessage.setRecipient(javax.mail.Message.RecipientType.TO, toAddress);
        mimeMessage.setSubject("Test Mail...");
        Transport transport = connection.getTransport("smtp");
        transport.connect(smtpServer, userAccount, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    }

    public void testSendMailToCheckThatMessagingExceptionIsNotThrown() {
       try {
            genericTaskInterpreter.sendMail();
        } catch (MessagingException messagingException) {
            fail("A MessagingException is thrown..." + messagingException.getMessage());
        }
    }

Am I doing it correctly? How can I improve it?


texts:
Can the following condition be optimized/simplified ?

if (!this.properties.width ||
    this.properties.width <= 0 ||
    !this.properties.height ||
    this.properties.height <= 0)
  return;

So basically if properties does not have a width or height property or the width or height property is less than or equal to zero then return


texts: Filter out URLs with any of some given file extensions

texts:
I wrote some code to filter a list of links, URLs, with multiple conditions given by file extensions. I want to remove every URL that is not an HTML file. The code is:

avoid = [".pptx", ".ppt", ".xls", ".xlsx", ".xml", ".xlt", ".pdf",
         ".jpg", ".png", ".svg", ".doc", ".docx", ".pps"]

links = ["http://www.abc.com", "http://www.abc.com/file.pdf",
         "http://www.abc.com/file.png"]

def analyse_resource_extension(url):
    match = [ext in url for ext in avoid]
    return any(element is True for element in match)

links = list(filter(lambda x: analyse_resource_extension(x) is False, links))

so that links finishes with ["http://www.abc.com"] as only value. This solution seems kind of wordy for me. Is there any way to perform the same action without using the analyse_resource_extension function?


texts:
In some (lower-level) parts of my codebase I often have the need to allocate resizable array storage for certain objects, that usually are not default-constructible.

I created a simple class using std::aligned_storage and I was wondering if it's safe and if it can be improved.

The user of the class has to keep track of the current capacity.

template<typename T> class ResizableArray
{
    private:
        using TStorage = std::aligned_storage_t<sizeof(T), alignof(T)>;
        TStorage* data{nullptr};

    public:
        ~ResizableArray() { delete[] data; }

        void resize(std::size_t mSizeOld, std::size_t mSizeNew)
        {
            auto newData(new TStorage[mSizeNew]);
            for(auto i(0u); i < mSizeOld; ++i) newData[i] = std::move(data[i]);

            delete[] data;
            data = newData;
        }

    auto& operator[](std::size_t mIdx) noexcept
    { return reinterpret_cast<T&>(data[mIdx]); }

    const auto& operator[](std::size_t mIdx) const noexcept
    { return reinterpret_cast<const T&>(data[mIdx]); }
};

Example usage:

int main()
{
    ResizableArray<Thing> a;

    // Resize array capacity from 0 to 10
    a.resize(0, 10);

    for(auto i(0u); i < 10; ++i)
        new (&a[i]) Thing{/* something */};

    return 0;
}


texts:
In this answer I suggested using a fluent interface "builder" to replace all the hard-coded, repetitive and quite error-prone inline XML string concatenations.

This code might need a bit of tweaking to work perfectly with the OP's code in the question this code is following-up on, but it seems to work as expected. Thoughts?

public enum XmlQueryOperator
{
    Equals,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual
}

public class XmlQueryBuilder<TEntity>
    where TEntity : class
{
    private readonly XDocument _xDoc = new XDocument();
    private readonly XElement _queryNode = new XElement("query");

    public XmlQueryBuilder()
    {
        var rootNode = new XElement("queryxml");
        rootNode.SetAttributeValue("version", "1.0");

        var entityNode = new XElement("entity");
        entityNode.Value = typeof (TEntity).Name;

        rootNode.Add(entityNode);
        _xDoc.Add(rootNode);
    }

    public XmlQueryBuilder<TEntity> Where<TProperty>(Expression<Func<TEntity, TProperty>> property, XmlQueryOperator operation, string value)
    {
        var xCondition = new XElement("condition");
        var xField = new XElement("field");
        xField.Value = GetPropertyName(property);

        var xExpression = new XElement("expression");
        xExpression.SetAttributeValue("op", operation.ToString());
        xExpression.Value = value;

        xField.Add(xExpression);
        xCondition.Add(xField);

        _queryNode.Add(xCondition);
        return this;
    }

    public override string ToString()
    {
        var parent = _xDoc.Element("queryxml");
        if (parent == null) throw new InvalidOperationException("root node was not created.");

        parent.Add(_queryNode);
        return _xDoc.ToString();
    }

    private string GetPropertyName<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
    {
        // credits http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression/672212#672212 (modified to return property name)
        var type = typeof(TSource);

        var member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", propertyLambda));

        var propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", propertyLambda));

        if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format("Expresion '{0}' refers to a property that is not from type {1}.", propertyLambda, type));

        return propInfo.Name;
    }
}

Usage - given a TestEntity:

public class TestEntity
{
    public string Test1 { get; set; }
    public int Test2 { get; set; }
    public DateTime Test3 { get; set; }
}

This program produces the expected output:

class Program
{
    static void Main(string[] args)
    {
        var builder = new XmlQueryBuilder<TestEntity>()
            .Where(t => t.Test1, XmlQueryOperator.Equals, "abc")
            .Where(t => t.Test2, XmlQueryOperator.GreaterThan, "def")
            .Where(t => t.Test3, XmlQueryOperator.LessThanOrEqual, DateTime.Now.ToString());

        Console.WriteLine(builder.ToString());
        Console.ReadLine();
    }
}

Output:

<queryxml version="1.0">
  <entity>TestEntity</entity>
  <query>
    <condition>
      <field>Test1<expression op="Equals">abc</expression></field>
    </condition>
    <condition>
      <field>Test2<expression op="GreaterThan">def</expression></field>
    </condition>
    <condition>
      <field>Test3<expression op="LessThanOrEqual">2014-05-05 14:14:57</expression></field>
    </condition>
  </query>
</queryxml>


texts:
I am fetching the friend list for a chat application using a Vuex store. I need to dispatch the getter via an interval. Is there a best practices way to do this?

<template>

Who's Online

            <UserListItem v-for="user in friendList" :user="user" :key="user.user_id" />

</template>


texts: Select the element out of the array if its index is a Fibonacci number

texts:
I've some questions for an exam and wondered if somebody could take a look at my Fibonacci sequence that is supposed to answer this question:

  "select the element out of the array if its index is a Fibonacci number"

def fibonacci_sequence(max_num)
  sequence = [1, 2]
  loop do
    fibonacci = sequence[-2] + sequence[-1]
    break if fibonacci >= max_num
    sequence << fibonacci
  end
  sequence
end

# array size
max_num = 100
numbers = []
1.upto(max_num) { |num| numbers << num }
fibonacci = fibonacci_sequence(max_num)

# select fibonacci numbers and assign array to variable
fibonacci_numbers = numbers.select { |num| fibonacci.include?(num) }

My thoughts were that I had to work out what the Fibonacci sequence was before I could select numbers out of the array that were Fibonacci. The thing is I already answer the question by assigning these numbers to the Fibonacci variable. I've then used a select method on the original numbers array even though I already know what the output is going to be.

Have I gone about this the right way? I'm thinking no!


texts:
I have this if else block code

 if($_POST["item"]=="All"){
        $notificatioSetting->AllNotification=$_POST["status"];
    }
    else if($_POST["item"]=="Accept"){
        $notificatioSetting->AcceptTrackRequest=$_POST["status"];
    }
    else if($_POST["item"]=="Deny"){
        $notificatioSetting->DenyTrackRequest=$_POST["status"];
    }

this condition continues for almost 12 another else if condition. Beside this and switch, is there a better way?


texts: Controller for an Administrator User, can this be improved? (codeigniter)

texts:
I want to write better code.
This is a simple controller class for an administrator login.

Are there conventions or tips in PHP to rewrite this code and improve it?

<?php

class Administrators extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        if(!$this->session->userdata('logged_in')) {
            redirect('/office/administrators/login');
        } else {
            redirect('/office/dashboard/');
        }
    }

    public function login() {

        if($this->session->userdata('logged_in')) {
            redirect('/office/dashboard/');
        }

        if($_SERVER['REQUEST_METHOD'] == 'POST') {

             $a = new Administrator();

            if($a->login($this->input->post('email'),$this->input->post('password'))) {
                    redirect('/office/dashboard/');
            } else {
                $this->messages->add('Unable to authenticate you', 'error');

            }
        }

        $data['error_messages'] = $this->messages->get('error');
        $this->load->view('/office/administrators/login', $data);
    }

    public function logout() {
        $this->simpleloginsecure->logout();
        redirect('office/administrators/login');
    }

}

?>


texts:
I would like to test the following garbage collector code on a database of sessions.
It should be following the conditions below:

if 'remember me' is enabled by the user, then it should delete all rows which are not active within 2 weeks.
if 'remember me' is disabled by the user, then it should delete all rows which are not active within 30 minutes.

I have times inserted in the LAST_ACTIVITY column, with the UNIX_TIMESTAMP() format.

public function gc( $maxlifetime )
{
    $this->conn->SQL( 'DELETE FROM session WHERE (LAST_ACTIVITY < ? AND REMEMBERUSER = ?) OR (LAST_ACTIVITY < ? AND REMEMBERUSER = ?)' ,
        [ strtotime('-30 minutes'), 'N' , strtotime('-2 weeks'), 'Y']);
    return true;
}

Are the AND or OR operators working properly? I would only like to test the SQL query, and not the gc method.


texts:
Using python 3.6. I have written this code (below) to apply hysteresis to a signal (a numpy array).

My aim was to create a function that didn't require any loop to remember the previous state of the signal. For that purpose I re-used code from this post.

Here is an example output:

And here is the code that generated it.

import matplotlib.pyplot as plt
import numpy as np

def ups_downs(y):
    """Detect when the direction of y crosses 0
    """

    try:
        summed = np.cumsum(y)
        d = np.sign(np.diff(summed))
        ud = np.flatnonzero(d)
        uds = d[ud]
        change = ud[np.r_[True, uds[1:] != uds[:-1]]]

        out = np.zeros(len(summed), dtype=int)

        out[1:][change] = d[change]
    except IndexError:
        out = y
    return out

def hysteresis(signal, top_band, bottom_band, normal_below=False):
    """Return a signal that has had hysteresis applied. A value of 1
    in the returned result indicated the signal has crossed both bands
    and has returned to its default position (either above or below
    both top and bottom bands).

    Args:
        signal: A 1D numpy array to apply hysteresis to
        top_band: A 1D numpy array. When the signal evaluates above this band
            the signal is considered 'above'
        bottom_band: A 1D numpy array. When the signal evaluates below this band
          the signal is considered 'below
        normal_below: When `True` indicates that the signal is normally 'below'
          the bottom band. Default = `False` indicating the signal is normally 'above'
          the top band.
    """
    result = np.zeros(len(signal), int)
    i, ii = {False: (1, -1), True: (-1, 1)}[normal_below]
    result[signal > top_band] = i
    result[signal < bottom_band] = ii
    result = ups_downs(result)
    result[result == -1] = 0
    zero_out = {False: np.argmax(signal < bottom_band),
                True: np.argmax(signal > top_band)}[normal_below]
    result[:zero_out] = 0
    return result

top_band = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
                     17, 18, 19])
bottom_band = np.array([-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                        15, 16, 17])
signal = np.array([1, 2, 3, 4, 1, 2, 7, 8, 9, 6, 7, 12, 11, 14, 11, 12, 15,
                   14, 20, 16])

result = hysteresis(signal, top_band, bottom_band, normal_below=True)

x = np.arange(signal.shape[0])
plt.plot(x, top_band, label='top_band')
plt.plot(x, bottom_band, label='bottom_band')
plt.plot(x, signal, label='signal')
plt.plot(x, result, label='result')
plt.legend()
plt.show()

As stated earlier the ups_downs function is re-purposed from this post. So i'm really interested if there is a simpler way to achieve the same result with out having to use it. Although the concept is simple to understand, I found it challenging to create the hysteresis function, particularly how to initialize the output. I decided to zero it out until the signal has made a whole round trip.

The function takes 4 parameters. The signal, top_band, bottom_band and most confusingly normal_below. normal_below indicates that the signal is normally 'below' or 'above' both bands. And that upon returning to this state the returned result should indicate this.

How could it be improved?


texts: Map coloring with MRV and Degree heuristics in Python

texts:
I am relatively new to Python. I wrote this solution to the well known map coloring problem and also implemented the MRV and Degree heuristics. Here, I am considering the map of Australia - ['WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T'] and 3 given colors - ['R','G', 'B']

# choosing first node with degree heruistics
# applying MRV with backtracking

from enum import Enum
import pdb

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class Graph:
    def __init__(self, totalNodes, adjacencyList, color):
        self.totalNodes = totalNodes
        self.adjacencyList = adjacencyList
        self.color = color
        self.nodeSequence = [""]*totalNodes

    def isSafe(self, node, c):
        for i in range(len(self.adjacencyList[node])):
            if(self.color[self.adjacencyList[node][i]] == c):
                return False
        return True

    def graphColorUtil(self, node, colorLimit):
        if node == '':
            # check and color any uncolored node
            for key, value in self.color.items():
                if value == 0:
                    self.graphColorUtil(key, colorLimit)
            return True

        # pdb.set_trace()
        for c in range(1, colorLimit+1):
            if(self.isSafe(node, c) == True):
                self.color[node] = c
                nextNode = self.getNodeWithMRV(node, colorLimit)
                if(self.graphColorUtil(nextNode, colorLimit) == True):
                    return True
                else:
                    self.color[node] = 0

        return False

    def graphColoring(self, colorLimit):
        # pdb.set_trace()
        startNode = self.pickNode('')
        if(self.graphColorUtil(startNode, colorLimit) == True):
            return True
        else:
            print("Solution does not exists")
            return False

    # pick node using MRV
    def pickNode(self, initialNode):
        maxCount = 0
        selectedNode = ''
        # the very first node
        if (initialNode == ''):
            for node, neighbourList in self.adjacencyList.items():
                if (len(neighbourList) > maxCount and self.color[node] == 0):
                    maxCount = len(neighbourList)
                    selectedNode = node
        # the other nodes
        else:
            for i in range(len(self.adjacencyList[initialNode])):
                childNode = self.adjacencyList[initialNode][i]
                if (self.color[childNode] == 0 and len(self.adjacencyList[childNode]) > maxCount):
                    maxCount = len(self.adjacencyList[childNode])
                    selectedNode = childNode

        return selectedNode

    def getNodeWithMRV(self, parentNode, colorLimit):
        selectedNode = ''

        for i in range(len(self.adjacencyList[parentNode])):
            childNode = self.adjacencyList[parentNode][i]
            countColor = 0
            for c in range(1, colorLimit+1):
                if(self.isSafe(childNode, c) == True):
                    countColor += 1
            if (countColor < minCount):
                selectedNode = childNode

        return selectedNode

# driver code
def main():
    adjacencyList = {
        'WA': ['NT', 'SA'],
        'NT': ['WA', 'SA', 'Q'],
        'SA': ['WA', 'NT', 'Q', 'NSW', 'V'],
        'Q': ['NT', 'SA', 'NSW'],
        'NSW': ['SA', 'Q', 'V'],
        'V': ['SA', 'T', 'NSW'],
        'T': ['V']
    };

    color = {
        'WA': 0,
        'NT': 0,
        'SA': 0,
        'Q': 0,
        'NSW': 0,
        'V': 0,
        'T': 0
    };

    g = Graph(7, adjacencyList, color)
    colorLimit = 3
    g.graphColoring(colorLimit)

    for node, color in g.color.items():
        print(node, Color(color).name)
main()

What could be the possible ways to refactor this code? I am also interested for feedback on Python code style in general.


texts:
Let's consider a method like this:

public bool IsWordABeforeWordB(string Text, string WordA, string WordB)
{
   ...
}

By Word I mean a string composed of more than one character.

Test cases:

[TestMethod]
public void IsWordABeforeWordB_ShouldBeTrue()
{
    string Text = "CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([IDTest] ASC)";
    bool result = AtomicCheckMethods.IsWordABeforeWordB(Text, "CLUSTERED", "ASC");
    result.Should().BeTrue();
}

[TestMethod]
public void IsWordABeforeWordB_ShouldBeFalse()
{
    string Text = "CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([IDTest] ASC)";
    bool result = AtomicCheckMethods.IsWordABeforeWordB(Text, "PRIMARY KEY", "CONSTRAINT");
    result.Should().BeFalse();
}

[TestMethod]
public void IsWordABeforeWordB_IgnoreCase_ShouldBeTrue()
{
    string Text = "CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([IDTest] ASC)";
    bool result = AtomicCheckMethods.IsWordABeforeWordB(Text, "clustered", "asc");
    result.Should().BeTrue();
}

[TestMethod]
public void IsWordABeforeWordB_IgnoreCase_ShouldBeFalse()
{
    string Text = "CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([IDTest] ASC)";
    bool result = AtomicCheckMethods.IsWordABeforeWordB(Text, "primary key", "constraint");
    result.Should().BeFalse();
}

What I tried:

public static bool IsWordABeforeWordB(string Text, string WordA, string WordB)
{
    string stringBeforeWordB = Text.Substring(0, Text.IndexOf(WordB, StringComparison.InvariantCultureIgnoreCase));
    return stringBeforeWordB.IndexOf(WordA, StringComparison.InvariantCultureIgnoreCase) >= 0;
}

Can I do it better?


texts:
I created a function that prints where the students are - lesson, long break or short break (and which short break)
Function parameters are:
    shortBreak - duration of short break
    longBreak - duration of long break
    lesson - after which lesson is long break
    time - the time where students are located

My parameters to test function are
   currently(shortBreak: 5, longBreak: 15, lesson: 3, time: "10:37)

So it should be
  8:00 - 8:45 - lesson
  8:45 - 8:50 - short break
  8:50 - 9:35 - lesson
  9:35 - 9:40 - short break
  9:40 - 10:25 - lesson
  10:25 - 10:40 - long break (after 3.lesson is long break)

which means that students are currenty on long break.
How can I write my code better (can I use some more OOP principles or closure somehere or something else)?
import UIKit

enum current {

case lesson
case shortBreak
case longBreak

}

func currently(shortBreak: Int, longBreak: Int, lesson: Int, time:String){

    var shortBreakCounter: Int = 0
    var currentLesson: Int = 1
    var currentHours: Int = 8
    var currentMinute: Int = 0
    var currentCase: current = .lesson

    let minute: Int = Int(time.suffix(2)) ?? 0
    let hour: Int = Int(time.prefix(2)) ?? 0

    if(checkValid(hour: hour, minute: minute)){

        print("Invalid time")
    }

    else {

        while isInRange(hour: currentHours, minute: currentMinute) {

            currentCase = .lesson

            currentMinute += 45

            if currentMinute >= 60 {
                currentHours += 1
                currentMinute = 0
            }

            if currentLesson == lesson {

                currentCase = .longBreak

                currentMinute += longBreak

                if currentMinute >= 60 {
                    currentHours += 1
                    currentMinute = 0
                }

            } else{

                currentCase = .shortBreak

                currentMinute += shortBreak

                shortBreakCounter += 1

                if currentMinute >= 60 {
                    currentHours += 1
                    currentMinute = 0
                }

            }

            currentLesson += 1

        }

        switch currentCase {

            case .shortBreak:
                print("Students are on \(shortBreakCounter) short break")
            case .longBreak:
                print("Students are on long break")
            default:
                print("Students are on lesson")
            }

    }

}

func checkValid(hour: Int, minute:Int) -> Bool {

    if hour >= 16 || hour < 8 {

        return true

    } else if minute > 59 || minute < 0 {

        return true
    }

    return false

}

func isInRange(hour: Int, minute: Int) -> Bool{

    if 8..<16 ~= hour &&  0..<60 ~= minute  {

        return false

    }

        return true

    }

    currently(shortBreak: 5, longBreak: 15, lesson: 3, time: "10:37")


texts: Find the minimum gap (difference) between adjacent elements in a linked list

texts:
Write a method called minGap that returns the    minimum gap between
  adjacent values in a list of integers.  The gap between    two
  adjacent values in a list is defined as the second value minus the
  first    value.  For example, suppose a variable called list stores
  these values:

  [1, 3, 6, 7, 12]

  The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1
  (7 - 6), and the fourth gap is 5 (12 - 7).  Thus, the call:

  list.minGap()

  should return 1 because that is the smallest gap.  Notice that the minimum
  gap could be a negative number.  For example, if list stores the following:

  [3, 5, 11, 4, 8]

  The gaps are 2 (5 - 3), 6 (11 - 5), -7 (4 - 11), and 4 (8 - 4).  Of these
  values, -7 is the smallest, so it would be returned.

  Your method should return 0 if the list has fewer than 2 elements.  You are
  writing a method for the LinkedIntList class:

    public class ListNode {
        public int data;       // data stored in this node
        public ListNode next;  // link to next node in the list

        <constructors>
    }

    public class LinkedIntList {
        private ListNode front;

        <methods>
    }

  Your method should not modify the list contents and is required to
  run in    O(n) time where n is the length of the list.  You may not
  call any other    methods of the LinkedIntList class and you may not
  construct any structured    objects to solve this problem.

I'm unsure if I'm doing the right thing for checking minimums by setting the int minGap to Integer.MAX_VALUE (let me know if this is bad). I want to get better at these problems, so any tips that can make my code more readable or easier to write would be awesome! I didn't know a lot about using multiple references to linked lists before I solved this problem, so any advice to solving these problems in the future would be much appreciated.

public int minGap() {
    if (front == null || front.next == null) {
        return 0;
    }
    int minGap = Integer.MAX_VALUE;
    ListNode prev = front;
    ListNode p = front.next;
    while (p != null) {
        int checkGap = p.data - prev.data;
        if (checkGap < minGap) {
            minGap = checkGap;
        }
        prev = p;
        p = p.next;
    }
    return minGap;
}


texts:
I am discussing with one of my peers about proper encapsulation. We had to write this code. One of the specifications is: "The Student object has to have a Grade object called finalGrade. Code hint: Grade finalGrade;"

This is my code

public class Student
{
  private String firstName;
  private String lastName;
  private String id;

  public Grade finalGrade = new Grade(); // THIS IS THE QUESTIONABLE CODE
...
...
}

public class TestStudent
{

  public static void main(String[] args)
  {
   ...
   ...
   ...
    student.finalGrade.setGradeValue(85);
    student.finalGrade.setLetterGrade('B');
    student.setFinalGrade('B');

    System.out.println(student.finalGrade.getGradeValue());
    System.out.println(student.finalGrade.getLetterGrade());
  }
}

This is their code

public class Student {
...
Grade finalGrade;  // THIS IS THE QUESTIONABLE CODE
public Grade getFinalGrade() {
return finalGrade;
}

public void setFinalGrade(Grade finalGrade) {
this.finalGrade = finalGrade;
}

....
public String toString() {
String display = String.format("Student: id= %d name= %s letterGrade = %s", ID, getName(), finalGrade );
return display;
}
}

public class TestStudent {
public static void main(String[] argv) {
...
...
Grade g = new Grade();
g.setGradeValue(85);
g.setLetterGrade('B');
s.setFinalGrade(g);
System.out.println(s.toString());
}
}

Ultimately, which code is better given the specification?  My argument is that finalGrade is a class and should be accessed with the dot operator. My peer states that it is an attribute and should be private. I see it as a class accessing a class such as SuperClass.class.method();


texts:
I've realized JS callback hell and I started looking into Promises libraries.
After reading some articles I decided to start with BluebirdJS. I didn't realise how to properly use them yet, because documentation written with API examples, not real usage.

I have two files (NodeJS environment):

#monitor.js
Promise = require("bluebird")
class Monitor
  constructor: (@api) ->

  getServerInfo: ->
    return new Promise((resolve, reject) =>
      @api.query("messages.getLongPollServer", { use_ssl: 1}).then(
        (result) =>
          @key = result.response.key
          @server = result.response.server
          @ts = result.response.ts

          resolve(@)

        reject
      )
    )

  printDetails: ->
    console.log(@key, @server, @ts)

module.exports = Monitor

#app.js
Api = require("./api")
Monitor = require("./monitor")

api = new Api("6de61129da290c3edf9c699ad25638156266e7b6bdbcc00407efb630e5c62f2d4c71974c7bdba52a03dbd")

monitor = new Monitor(api)

monitor.getServerInfo().then((monitor) -> monitor.printDetails())

What I wanted to achieve is something like this:

monitor.getServerInfo().then().printDetails()

because getServerInfo runs asynchronously.

Am I using promises correctly?


texts: Archiving data while running update statement

texts:
I'm using sql server and I'm  trying to update certain columns in a table but before it updates the data, I want to insert the data into another table.

This is my code

declare @table1 table (Id int, Name varchar(100))
declare @temp table (Id int, Name varchar(100), CreatedOn datetime default getdate())

insert into @table1 values (1, 'Albert')
insert into @table1 values (2, 'Alex')
insert into @table1 values (3, 'Alas')
insert into @table1 values (4, 'Bob')

update @table1
set Name = 'B' + Name
output Deleted.Id, Deleted.Name, getdate() into @temp
where Name like 'A%'

select * from @table1
select * from @temp

Above code seems to be working correctly. Please let me know if I have to change anything.


texts: Draw polygons with increasing/decreasing vertices

texts:
I wrote a small program in Javascript that, when given a certain number of sides, will draw a polygon with that number of sides (i.e. 3 for a triangle, 5 for a pentagon, 8 for octagon, etc.).
The program is set on an interval that will, every second, increment the number of sides, redraw the canvas, and then draw the new polygon with the new number of sides.
The code works as intended, though I'm not entirely sure if it's working most efficiently. Was wondering if there were better ways to manage variables, draw to the screen, etc.
Here is the jsFiddle
---HTML---

    <title>Circles</title>

Sides:

    <input type='button' class='dir' id='backward' value='BACKWARD' />
    <input type='button' class='dir' id='forward' value='FOWARD' />
    <input type='button' id='start' value='Start' />
    <input type='button' id='stop' value='Stop' />
    <input type='button' id='reset' value='Reset' />

    <canvas id='canvas' width='500' height='500'></canvas>

---Javascript---
class Vector {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
}

class Circle {
  constructor(x, y, radius) {
    this.center = new Vector(x, y);
    this.radius = radius;
  }
}

const input = document.getElementById("sides");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const center = {
  x: canvas.width / 2,
  y: canvas.height / 2
};
const rotateAround = 3 * Math.PI / 2;

drawCanvas();

let reverse = false;
let sides = 0;
let radius = center.y * 0.8;
let shapes = [];

function reset() {
  context.rotate(-(3 * Math.PI / 2));
  context.translate(-center.y, -center.y);
  drawCanvas();
  context.translate(center.y, center.y);
  context.rotate(3 * Math.PI / 2);
}

function draw() {
  reset();
  if (reverse) {
    if (sides != 0) {
      sides -= 1;
    }
  } else {
    sides += 1;
  }
  document.getElementById('noSides').innerText = sides;
  if (sides > 0) {
    shapes = [];
    for (let i = 0; i < sides; i++) {
      shapes.push(new Circle(0, 0, 20));
    }

    for (let i = 0; i < shapes.length; i++) {
      let x1 = radius * Math.cos(Math.PI * (i / (shapes.length / 2)));
      let y1 = radius * Math.sin(Math.PI * (i / (shapes.length / 2)));

      shapes[i].center.x = x1;
      shapes[i].center.y = y1;
    }

    for (let i = 0; i < shapes.length; i++) {
      for (let j = i + 1; j < shapes.length; j++) {
        context.beginPath();
        context.lineWidth = 0.5;
        context.moveTo(shapes[i].center.x, shapes[i].center.y);
        context.lineTo(shapes[j].center.x, shapes[j].center.y);
        context.stroke();
        context.closePath();
      }
    }
  }
}

function drawCanvas() {
  context.fillStyle = "lightgrey";
  context.fillRect(0, 0, canvas.width, canvas.height);
}

let interval;
let started = false;

function update() {
  context.translate(center.y, center.y);
  context.rotate(rotateAround);

  drawCanvas();
}

update();

document.getElementById('start').onclick = function() {
  if (started === false) {
    started = true;
    interval = setInterval(draw, 1000);
  }
}

document.getElementById('stop').onclick = function() {
  clearInterval(interval);
  started = false;
}

document.getElementById('forward').onclick = function() {
  reverse = false;
}

document.getElementById('backward').onclick = function() {
  reverse = true;
}

document.getElementById('reset').onclick = function() {
    clearInterval(interval);
    reset();
    sides = 0;
}