texts:
I'm getting the right results for the code for the sample outputs, but the OJ is giving a TLE (3 seconds max).

The questions is here.

int main()
{
    double h,u,d,f;
    while(scanf("%lf%lf%lf%lf",&h,&u,&d,&f)!=EOF)
    {
        //cin>>h;
       // if(h==0)
          //  break;
        //cin>>u>>d>>f;
        double fu=.01*f*u;
        double used_fu=0;
        int day=1;
        double crossed=0;
        int success=0;
        while(1)
        {
            crossed+=(u-used_fu);
            if(crossed>h)
            {
                success++;break;
            }
            crossed-=d;
            if(crossed<0)
                break;
            used_fu+=fu;
            day++;
        }
        if(success==0)
            cout<<"failure";
        else
            cout<<"success";
        cout<<" on day "<<day<<"\n";
    }
    return 0;
}


texts:
Can I get some help on shortening the amount of code I have in this program?

import requests
import gzip
import sys
import urllib
from tabulate import tabulate
from bs4 import BeautifulSoup
from io import BytesIO

# firstly it will display a list of movies, the user will then type in the torrent they want to download

# download file
def get_file(href, file_name):
    try:
        req = requests.get('https://examplewebsite.com' + href)
    except Exception as e:
        print (e)

    response = req.text
    soup = BeautifulSoup(response)
    download = soup.find('a', {'class': 'siteButton giantButton    verifTorrentButton'})

    file_name = file_name + '.torrent'

    # this encodes the response information in a file

    response = urllib.urlopen(download.get('href'))
    buffer = BytesIO(response.read())

    gz = gzip.GzipFile(fileobj=buffer)

    with open(file_name,'wb') as f:
        f.truncate()
        f.write(gz.read())

def select_torrent():
    torrent = raw_input('>>')
    if torrent =='q' or torrent =='Q':
        sys.exit(0)
    else:
        return torrent
def test(text):
    if text=='q' or text=='Q':
        sys.exit(0)

# generates a list of movies
def find_movies(pages):
    total_movie_list = {}
    total_amount_of_movies = []
    total_movie_number = 0

    for i in xrange(pages):
        try:
            req = requests.get('https://example.website/movies/'+ str(i))
        except Exception as e:
            print (e)
        else:

            response = req.text
            soup = BeautifulSoup(response)

            #find elements in html file
            movies = soup.findAll('a', {'class': 'cellMainLink'})
            seed = soup.findAll('td',{'class':'green center'})
            leech = soup.findAll('td',{'class':'red lasttd center'})

            #put seed and leech data into list
            seed_list = [number.string for number in seed]
            leech_list = [number.string for number in leech]

            # generate dictionary of movies with their movie name and seed/leech data
            movie_temp = {i+total_movie_number: (movies[i].get('href'), movies[i].string,seed_list[i],leech_list[i]) for i in range(len(movies))}
            #put data into a table

            table = [[key,value[1],value[2],value[3]]for key,value in movie_temp.items()]
            #add onto current number of movies
            total_amount_of_movies += table
            #update movie list in order to download them
            total_movie_list.update(movie_temp)

            # add on to the last movie  number
            current_number_of_movies = len(movies)
            total_movie_number +=current_number_of_movies

    print(tabulate(total_amount_of_movies,headers=['number','name','seeder','leecher']))

    return total_movie_list

if __name__ == '__main__':
    #find movies, get input from user, then download movie torrent
    pages = raw_input('how many pages do you want(press q to quit)?:')
    test(pages)
    movie_list = find_movies(int(pages))
    print('\ndownload a file by typing the number(press q to quit)\n')
    torrent  = select_torrent()
    test(torrent)

    get_file(movie_list[int(torrent)][0], movie_list[int(torrent)][1])


texts: Decoding assembly instructions in a Game Boy disassembler

texts:
I am coding a game boy disassembler in C++. The program (simplified here) converts a vector of byte into an assembly instruction and print it.

To do so, it iterates through the vector of bytes (char) with an iterator. I noticed that with the it!=char_vect.end() condition, there is the risk that the iterator goes out from the vector. So I have to check that I do not get out of the vector at each iteration and if it occurs, I throw an error.

#include <iostream>
#include <vector>

int disassemble(std::vector<char>::iterator& it){

    int opcode = *it;
    int opbytes = 1; //number of bytes used by the operator

    switch(opcode){
        case 0x76 : std::cout<<"HALT "<<std::endl; opbytes = 1; break;
        case 0x10 : std::cout<<"STOP $"<<(int)*(it+1)<<std::endl; opbytes =2; break;
        //... About 250 different cases
        default : std::cout<<"Instruction not implemented yet"<<std::endl;
    }

    return opbytes;
}

int main(){

    std::vector<char> char_vect = {0x76, 0x10, 0x20}; // Fill vector of char
    std::vector<char>::iterator it = char_vect.begin();

    // First I only did that
    //while (it!=char_vect.end()){
    //  it+=disassemble(it);
    //}

    // But I have to check that I do not go out of the char_vect

    while (it!=char_vect.end()){
        try{
            it+=disassemble(it);
            //check that it do not overpass end
            if (size_t(it - char_vect.begin())>char_vect.size()){
                throw "Try to disassemble instruction outside of memory bounds";
            }
        }
        catch(const char * c){
            std::cerr << "Fatal error: " << c << std::endl;
            return 1;
        }
    }
    return 1;
}

This code works fine. Now I wonder, I have a possible exception case which is the iterator going further than vect_char.end(). Is a try / catch an appropriate way to handle this case knowing that:

The reason for the iterator to go out of bounds could be either:

A non valid input byte sequence, for example {0x76, 0x20, 0x10} since the instruction 0x10 expects an argument. This should not append.
A mistake in the disassemble function. For exemple with the valid input {0x76, 0x10, 0x20}, if I code by mistake that 0x10 uses 3 opbytes instead of 2, the iterator will go out of bounds. This should not append either.

If I iterated through the vect_char with an index, I would not have this issue and the code would be more compact

I never really used try/catch before and I do not know if it is intented for such situations, so I would like to know, how would you have handled this unexpected case?


texts: A method that generates a Comparator using lambda expression

texts:
Given below is an exercise from the book *Java SE 8 for the Really Impatient( by Cay S. Horstmann:

  Write a method that generates a Comparator that can be normal or
  reversed, case-sensitive or case-insensitive, space-sensitive or
  space-insensitive, or any combination thereof. Your method should
  return a lambda expression.

Is there a better (efficient, elegant) way to do it than below?

public static final int COMPARE_REVERSED = 0x01;
public static final int COMPARE_CASE_INSENSITIVE = 0x02;
public static final int COMPARE_SPACE_INSENSITIVE = 0x04;

public static Comparator<String> getComparator(int flags) {

    return (s1, s2) -> {
        if (has(flags, COMPARE_REVERSED)) {
            String temp = s1;
            s1 = s2;
            s2 = temp;
        }
        if (has(flags, COMPARE_SPACE_INSENSITIVE)) {
            s1 = s1.replaceAll("\\s", "");
            s2 = s2.replaceAll("\\s", "");
        }
        if (has(flags, COMPARE_CASE_INSENSITIVE)) {
            return s1.compareToIgnoreCase(s2);
        }
        return s1.compareTo(s2);
    };
}

public static boolean has(int flags, int FLAG) {
    return (flags & FLAG) != 0;
}


texts: Calculate min/max values for (un)signed integral number of up to 64 bits

texts:
This question is a follow up of Calculate min/max values for signed or unsigned integral number with any valid number of bits (up to 64)

I was answering the question Given two int values, return the one closer to 10, and I indicated that something like the following snippet of code could be a different approach for solving the problem.

In the original question, it turned out I had made a mistake, but since there were already some answers, I've decided to post a follow up question with the fixes.

Can this be done in a more efficient or more elegant way?

public class Bits
{
    public static void MinMaxI(ulong _bits, out long _min, out long _max)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        _min = ~(long)0 << (int)(_bits - 1);
        _max = -1 - _min;
    }

    public static long MinI(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        return ~(long)0 << (int)(_bits - 1);
    }

    public static long MaxI(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        return -1 - (~(long)0 << (int)(_bits - 1));
    }

    public static ulong MaxN(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 1 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("1 <= _bits <= 64"));
        }

        return _bits == 64 ? ~(ulong)0 : ~(~(ulong)0 << (int)_bits);
    }
}


texts:
Simple post and download web app in Bottle:

server.py

import sys
import bottle
from bottle import request, response
import pymongo
import gridfs
from bson.objectid import ObjectId

import mimetypes

mimetypes.init()

# Mongo Connection

connection = pymongo.MongoClient("mongodb://localhost")
db = connection.pacman
test_col = db.test
fs = gridfs.GridFS(db)

# Static Routes
@bottle.get('/<filename:re:.*\.js>')
def javascripts(filename):
    return bottle.static_file(filename, root='static/js')

@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
    return bottle.static_file(filename, root='static/css')

@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
    return bottle.static_file(filename, root='static/img')

@bottle.get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
    return bottle.static_file(filename, root='static/fonts')

@bottle.route('/')
def home_page():
    result = db.fs.files.find({"filename": {"$exists": True}})

    return bottle.template('files_test/home', files=list(result))

@bottle.route('/add')
def add_page():
    return bottle.template('files_test/add')

@bottle.route('/upload', method='POST')
def do_upload():
    data = request.files.data
    if data:
        raw = data.file.read()  # This is dangerous for big files
        file_name = data.filename
        try:
            newfile_id = fs.put(raw, filename=file_name)
        except:
            return "error inserting new file"
    print(newfile_id)
    return bottle.redirect('/')

@bottle.route('/download')
def download():
    file_id = ObjectId(bottle.request.query.id)
    if file_id:
        try:
            file_to_download = fs.get(file_id)
        except:
            return "document id not found for id:" + file_id, sys.exc_info()[0]
        file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]

        response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
        response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name
        response.content_length = file_to_download.length
        # print response
        return file_to_download

bottle.debug(True)
bottle.run(host='localhost', port=8080)

add.tpl

<!DOCTYPE html>

    <title>Preformance and Capacity Management</title>
    <link rel="stylesheet" type="text/css" href="style.css">

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="data" />

    <input type="submit"/>
</form>

home.tpl

<!DOCTYPE html>

    <title>Preformance and Capacity Management</title>
    <link rel="stylesheet" type="text/css" href="style.css">

%for fileobj in files:
    Filename: {{fileobj['filename']}}

    Size: {{fileobj['length']}}

    Date Uploaded: {{fileobj['uploadDate']}}

    md5: {{fileobj['md5']}}

    &lt--Download File--&gt

%end


texts: Basic HTML structure for three columns of articles

texts:
I'm new to HTML and programming in general and I want to make sure my code is organized and that I'm using the best practices while I go along.

So, I made this example layout I would like to convert to HTML5:

And this is the HTML5 code I created:

Title

Subhead

Item 1

Lorem ipsum...

Item 2

Lorem ipsum...

Item 3

Lorem ipsum...

Now to the questions:

Is there a difference between using div instead of sections or articles? I mean, not only in the organization realm but also in optimization realm? Is there a general best practice convention nowadays about this specific topic? Because I feel that using sections and articles makes the code easier to read (and also makes the CSS file cleaner).
Should I have a header tag inside each article? I heard this is best practice but I feel like this would make the code harder to read and at the same time I feel like it makes the code more organized so I'm kind of confused what to do.
About code readability: Should I keep a line break between different items like sections? In a small HTML file I'm aware that like breaks wouldn't be a big deal but in a big HTML file you could have like 200 empty lines making the code way bigger than it has to be. What do people usually do about this?


texts:
Currently I need to download thousand of images, I can use 2 functions to download the images: LoadUrl or LoadUrlProxy.

Each function has different parameters:

LoadUrl(url, timeout)
LoadUrlProxy(url, proxy_client, proxy_params)

As I don't want to duplicate the code, I'm looking to simplify the way I'm passing a function reference and its parameters, not sure If below is the best way or I can improve this code?

     # func(Function): Function reference which defines how to download images
      func = LoadUrl
      if use_proxy:
        proxy_client = CreateProxyClient()
        proxy_params = GetProxyParams()
        func = LoadUrlProxy
      images = []

      with futures.ThreadPoolExecutor(max_workers=_MAX_WORKERS) as executor:
        # Start the load operations and mark each future with its URL
        if use_proxy:
          future_to_url = {
              executor.submit(func, image, proxy_client, proxy_params): image
              for image in image_list
          }
        else:
          future_to_url = {
              executor.submit(func, image, _EXECUTOR_TIMEOUT): image
              for image in image_list
          }
        for future in futures.as_completed(future_to_url):
          image = future_to_url[future]
          try:
            images.append((image.master_id, future.result()))
          except Exception as exc:
            logging.exception('%r Generated an exception: %s', image.url, exc)


texts: How to use inversion of control within a strategy when using the strategy pattern

texts:
I am creating a skeleton application to demonstrate use of the Strategy design pattern and inversion of control inside a Strategy.

The application is the backend of a simple board game, which also has the capability to save and load the board. Since we can have different types of data stores for saving, I have used an interface PersistenceStrategy and concrete implementations of it like the FilePersistenceStrategy.

I have listed the code below. However, I am stuck in one place. Inside the FilePersistenceStrategy class, the save() as well as load() methods need to communicate with a file. I do not want these methods to create a file handle (Reader/Writer) themselves, since this will be bad for testability.

I know there are several ways for these methods to get hold of FileReader and FileWriter objects - like getting them from a factory, or getting the FQN from a properties file and instantiating them using reflection.

The most common method of solving this problem - Dependency Injection, cannot be used here because the load() and save() methods come from an interface and we cannot add Strategy specific parameters to the interface.

How would you solve this problem, and what in your opinion are the pros and cons of different approaches ?

Code follows:

Board.java

package com.diycomputerscience.example.sanddi;

public class Board {

    private PersistenceStrategy persistenceStrategy;
    private BoardState state;

    public Board(PersistenceStrategy persistenceStrategy) {
        this.persistenceStrategy = persistenceStrategy;
    }

    //various methods of playing the board game

    public void load() throws PersistenceException {
        this.state = this.persistenceStrategy.load();
    }

    public void save() throws PersistenceException {
        this.persistenceStrategy.save(this.state);
    }
}

BoardState.java

package com.diycomputerscience.example.sanddi;

public class BoardState {

}

PersistenceStrategy

package com.diycomputerscience.example.sanddi;

public interface PersistenceStrategy {
    public void save(BoardState state) throws PersistenceException;
    public BoardState load()  throws PersistenceException;
}

FilePersistenceStrategy.java

package com.diycomputerscience.example.sanddi;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class FilePersistenceStrategy implements PersistenceStrategy {

    @Override
    public void save(BoardState state) throws PersistenceException {
        FileWriter writer = getFileWriter();
        //logic to save the state
        if(writer != null) {
            try {
                writer.close();
            } catch(IOException ioe) {
                String msg = "Could not close FileWriter";
                throw new PersistenceException(msg, ioe);
            }
        }
    }

    @Override
    public BoardState load() throws PersistenceException {
        FileReader reader = getFileReader();
        BoardState state = parseFileForBoardState(reader);
        return state;
    }

    private BoardState parseFileForBoardState(FileReader reader) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ?
     * @return
     */
    private FileReader getFileReader() {
        // Create a FileReader from a well known file name...
        // perhaps a hardcoded name or read name from a config file
        return null;
    }

    /**
     * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ?
     * @return
     */
    private FileWriter getFileWriter() {
        // Create a FileWriter from a well known file name...
        // perhaps a hardcoded name or read name from a config file
        return null;
    }
}

PersistenceException.java

package com.diycomputerscience.example.sanddi;

public class PersistenceException extends Exception {
    //Override all constructors from the superclass

    public PersistenceException(String msg, Throwable cause) {
        super(msg, cause);
    }
}


texts:
I doing some algorithm reviews and am soliciting opinions on my implementation of the Merge Sort in Python.

Anything from readability to optimization is fair game.

In particular, I am wondering if accessing the elements of a list using pop(0) somehow slows things down. I am doing this because I am not aware of a good way to peek into the last for the last element.

Note: The code works on both Python 3 and 2.

import math

def merge(left, right):

    merge_result = []

    while (len(left) > 0 and len(right) > 0):
        if left[0] > right[0]:
            merge_result.append(right.pop(0))
        else:
            merge_result.append(left.pop(0))

    while (len(left)):
            merge_result.append(left.pop(0))

    while (len(right)):
            merge_result.append(right.pop(0))

    return merge_result

def merge_sort(array_to_be_sorted):

    if len(array_to_be_sorted) < 2:
        return array_to_be_sorted

    middle = math.floor(len(array_to_be_sorted) / 2)

    left = array_to_be_sorted[0:middle]
    right = array_to_be_sorted[middle:]

    return merge(merge_sort(left),merge_sort(right))


texts: Create a complete binary tree and do level order traversal on it

texts:
How can I optimize this code?

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

struct Node
{
    int data;
    Node *left,*right;
};

Node *createNode(int data){
    Node *node=new Node;
    node->left=NULL;
    node->right=NULL;
    node->data=data;
    return node;
}

Node buildTree(Node *newNode,queue<Node *>&q){
    Node *f=q.front();
    if(f->left && f->right) {q.pop();f=q.front();}
    if(!f->left) f->left=newNode;
    else if(!f->right) f->right=newNode;
    q.push(newNode);
}

void levelOrder(Node *root){
    queue<Node*>q;
    if(root){
        q.push(root);
        while(!q.empty()){
            Node *d =q.front();
            q.pop();
            cout<<d->data<<" ";
            if(d->left) q.push(d->left);
            if(d->right) q.push(d->right);
        }
    }
}

int main(){
    Node *root=createNode(10);
    queue<Node *>q;
    q.push(root);
    for(int i=0;i<10;i++){
        buildTree(createNode(i),q);
    }
    levelOrder(root);
    return 0;
}


texts:
On my application I use this method to store and to output the data.  I would like to know if it is safely and correct.

##store the data###
//sanitize
function clean($testo)
{
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    $testo = $purifier->purify($testo);

    $testo = mysql_real_escape_string($testo);
    return $testo;
}
$value = clean($_POST[value]);
//the clean function contain mysql_real_escape_string and htmlpurifier class
$sql = mysql_query("insert into table values(null,$value);");

##output the data####
$sql = mysql_query("select * from table");
$val = mysql_fetch_array($sql);
function echoValue($valore){
    $valore = htmlspecialchars(strip_tags(stripslashes($valore)), ENT_QUOTES, "UTF-8");
    return $valore;

}
echo echoValue($val);
// the echoValue function contain strip_tags and htmlentities


texts: Optimizing iteration through linked lists

texts:
I have a data structure composed of several std::lists, each sorted by a specific criterion. When a new item is inserted into this data structure, there is a need for a reference item already in this data structure. Also all the items between the reference and insertee need to be collected into sets.

According to the profiler, this insertion is the bottleneck of the entire program. Here I present a simplified version of my insertion method.

upperReferenceSet_.clear();
lowerReferenceSet_.clear();
for (int objective = 0; objective < nObjectives_; ++objective)
{
    const  Real referenceValue = reference_->value(objective);
    const  Real  inserteeValue =  insertee_->value(objective);
    const bool lower = referenceValue >= inserteeValue;
    const  int directionTowardsInsertee = lower ? -1 : 1;
    Iterator it = referencePositions_[objective];

    ReferenceSet& referenceSet = lower ? lowerReferenceSet_:
                                         upperReferenceSet_;
    const  auto comparison = lower ? [](Real a, Real b){return a >= b;}:
                                     [](Real a, Real b){return a <= b;};

    while (comparison(it->value(), inserteeValue))
    {
        referenceSet.insert(it->individual());
        std::advance(it, directionTowardsInsertee);
    }

    lists_[objective].insert(it, Node(insertee_, inserteeValue));
}

Each list is of type std::list<Node> where the Node is defined by:

class Node
{
public:
    Node(Individual* ind, Real val)       :individual_(ind),value_(val){}
    const Individual* individual() const  {return individual_;}
    Real value() const                     {return value_;}

private:
    Individual* const individual_;
    const Real value_;
};

The Individual is an entity which has n values (objectives), where each value can be accessed by an Individual::value(int index) member function. There are n lists, each containing the same set of Individuals, each sorted by one objective (value). Also the objective pertaining to that list is cached in the node and can be accessed by the Node::value() member function.

I would like to ask how can I make this method faster. I suspect that there are three sources of slowness:

The access to reference sets indirectly using a C++ reference.
The use of lambda functions which produce another indirection.
The use of std::advance just to perform one step.

I am thinking of refactoring the function to pass the data structure in two passes, first for the upper reference sets and then for the lower ones. This would solve all three problems.

I am hesitating since it would result in some code duplicity. Also I am curious about any opinions on my theories and my code.


texts:
I wrote a simple program that converts graphic files in a folder to a single PDF using Magic.NET. It works fine. I'm interested in general comments about the code as well as suggestions how I can make it run faster. Answers with some code are especially welcome.

static void Main(string[] args)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    // Any() needs using System.Linq
    if ( Directory.EnumerateFileSystemEntries(args[0], "*.tif").Any() == false )
    {
        Console.WriteLine("No TIF files found.");
        Environment.Exit(-1);
    }

    string[] directory = Directory.GetFiles(args[0], "*.tif");

    // gets a directory name even when a relative path is given
    // http://stackoverflow.com/a/674495/2657875
    string filename = new FileInfo(directory[0]).Directory.FullName + ".pdf";

    // returns the pathname where the currently executing assembly resides
    MagickNET.Initialize(Path.GetDirectoryName
        (Assembly.GetExecutingAssembly().Location) + @"\MagicSettings");
    Console.WriteLine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
    using (MagickImageCollection collection = new MagickImageCollection())
    {
        foreach (string file in directory)
        {
            MagickImage image = new MagickImage(file);
            image.Quality = 100;
            image.Sharpen(0, 3);
            image.CompressionMethod = CompressionMethod.Group4;
            collection.Add(image);
        }

        try
        {
            collection.Write(filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;
        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}",
            ts.Hours, ts.Minutes, ts.Seconds);
        Console.WriteLine("Done in " + elapsedTime);
    }
}


texts: Calling different class objects using python

texts:
Im trying to get more grip of Classes and also calling different classes to each other which will be more understandable when showing code before:
Utils.py
from proxymanager import ProxyManager # https://pypi.org/project/proxy-manager/

class ProxyServer:
    def __init__(self):
        self.proxy_manager_test = ProxyManager('./test.txt')
        self.proxy_manager_test2 = ProxyManager('./test2.txt')
        self.proxy_manager_test3 = ProxyManager('./test3.txt')
        self.proxy_manager_test4 = ProxyManager('./test4.txt')

    def hello(self):
        return self.proxy_manager_test.random_proxy().get_dict()

    def world(self):
        return self.proxy_manager_test2.random_proxy().get_dict()

    def hey(self):
        return self.proxy_manager_test3.random_proxy().get_dict()

    def yes(self):
        return self.proxy_manager_test4.random_proxy().get_dict()

class Testing:

    def GetData(self, value=None):
        if value:
           dataSaved = getattr(ProxyServer(), value)() # <--- Technically works but is it correct way to do it?
           print(dataSaved)

Main.py

import random
import time
from .utils import Testing

scraper = Testing()

randomList = ["hello", "world", "hey", "yes"]

while True:
    response = scraper.GetData(
        value=random.choice(randomList)
    )
    time.sleep(10)

My concern is the dataSaved = getattr(ProxyServer(), value)() which seem to work as expected but i'm not sure if its correct way to do it, I did get some review about it but the answer I got was that it will technically work but its wrong to do it this way and I want a second opinion from you guys, Is it actually wrong doing it this way?
And please, let me know if I am missing anything else here to provide missing information :)


texts: Extracting English-French cognates from a messy .txt glossary

texts:
After using an online tool to convert a PDF glossary of English-French cognates to a .txt file, I wanted to write a simple script to extract the cognate pairs and save them to a CSV. I could then import them to my flashcard software (Anki). The .txt file ended up being rather messy, and, as a novice programmer who's new to R, the only solution I found was rather crude.

Feedback on the slice/append calls in 1.) and the hideous indexing in 3.) would be particularly appreciated.

library(tidyverse) # dplyr
glossary <- as_tibble(read.delim("papers/frenchcognates.txt", encoding = "UTF-8", stringsAsFactors = FALSE))

## 1.) Extract cognates and language headings into a table. ##
cognates <- glossary %>%
  # Select only the English-French half of the glossary.
  slice(1:1872) %>%
  # Extract the glossary entries (cognates) and headings ("English" or "French")
  filter(str_detect(Glossary, "^[E-F]?[[:lower:]-]+[ \\(to\\)]*$")) %>%
  # Language headings are misplaced for certain letters. Delete...#
  slice(-543) %>%
  slice(-613) %>%
  slice(-723)
#...then move for the while-loop later #
cognates <- append(cognates$Glossary,"French", after=551)
cognates <- append(cognates,"French", after=622) # append() coerced the list to character vector
cognates <- append(cognates,"French", after=733)

## 2.) Loop to separate words into two lists by language heading. ##
words <- vector("list", 2)
lang <- 1 # Using the language headers as a gate
for (word in cognates) {
  if (word == "English") {
  lang <- 1
  } else if (word == "French") {
    lang <- 2
  } else {
    words[[lang]] <- c(words[[lang]], word)
  }

## 3.) Combine lists into matrix/data frame, then save into CSV. ##
# Regex problem: months in English are capitalized, but aren't in French.
words[[2]] <- words[[2]][!(words[[2]] %in% c("août", "décembre", "mars"))]
words.mtx <- cbind(words[[1]], words[[2]])
# Convert to data frame (add colnames first)
colnames(words.mtx) <- c("english", "french") # add column names
words.df <- as_tibble(words.mtx)
# Save to CSV
write_csv(words.df, "writing/cognates") # folder in my wd


texts:
I'm cleaning build directories produced by GNOME build tool, JHBuild. This tool either downloads tarballs or clones git repositories, depending on set-up. After that, it proceeds to compilation (and then installation). Once in a while, something gets screwed up, and I need to clean the build directories so that I can start from scratch (because I don't know how to fix some of these problems).

Here's how I did it, and I'd like you to tell me if it can be improved:

import os
import subprocess

top_level = os.path.expanduser("~/src/gnome")
for filename in os.listdir(top_level):
    full_path = "{}/{}".format(top_level, filename)
    if os.path.isdir(full_path):
        cmd = "cd ~/src/gnome/{} && git clean -dfx".format(filename)
        if subprocess.call(cmd, shell=True) != 0:
            cmd = "cd ~/src/gnome/{} && make distclean".format(filename)
            if subprocess.call(cmd, shell=True) != 0:
                cmd = "cd ~/src/gnome/{} && make clean".format(filename)
                subprocess.call(cmd, shell=True)


texts: Function to filter comments and ratings, with pagination support

texts:
I have a web component that is rendering a list of items and I have this method for filtering these items based in a filterBy object that is being updated by other events and stored in the same component class.

filterBy = {
    comment: '', // string
    rating: [] // array of numbers
}

filterFeedback(items) {
    let filteredItems = [];
    const pagination = { offset: 0, limit: 10, totalCount: items.length };
    const { comment, rating } = this.filterBy;

    const filteringFn = (condition) => {
        items.map((item) => {
            if (filteredItems.length < pagination.limit) {
                if (condition(item)) {
                    filteredItems.push(item);
                }
            } else {
                return;
            }
        });
    }
    if (comment && (!rating || rating.length === 0) && comment !== '') {
        filteringFn((item) => item.comment && item.comment.includes(comment));
    } else if (!comment && rating && rating.length > 0) {
        filteringFn((item) => rating.some((value) => value === item.rating));
    } else if ((comment && comment !== '' )&& rating && rating.length > 0) {
        filteringFn((item) => item.comment && item.comment.includes(comment) && rating.some((value) => value === item.rating));
    } else {
        filteredItems = items ? items.filter((item, i) => i < pagination.limit) : [];
    }

    return filteredItems;
}

I was analyzing this code and trying to make it more clear and readable. I think the filteringFn saves me a lot of code duplication but still, I found the conditionals unreadable. Besides, it's not scalable in case I'd like to add more filters.


texts:
I haven't studied a lot about positioning of controls in ASP.NET using .Net framework 3.5 but still I know following control positioning technique isn't the best one, just to mention its a user control,

    <asp:Label ID="Label2" runat="server" Text="Number of Days"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

Right now I am using tabs and spaces to position controls but can I do it in a better way.


texts: Replacing a variable in a loop by records from a Table

texts:
I have a Date Table like this one:

Exit_Date  Date_ID
2017-05-31    1
2017-04-26    2
2017-01-02    3
2016-12-24    4
2016-11-27    5

I use a loop to insert each of those Dates into a CTE to generates the last 15 years of these dates like this:

declare @DI int = 1
declare @d date
while @DI <=5
begin
    select @d = Exit_Date from Date_Table where Date_ID = @DI
    declare @EDTable table (Exit_Date  Date);
    with
      a as(
        select dateadd(yy,-1,@d) d,0 i
          union all
        select dateadd(yy,-1,d),i+1 from a where i<14
      ),
      b as(select d,datediff(dd,0,d)%7 dd from a)
     insert into @EDTable select d from b;
      set @DI = @DI + 1
 end

The results is correct, I get 75 rows with my dates. I would like to know if there is a way to get rid of the WHILE loop by replacing variable @d by each date record from Date_Table?


texts:
I'm working on this method in Java, which is giving me the factors of a number. I'll be using this method a lot, and I was wondering if there isn't a better way of doing it. Like, with just one loop. Although this code works great and it returns what I expect, I just want to know if there's a better workaround.

The method:

public static void main(String[] args) {
    System.out.print("Enter a positive number: ");
    Scanner scanner = new Scanner (System.in);
    int number = scanner.nextInt();
    int count;
    for (int i = 2; i<=(number); i++) {
        count=0;
        while (number % i == 0) {
            number /= i;
            count++;
        }
    if (count == 0) continue;
        System.out.println(i+ "**" + count);
    }
}

The output I'm expecting:

number = 288;
2**5
3**2


texts: Server socket implementation with Python asyncio

texts:
I want a socket server implementation with the Python asyncio library. I have this code but I don't know if it's correct. I want to implement SSL, too.

I used code from the documentation example and I added some modifications for it the way I want. Now the code works with any client implementation with the socket library, and I added a UNIX signal handler, too.

import asyncio
import functools
import os
import signal

class ServerClientProtocol(asyncio.Protocol):

    def __init__(self):
        self.peername = ""

    def connection_made(self, transport):
        self.peername = transport.get_extra_info('peername')
        print('Connection from {}'.format(self.peername))
        self.transport = transport

    def data_received(self, data):
        print("dato: ", data)
        message = data.decode()
        print('Data received: {!r}'.format(message))

        print('Send: {!r}'.format(message))
        self.transport.write(data)

    def connection_lost(self, exc):
        print('Close {0} socket. Exception: {1}'.format(self.peername, exc))

        self.transport.close()

def ask_exit(signame):
    print("Señal {} recibida: Salir".format(signame))
    server.wait_closed()
    loop.stop()

loop = asyncio.get_event_loop()
for signame in ('SIGINT','SIGTERM'):
    loop.add_signal_handler(getattr(signal, signame),
                            functools.partial(ask_exit,signame))

# Each client connection will create a new protocol instance
coro = loop.create_server(ServerClientProtocol, '127.0.0.1', 12345)
server = loop.run_until_complete(coro)

# Serve requests until CTRL+c is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
print("pid {}: send SIGINT or SIGTERM to exit.".format(os.getpid()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    loop.close()

I want opinions about this code, please.


texts: Need an algorithm to optimize grouping python dictionaries in hierarchical form

texts:
Previously I asked a question on how to group dictionaries in a list in a hierarchical structure.

Initially I wanted to group a list of dictionaries that looks like the following, using multiple keys:

[{'dept':1, 'age':10, 'name':'Sam'},
{'dept':1, 'age':12, 'name':'John'},
.
.
.
{'dept':2,'age':20, 'name':'Mary'},
{'dept':2,'age':11, 'name':'Mark'},
{'dept':2,'age':11, 'name':'Tom'}]

And the output would be:

[
    {
        2: {
            20: [
                {
                    'age': 20,
                    'dept': 2,
                    'name': 'Mary'
                }
            ]
        },
        {
            11: [
                {
                    'age': 11,
                    'dept': 2,
                    'name': 'Mark'
                },
                {
                    'age': 11,
                    'dept': 2,
                    'name': 'Tom'
                }
            ]
        }
    },
    {
        1: {
            10: [
                {
                    'age': 10,
                    'dept': 1,
                    'name': 'Sam'
                }
            ]
        },
        {
            12: [
                {
                    'age': 12,
                    'dept': 1,
                    'name': 'John'
                }
            ]
        }
    }
]

Using this code:

import itertools, operator

l = [{'dept':1, 'age':10, 'name':'Sam'},
        {'dept':1, 'age':12, 'name':'John'},
        {'dept':2,'age':20, 'name':'Mary'},
        {'dept':2,'age':11, 'name':'Mark'},
        {'dept':2,'age':11, 'name':'Tom'}]

groups = ['dept', 'age', 'name']

groups.reverse()
def hierachical_data(data, groups):
    g = groups[-1]
    g_list = []
    for key, items in itertools.groupby(data, operator.itemgetter(g)):
        g_list.append({key:list(items)})
    groups = groups[0:-1]
    if(len(groups) != 0):
        for e in g_list:
            for k,v in e.items():
                e[k] = hierachical_data(v, groups)

    return g_list

print hierachical_data(l, groups)

This method works fine, but now I need to optimize. The dictionaries has a big memory overhead and this grouping gets pretty slow when we are dealing with huge number of records.

I was wondering if there is any algorithm I could use to reduce the time needed to do the grouping.

P.S: I wouldn't mind changing the data-structure as long as it gives me the same hierarchical format, or any better suggestion of course.

Thanks.


texts: Unique Paths II, dynamic programming problem, O(n^2) time, O(n^2) space

texts:
This is based on this leetcode question.  I get the correct answer, but I know it could be much, much cleaner.  I also know there is supposed to be an O(n) space solution, but I'm not sure how to implement cleanly.
It is a dynamic programming problem, I tried to add some helpful code comments, I know it's pretty messy so thank you for your review.
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        #initialize memoization array
        memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]

        #add known values before any calculation (last row and last column)
        memo[len(memo)-1][len(memo[0])-1] = 1
        for i in range(len(memo[0])-2,-1,-1):
            if obstacleGrid[len(memo)-1][i] != 1:
                memo[len(memo)-1][i] = memo[len(memo)-1][i+1]
            else:
                memo[len(memo)-1][i] = 0

        for j in range(len(memo)-2,-1,-1):
            if obstacleGrid[j][len(memo[0])-1] != 1:
                memo[j][len(memo[0])-1] = memo[j+1][len(memo[0])-1]
            else:
                memo[j][len(memo[0])-1] = 0

        if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:
            return 0

        #does calculations
        def helper(row,col):
            nonlocal memo
            if obstacleGrid[row][col] == 1:
                return 0
            if memo[row][col] == -1:
                memo[row][col] = helper(row+1,col) + helper(row,col+1)
            return memo[row][col]

        return helper(0,0)


texts:
I am new to C, but have experience with Python and R. The following code implements the Game of Life and represents my first finger exercise in C. I would like to have some feedback regarding the coding style and conventions in the C community. (I commented out the two Windows specific lines, in case someone wants to run it on another operating system)

//gcc -Wextra -Wall -Werror -O3 -march=native -std=c99 -o test.exe gameOfLife.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
//#include <Windows.h>

void initField(bool field[],
               const size_t rows,
               const size_t cols,
               const float fill)
{
    // fill everything with zeros
    memset(field, 0, rows*cols*sizeof(bool));

    // fill the desired amount of entries with ones
    srand(time(0));
    for(size_t r = 1; r < rows-1; ++r)
        for(size_t c = 1; c < cols-1; ++c)
            if(rand() / (float)RAND_MAX < fill)
                field[r*rows + c] = 1;
}

unsigned countNeighbors(bool field[], const size_t rows, const size_t entry)
{
    return field[entry-rows-1] + field[entry-rows] + field[entry-rows+1] +
           field[entry-1] +                          field[entry+1] +
           field[entry+rows-1] + field[entry+rows] + field[entry+rows+1];
}

void updateField(bool field[], const size_t rows, const size_t cols)
{
    // create a new field filled with zeros
    bool tmp[rows * cols];
    memset(tmp, 0, rows*cols*sizeof(bool));

    // apply update rules and set some entries to one
    for(size_t r = 1; r < rows-1; ++r)
        for(size_t c = 1; c < cols-1; ++c) {
            size_t entry = r*rows + c;
            unsigned neighbors = countNeighbors(field, rows, entry);
            // update entry based on neighbors
            if(neighbors == 3 || (neighbors == 2 && field[entry]))
                tmp[entry] = 1;
        }

    // update the actual field
    memcpy(field, tmp, rows*cols*sizeof(bool));
}

void printField(bool field[], const size_t rows, const size_t cols)
{
    for(size_t r = 0; r < rows; ++r) {
        for(size_t c = 0; c < cols; ++c)
            printf("%i", field[r*rows + c]);
        printf("\n");
    }
    printf("\n");
}

int main()
{
    // actual dimensions are (rows-1)*(cols-1), but for convenience
    // we are going to create a border around it filled with zeros
    const size_t rows = 21;
    const size_t cols = 21;
    bool field[rows * cols];

    // initialize the field with ~20% of entries set to 1
    initField(field, rows, cols, 0.2);

    // print and update the field for some iterations
    for(unsigned i = 0; i < 100; ++i) {
        printField(field, rows, cols);
        updateField(field, rows, cols);
        //Sleep(500);
    }

    return 0;
}


texts:
I would like to give an Integer to whatever demands it. For that I use the following code

public class IntIDGenerator {

    private static int sequence = 1;

    public synchronized static int generate(){
        sequence++;
        return sequence;
    }

}

It is thread-safe because the synchronized term in the method generate(), but I have the feeling that it is possible to implement this generation in a better way. I was thinking in AtomicInteger, but I will have, more or less, the same problem. Any hint?


texts: Returning lines for a given function from a JavaScript file

texts:
The function below iterates through an array that contains all the lines of a JavaScript file (a global array, this_file), and returns just those lines (current_function) containing the text of the function with the name that is passed by the argument (funShun). The code assumes that the function to copy ends whenever '}' by itself (not preceded by whitespace) is spotted (this is true of the file I'm working with).

My question is about whether it would be preferable (and how to do it) to substitute a regex in place of iterating through the file line by line.

This works fine, but it seems to me this could be done with a regex applied to the original Ajax string, but that might be beyond my current regex abilities.

All advice greatly welcome!

// Return an array containing the text of the input function.
function load_function_text(funShun) {
  // Iterate through the present JS file's text.
  var line_num = 0; // Track line num so you can grab the previous line.
  var current_function = [];
  var copying_lines = false;
  this_file.forEach(function(line) {
    // Start copying when 'function funShun' is spotted. (Start pushing from previous line.)
    if (line.match("function " + funShun)) {
      current_function.push(this_file[line_num - 1]);
      current_function.push(line);
      copying_lines = true;
      line_num += 1;
    // Stop copying when '}' is spotted.
    } else if (copying_lines && line === '}') {
      // Add the '}' line.
      current_function.push(line);
      // Stop copying when end of function is reached.
      copying_lines = false;
    } else {
      if (copying_lines) current_function.push(line);
      line_num += 1;
    }
  });
  return current_function;
}


texts:
I call remote server to get my result. Result might contain artist,track and album depends on API method but there will be only one response (artist or track or album) at a time. It mean the other two will be null.  How can I improve:

public void onNext(Result result)
public void renderList(List<?> result). Is it okay the way I am assigning values to the adapter?

private void apiTask(final Observable<Result> observer) {
        observer.subscribe(new Subscriber<Result>() {
            @Override
            public void onCompleted() {
                Log.i(TAG , "onComplete" );
            }

            @Override
            public void onError(Throwable e) {
                    Gson gson = new Gson();
                try {
                    ResponseBody response = ((HttpException) e).response().errorBody();
                    if (response != null) {
                        ApiError apiError = gson.fromJson(response.charStream(), ApiError.class);
                        if (apiError != null && apiError.getMessage() != null) {
                            daoManagerResponse.onError(apiError.getMessage());
                        } else {
                            daoManagerResponse.onError(e.getMessage());
                        }
                    }
                }
                catch (RuntimeException exception) {
                    daoManagerResponse.onError(e.getMessage());
                }
            }

            @Override
            public void onNext(Result result) {
                    try {
                        daoManagerResponse.onResponse(result.getMatchItem().getAlbummatches().getAlbum());
                    }
                catch (NullPointerException e) {
                    Log.e(TAG, e.getMessage());
                }
                try {
                    daoManagerResponse.onResponse(result.getMatchItem().getArtists().getArtists());
                } catch (NullPointerException e) {
                    Log.e(TAG, e.getMessage());
                }

                try {
                    daoManagerResponse.onResponse(result.getMatchItem().getTracks().getTracks());
                } catch (NullPointerException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });
    }

2:-

@Override
public void onResponse(List<?> result) {
    if (result.size() > 0) {
        resultActivityView.renderList(result);
        resultActivityView.onSearchComplete();
    } else {
        resultActivityView.noResult();
    }
}

3:-

@Override
public void renderList(List<?> result) {

    if (result != null && result.size() > 0) {
        if (result.get(0) instanceof Track) {
            TrackAdaptor trackAdaptor = new TrackAdaptor();
            recyclerView.setAdapter(trackAdaptor);
            trackAdaptor.setTracks((List<Track>) result);
        }

        if (result.get(0) instanceof Album) {
            AlbumAdaptor albumAdaptor = new AlbumAdaptor();
            recyclerView.setAdapter(albumAdaptor);
            albumAdaptor.setAlbum((List<Album>) result);

        }

        if (result.get(0) instanceof Artist) {
            ArtistAdaptor artistAdaptor = new ArtistAdaptor();
            recyclerView.setAdapter(artistAdaptor);
            artistAdaptor.setArtists((List<Artist>) result);
        }
    }
}

You can have a look here for better understanding

https://github.com/Iqra786/Radio


texts: Simple mutex and conditional variable signal in C

texts:
I'm new to multithreading in C so I made a toy program that uses a mutex and a conditional variable to communicate between two threads. do_work performs a task every 1 second (task could take longer than 1 second). Is this implementation free from deadlocks and race conditions? Anything else I might be missing?

#include <pthread.h>
#include "errors.h"

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int predicate_value = 0;

void *do_work(void *work) {
    int status = 0;
    int i = 0;
    while (1) {
        status = pthread_mutex_lock(&mutex);
        if (status != 0) {
            err_abort(status, "Lock mutex");
        }
        while (predicate_value == 0) {
            printf("%s\n", "waiting");
            status = pthread_cond_wait(&cond, &mutex);
            if (status != 0) {
                err_abort(status, "Wait on condition");
            }
        }
        if (predicate_value != 0) {
            printf("doing some work: %d\n", i);
            ++i;
            predicate_value = 0;
        }
        status = pthread_mutex_unlock(&mutex);
        if (status != 0) {
            err_abort(status, "Unlock mutex");
        }
    }
}

int main () {
    int status = 0;
    pthread_t work_thread_id;
    status = pthread_create(&work_thread_id, NULL, do_work, NULL);
    if (status != 0) {
        err_abort(status, "Create work thread");
    }
    while (1) {
        if (predicate_value == 0) {
            status = pthread_mutex_lock(&mutex);
            if (status != 0) {
                err_abort(status, "Lock mutex main");
            }
            printf("%s\n", "changed value");
            predicate_value = 1;
            status = pthread_cond_signal(&cond);
            if (status != 0) {
                err_abort(status, "signal condition");
            }
            status = pthread_mutex_unlock(&mutex);
            if (status != 0) {
                err_abort(status, "Unlock mutex main");
            }
            printf("%s\n", "time to sleep");
        }
        sleep(1);
    }
}


texts:
I've created a script to create a module in our MVC framework. The structure of the module is like this (for this example, the module is called test):

test >
    Test.php
    controllers >
        IndexController.php
    models >
        TestModel.php
    open >
       css >
       js >
    views >

Here's what I have for the script. If can have an optional flag of -o to allow the script to remove and override the folder is it already exists.

#!/bin/bash

OVERRIDE=false

while getopts ":o" opt; do
        case $opt in
                o ) OVERRIDE=true
        esac
done

# Check we're in the right directory.

if [ ${PWD##*/} != "modules" ]; then
        echo "Make sure you're in the modules directory"
        exit 1
fi

echo "Enter the module name you want:"

# Get the name, and format it into the formats we need.
read moduleName
lowercaseModuleName=${moduleName,,}
uppercaseFirstModuleName=${lowercaseModuleName^}

# Check if the directory exists already.
if [ -d $lowercaseModuleName ]
    then
        if [ "$OVERRIDE" = true ]; then
                echo "Directory already exists, overridding it because of the -o flag"
                rm -rf $lowercaseModuleName
        else

                echo "Directory '$lowercaseModuleName' already exists, please remove if and try again. To have it overridden please use the -o flag"
                exit 1;
        fi
fi

# Make dir.
echo "Adding module $lowercaseModuleName..."
mkdir $lowercaseModuleName
cd $lowercaseModuleName

# Make root class
echo "Adding Root class..."
cat > $uppercaseFirstModuleName.php << EOF
<?php

class $uppercaseFirstModuleName extends Layer_Shared_Controller {

        public function preDispatch(){

        }
}
EOF

# Make controllers
echo "Adding IndexController..."
mkdir controllers
cd controllers

cat > IndexController.php << EOF
<?php

class IndexController extends $uppercaseFirstModuleName {

        /**
         * Index action.
         */

        public function indexAction(){

        }
}
EOF

# Add model
echo "Adding model..."
cd ../
mkdir models
cd models

cat > $uppercaseFirstModuleName"Model.php" << EOF
<?php

class ${uppercaseFirstModuleName}Model extends Layer_Model {

}
EOF

# Add open folder
echo "Adding open folder..."
cd ../
mkdir open
cd open
mkdir css js
cd ../

# Add view folder
echo "Adding view folder..."
mkdir views
cd ../

echo "Done! Module $uppercaseFirstModuleName created."

Is there anything bad/suboptimal, or that could be done easier?


texts:
Exercise 2.23

  The procedure for-each
  is similar to map. It takes as
  arguments a procedure and a list of
  elements. However, rather than forming
  a list of the results, for-each just
  applies the procedure to each of the
  elements in turn, from left to right.
  The values returned by applying the
  procedure to the elements are not used
  at all -- for-each is used with
  procedures that perform an action,
  such as printing. For example,

(for-each (lambda (x) (newline) (display x))
          (list 57 321 88))
57
321
88

  The value returned by the call to
  for-each (not illustrated above) can
  be something arbitrary, such as true.
  Give an implementation of for-each.

I wrote the following:

(define (for-each l f)
  (f (car l))
  (when (> (length l) 1) (for-each (cdr l) f)))

Is this a good answer?


texts: Parameterized Verilog shift register code

texts:
I am a beginner in FPGAs, and I am studying Verilog HDL. Could you please check the quality of my code (a shift register)? Any comments are welcome.
The shift register serializes parallel from wr_data_i data to serial_data_o and has two variations of first serialized bit. It may be most significant bit or least significant bit, which is defined in parameters as TRUE or FALSE.
`timescale 1ns / 1ps

module shift_reg #
(
  parameter integer DATA_WIDTH   = 16,
  parameter integer DO_MSB_FIRST = "TRUE"
)
(
  input  wire                      clk_i,
  input  wire                      s_rst_n_i,
  input  wire                      enable,
  input  wire                      wr_enable,

  input  wire [DATA_WIDTH - 1 : 0] wr_data_i,

  output wire                      serial_data_o
);
  localparam integer MSB = DATA_WIDTH - 1;
  localparam integer LSB = 0;
  localparam integer XSB = ("TRUE" == DO_MSB_FIRST) ? MSB : LSB;

  reg [DATA_WIDTH - 1 : 0] parallel_data;

  assign serial_data_o = (1'h1 == enable) ? parallel_data[XSB] : 1'hz;

  always @ (posedge clk_i)
    begin
      if (1'h0 == s_rst_n_i)
        begin
          parallel_data <= 'h0;
        end
      else if (1'h1 == wr_enable)
        begin
          parallel_data <= wr_data_i;
        end
      else if (1'h1 == enable)
        begin
          if ("TRUE" == DO_MSB_FIRST)
            begin
              parallel_data <= {parallel_data[MSB - 1 : 0], 1'h0};
            end
          else
            begin
              parallel_data <= {1'h0, parallel_data[MSB: 1]};
            end
        end
    end

endmodule


texts:
I'm using an HTML editor to insert code into a website. When you embed media like an iframe element, it deletes the code.

It's apparently a bug with TINYMce and grappelli, so as a workaround, I insert non-media content into the HTML editor:

width="854" height="480" src="https://www.youtube.com/embed/knYelygG1fI" frameborder="0" allowfullscreen

and then use DOM manipulation to replace the necessary elements.

It might be better to select by class, but I'm not sure how to do that in JavaScript. I've used jQuery innerWrap(), append() and prepend() too, which works. However, as soon as the YouTube embed URL is inserted into the iframe element:

iframe src="youtube/embed/movie"

the videos don't show and the iframes disappear.

This code works, but it just isn't very DRY. I've tested it on an Nginx server, hosted by Digital Ocean. The number of videos is also limited by the number of var strMessage, etc. I have physically written into the template, which isn't very dynamic.

width="854" height="480" src="https://www.youtube.com/embed/knYelygG1fI" frameborder="0" allowfullscreen

width="854" height="480" src="https://www.youtube.com/embed/_9RhLQvr0oc?autoplay=1

width="854" height="480" src="https://www.youtube.com/embed/_9RhLQvr0oc?autoplay=1


texts: Add events dispatching for ActionScript framework Robotlegs

texts:
I have the following function in a Service class

protected function writeToFile():void{
        var destinationFile:File = File.applicationStorageDirectory.resolvePath(_newPath);

        var fs:FileStream = new FileStream();

        fs.open(destinationFile, FileMode.WRITE);
        fs.writeBytes(_buffer, 0, _buffer.length);

        fs.close();

    }

this Service class should dispatch a SuccessfulCreateLocalFileEvent when writeToFile is successful and an UnsuccessfulCreateLocalFileEvent if writeToFile is unsuccessful.

I know that FileStream functions open and writeBytes may throw IOError if there is any problems. And all these FileStream functions all have void as return types.

I believe I need try catch, but I am not entirely sure how to do so.

Please advise.

This question is replicated at http://knowledge.robotlegs.org/discussions/questions/924-what-is-best-way-to-write-dispatch-events-in-this-service-class-function Experimenting which site has better answers for such a question.


texts:
Once a project gets bigger than a couple pages you don't want to have to call up every single page and do find & replace every time there's a change in the database structure. At least, I don't!

My solution has been to make a db handle class series that contains names as variables and queries as methods. But, I'm not very good with classes. I think I'm not coming at it from the right direction.

Sample:

class Users {
    //table
    protected $users = 'users';
        //columns
        protected $user_id = 'user_id';
        protected $username = 'user_name';
        protected $password = 'user_password';
}

class Emails extends Users {
    protected $emails = 'emails';
        protected $address = 'email_address';
        protected $confirm = 'email_confirmed';
        //the foreign key user_id is already defined in users

    function getUserEmail($username) {
        $join = junct([$this->users, $this->emails], $this->user_id);
        $sql = select($join, [$this->address], [$this->username]);
        $result = prepped_query($sql, $username);
        return $result;
    }
}

$x = new Emails();
$email = $x->getUserEmail($username);

One problem so far is that by having a class per table, I can use inheritance for one-to-many tables but many-to-many tables I can't inherit both. It makes awkward joins and forces prioritization where there sometimes isn't.

I have a couple ideas how I could restructure (defining all tables and names in one parent class with methods in children is one idea) but I don't know that any of them would actually be better, and they could have their own problems. Suggestions appreciated.


texts:
I was asked this question in interview:

Check if a number N is a power of K.
Example:
N = 32, K = 2 => True
N = 40, K = 5 => False

I wrote following code but got the feedback that, complexity could have be improved, How to improve its complexity?
def check_kth_power(n, k):
        while n%k == 0:
            n = n/k

        if n != 1:
            return False
        return True

print check_kth_power(128, 5)


texts:
I'm currently working on a website which provides content to users based on their region. As a result the website has subdirectories for the appropriate regions. For example, a pricing page would look something like this:

http://mydomain.com/ie/pricing
http://mydomain.com/gb/pricing
http://mydomain.com/fr/pricing

In order to target the appropriate search engines and signify to Google that there are different versions of the page, I've implemented hreflang tags. A good example of a site that uses these would be view-source:https://www.tripadvisor.ie/. If you view the source you will see a long list of hreflang tags to denote multiple regional versions of the page.

So, for my site, I decided to write a PHP script that would output the relevant hreflang tags on the correct page:

<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url, "pricing") == true): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>

However, the problem I'm facing is that if the URL contains pricing ANYWHERE it will output the above which is not correct if the URL was something like: http://www.mydomain.com/pricing-types.

To counteract this I added another if statement which checks to ensure that the word types is not present in the URL:

<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url,"pricing") == true && strpos($url, "types") == false): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>

Would anyone have any recommendations of how I could improve my script to read the URLs and match them to the appropriate hreflang tags but being more explicit in the URLs I read?


texts: Function that check's file type based on certain keywords

texts:
I have a function that breaks up a source file and checks each token against a keyword list to determine whether its a particular file type. How can I improve this function? Tokenization is a class that contains a function to break up the source code.

public static boolean validationTypeOfSQL(String sourceFile, Tokenization tokenization,ArrayList<String> uniqueKeywordList) {
    ArrayList<Token> createSourceCodeTokens = tokenization.createSourceCodeTokens(sourceFile);

    for (Token x : createSourceCodeTokens) {
        String smallerTokens[] = tokenization.tokenToSmallerToken(x.getToken());
        for (String smallerTOkenValue : smallerTokens) {
            Boolean result = smallerTOkenValue.contains(",");
            if (result == true) {
                String[] tokenSplit = smallerTOkenValue.split(",");
                for (String ts : tokenSplit) {
                    for (String t : uniqueKeywordList) {
                        if (t.toLowerCase().equals(ts.toLowerCase().replace("(", "").replace(",", "").replace(")", "").replace("\t", ""))) {
                            // System.out.println("This is a mysql file Mysql");
                            return true;
                        }
                    }
                }
            }
            else {
                for (String uniqueKeyword : uniqueKeywordList) {
                    if (uniqueKeyword.toLowerCase().equals(smallerTOkenValue.toLowerCase().replace("(", "").replace(",", "").replace(")", "")))
                    {
                        return true;
                    }
                }
            }
        }

    }
    return false;
}


texts:
I'm C# programmer and started Python recently for a new project.

This is a part of my project, and I want your opinion about my code and if it's clean or dirty, too long, has duplicate code, or it's good and standard.

(cmd= command ... at the end of file is just for class testing)

import xml.etree.ElementTree as ET

#TODO: processing attributes should be case insencitive

class command:
    def __init__ (self,htmlcommand):
        self.preview=False
        self.members=[]
        self.__parse__(htmlcommand)

    def __parse__(self,htmlcommand):
        root = ET.fromstring(htmlcommand)
        self.service=root.attrib['service']
        self.name=root.attrib['name']
        self.source=root.attrib['source']
        self.preview=bool(root.attrib['preview'])
        self.procedurename=root.attrib['procedurename']

        mems=root.findall('member')
        if(len(mems)==0):
            raise Exception('command has no member')
        for m in mems:
            self.members.append(member(m))

class member:
    def __init__ (self,member):
        self.params=[]
        self.__parse__(member)

    def __parse__(self,member):
        self.name=member.attrib['name']
        self.method=member.attrib['method']
        try:
            self.order=member.attrib['order']
        except:
            pass
        try:
            self.sort=member.attrib['sort']
        except:
            pass
        self.__parseparams__(member)

    def __parseparams__(self,member):
        params=member.findall('./params/param')
        for p in params:
            self.params.append(param(p))

    #def __getparams(member):

class param:
    def __init__(self,param):
        self.name=param.attrib['name']
        self.value=param.attrib['value']

cmd= command("""<basis core="external.ws.ws" service="bimepasargad" content="33,444" name="Internalissuance" source="cmsDbService" procedurename="sbserviceprocedure2" preview="true">
            <member name="bimepasargadInternalIssuance" method="internalissuance" sort="random">
                <params>
                    <param name="cms.query.token" value="111"/>
                    <param name="duration" value="2222"/>
                </params>
            </member>
            <member name="2" method="2" sort="random">
                <params>
                    <param name="cms.query.token" value="3"/>
                </params>
            </member>
        </basis> """)


texts:
This takes a collection of Objects from JavaScript and puts them into a Java project. How can I improve this code? What's the best solution?

// JavaScript fetch data into List ChartData

int i = 0;
int k = 0;

// output
for (Object currObj : ChartData) {

    // get all fields of Object
    for (Field field : currObj.getClass().getDeclaredFields()) {

        field.setAccessible(true);
        Object value = field.get(currObj);
         // parse only HashMap
        if ((value != null)&&value.getClass().toString().equalsIgnoreCase("class        java.util.HashMap"))) {

            //get HashMap
            HashMap hm = (HashMap)value;
            // Get a set of the entries
            Set set = hm.entrySet();
            // Get an iterator
            Iterator j = set.iterator();

            // Display elements
            while(j.hasNext()) {
               Map.Entry me = (Map.Entry)j.next();
               if ((me.getKey().toString().equalsIgnoreCase("y"))){
                 assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[i][0]); // check pairs
                 System.out.println("Actual y value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][0].toString());
                 i++;
               }

               if ((me.getKey().toString().equalsIgnoreCase("x"))){
                  assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[k][1]);// check pairs
                  System.out.println("Actual x value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][1].toString());
                  k++;
               }
            }
        }
    }
}


texts: Handling `IO Bool` and `IO (Either a b)` inside `IO (Maybe b)`

texts:
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE ScopedTypeVariables #-}

data E a
  = E1
  | E2
  | E3 a

data L
data R

f :: IO (Maybe (E L))
f =
  (undefined :: IO Bool) >>= \case
    False -> return (Just E1)
    True  ->
      (undefined :: IO Bool) >>= \case
        False -> return (Just E2)
        True  ->
          (undefined :: IO (Either L R)) >>= \case
            Left e  -> return (Just (E3 e))
            Right v -> (undefined :: R -> IO ()) v >> return Nothing

How to get rid of these three nested cases?


texts: Dynamically Change Logging Level of a Python Process

texts:
The intention of following code is to dynamically change the logging level of a running python process that has imported this module.

#!/usr/bin/python
import logging
import time
import signal

logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
# create logger object with 'ERROR' level logging.

def handler1(signum, frame):
    logger.setLevel(logging.DEBUG)

def handler2(signum, frame):
    logger.setLevel(logging.INFO)

signal.signal(signal.SIGUSR1, handler1)
# if process receives SIGUSR1 signal, the logging level changes to DEBUG.

signal.signal(signal.SIGUSR2, handler2)
# if process receives SIGUSR1 signal, the logging level changes to INFO.

while True:
    logger.info('info logging')
    logger.debug('debug logging')
    logger.error('error logging')
    logger.warn('warn logging')
    time.sleep(2)

The above script runs as expected but I am not sure if this the right way to full fill the goal. Please review the code, as well as issues in above resolution.


texts: Numbers of length N and value less than K

texts:
I am solving interview question from here.

Problem : Given a set of digits (A) in sorted order, find how many numbers of length B are possible whose value is less than number C.
Constraints: 1 ≤ B ≤ 9, 0 ≤ C ≤ 1e9 & 0 ≤ A[i] ≤ 9
Input: A = [ 0 1 5], B=  1  , C = 2 ; Output:  2 (0 and 1 are possible)
Input: A = 0 1 2 5  , B =  2  , C = 21 ; Output: 5 (10, 11, 12, 15, 20 are possible)

This is my approach
from itertools import product
from itertools import ifilter
def solve(A, B, C):
    if A == [] or B > len(str(C)):
        return 0

    elif B < len(str(C)):
        #constraint is B
        if B == 1:
            new_list = A
            return len(new_list)
        else:
            new_list = list((product((''.join(str(i)for i in A)),repeat = B)))
            b = [''.join(num) for num in new_list]
            c = list(ifilter(lambda  x: x[0]!='0'  , b))
            return len(c)

    elif B == len(str(C)):
        #constraint is C
        if B == 1:
            new_list = [i  for i in A if i< C]
            return len(new_list)
        else:
            new_list = list((product((''.join(str(i)for i in A)),repeat = B)))
            b = [''.join(num) for num in new_list]
            c = list(ifilter(lambda  x: x[0]!='0' and int(x) < C   , b))
            return len(c)

Test cases:
assert solve([2],5,51345) == 1
assert solve([],1,1) == 0
assert solve([ 2, 3, 5, 6, 7, 9 ],5,42950) == 2592
assert solve([0],1,5) == 1
assert solve([0,1,2,5],1,123) == 4
assert solve([0,1,5],1,2) == 2
assert solve([ 3 ],5, 26110) == 0
assert solve([0,1,2,5],2,21) == 5

How can I optimize this code in terms of memory usage?


texts: Extracting site visit information from a REST API call, including addresses from a MySQL database

texts:
I'm building a web app that pulls data from a ticketing system via REST API. I'm currently able to pull all of the data I need just fine but the loading process is really slow. I'd love any feedback regarding the optimization of my code.

<?php
include 'schedule.php';

$curl = curl_init();

foreach ($onsites as $value){

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://portal.-----.com/v4_6_release/apis/3.0/service/tickets?conditions=id%3D$value",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "authorization: -----",
        "cache-control: no-cache",
        "postman-token: -----",
        "x-cw-usertype: integrator"
    )
));

$response = curl_exec($curl);
$err      = curl_error($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    $response = json_decode($response, true);

    foreach ($response as $ticket) {
        $ticket_number = $ticket['id'];
        $summary[]       = $ticket['summary'];
        $company[]       = $ticket['company']['name'];
        $site[]          = $ticket['siteName'];
        $addressLine1  = str_replace('# D', '#D', $ticket['addressLine1']);
        $addressLine2  = $ticket['addressLine2'];
        $city          = $ticket['city'];
        $state         = $ticket['stateIdentifier'];
        $zip           = $ticket['zip'];
        $contact[]       = $ticket['contact']['name'];
        $resources     = $ticket['resources'];
        if(empty($addressLine2)) {
            $full_address[]   = "$addressLine1, $city, $state, $zip, USA";
        } else {
            $full_address[]   = "$addressLine1, $addressLine2, $city, $state, $zip, USA";
        }
    }
}
}

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("scheduler") or die(mysql_error());

if ($ticket_number = $onsites) {
$current_onsites = array();
$i = 0;

for ($i = 0; $i <= count($ticket_number); $i++) {
    @$current_onsites[$i]['id'] = $ticket_number[$i];
    @$current_onsites[$i]['text'] = $summary[$i];
    @$current_onsites[$i]['location'] = $location[$i];
    @$current_onsites[$i]['company'] = $company[$i];
    @$current_onsites[$i]['site'] = $site[$i];
    @$current_onsites[$i]['location'] = $full_address[$i];
    @$current_onsites[$i]['contact'] = $contact[$i];
    @$current_onsites[$i]['start_date'] = date('Y-m-d H:i:s', strtotime($startDate[$i]));
    @$current_onsites[$i]['end_date'] = date('Y-m-d H:i:s', strtotime($endDate[$i]));
    @$current_onsites[$i]['technician'] = $technician[$i];
    @$current_onsites[$i]['hours'] = $hours[$i];
    @$current_onsites[$i]['status'] = $status[$i];
    @$current_onsites[$i]['done'] = $doneFlag[$i];
    @$current_onsites[$i]['ownerFlag'] = $ownerFlag[$i];
    // Retrieve all the data from the db table
    $result = mysql_query('SELECT * FROM xy WHERE company LIKE "'.@$current_onsites[$i]['company'].'";')
        or die(mysql_error());
    // store the record of the "example" table into $row
    $row = mysql_fetch_array( $result );
    @$current_onsites[$i]['lat'] = $row['lat'];
    @$current_onsites[$i]['lng'] = $row['lng'];
}

print "<pre>";
print_r ($current_onsites);
print "</pre>";

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($current_onsites));
fclose($fp);
}

curl_close($curl);

?>


texts:
I need help cleaning up this monstrosity. Basically this is a user helper method that generates an array of cumulative user sign ups per week (start of week == Wednesday) starting 2016-06-15.

So something like this:

[ 1, 5, 9, 22, 34 ]

Where sign ups each week were 1, 4, 4, 13, 12.

In production, this is taking 5 seconds to run (and only 550 users over 7 weeks are present).

  def get_user_array
   @total_date_array = Array.new

    # Remember that the range will go as far as the last Sunday, see next step
    @date_array  = (Date.parse("2016-06-15")..Date.parse(Time.now.strftime("%F"))).select(&:wednesday?)
      @date_array.each do |x|
      start  = x - 7
      finish = x
      @range = start...finish
      @local_user_array = Array.new
      User.all.reject{|u| !u.valid? }.map {|u| @local_user_array << "Yes" if @range === Date.parse(u.created_at.strftime("%F"))}
      @total_date_array <<  @local_user_array
    end

   # Now get the current weeks users
    @current_week_start = @date_array.last
    @current_week_end = Date.parse(Time.now.strftime("%F"))
    @current_week_range = @current_week_start..@current_week_end
    @current_local_user_array = Array.new
    User.all.reject{|u| !u.valid? }.each do |u|
       @current_week_range === Date.parse(u.created_at.strftime("%F")) ? @current_local_user_array << "Yes" : false
    end

    @total_date_array <<  @current_local_user_array

   ## Now create the array....Phew!
   sum = 0
   @total_date_array = @total_date_array.map { |a| Array(a).count("Yes") }.map{ |x| sum  += x }

end

I am fairly inexperienced. I guessing that switching a lot of the code to SQL rather than keeping it in memory is one way to begin.


texts:
I have some data in the following format:

Visitor_id    rownum    contenttype
abc             1          PageA
abc             2          PageB
abc             3          PageC
def             1          PageB
def             2          PageD

This data is for about 40 Million+ visitor_id. I want the result in the following format:

[['1PageA','2PageB','3PageC']
['1PageB','2PageD']]

I wrote the following code to achieve this:

import pandas as pd
import numpy as np
from tqdm import tqdm
d = d.sort_values('visitor_id')
flow_new = []
visitors = set(d['visitor_id'])
for visitor_id in tqdm(set(d['visitor_id'])):
    flow_session = []
    temp = d[d.visitor_id==visitor_id]
    for count in range(0,len(temp)):
        flow_session.append(str(temp.iloc[count,2]) + temp.iloc[count,3])
    flow_new.append(flow_session)

Although this code runs properly and gives me the required results on a smaller dataset, it takes insanely long on the whole dataset. Here's the expected time from tqdm:

  0%|            | 42/12009071 [01:47<7473:36:18,  2.24s/it]

This is obviously extremely long and there has to be another way to do this much quicker.


texts:
Here is my implementation of the k-means algorithm in python. I would love to get any feedback on how it could be improved or any logical errors that you may see. I've left off a lot of the boilerplate code like the command line argument parsing, error handling for data read in from CSV file, etc. and just added the meat of the algorithm.

import os
import numpy as np

# kmeans clustering algorithm
# data = set of data points
# k = number of clusters
# c = initial list of centroids (if provided)
#
def kmeans(data, k, c):
    centroids = []

    centroids = randomize_centroids(data, centroids, k)

    old_centroids = [[] for i in range(k)]

    iterations = 0
    while not (has_converged(centroids, old_centroids, iterations)):
        iterations += 1

        clusters = [[] for i in range(k)]

        # assign data points to clusters
        clusters = euclidean_dist(data, centroids, clusters)

        # recalculate centroids
        index = 0
        for cluster in clusters:
            old_centroids[index] = centroids[index]
            centroids[index] = np.mean(cluster, axis=0).tolist()
            index += 1

    print("The total number of data instances is: " + str(len(data)))
    print("The total number of iterations necessary is: " + str(iterations))
    print("The means of each cluster are: " + str(centroids))
    print("The clusters are as follows:")
    for cluster in clusters:
        print("Cluster with a size of " + str(len(cluster)) + " starts here:")
        print(np.array(cluster).tolist())
        print("Cluster ends here.")

    return

# Calculates euclidean distance between
# a data point and all the available cluster
# centroids.
def euclidean_dist(data, centroids, clusters):
    for instance in data:
        # Find which centroid is the closest
        # to the given data point.
        mu_index = min([(i[0], np.linalg.norm(instance-centroids[i[0]])) \
                            for i in enumerate(centroids)], key=lambda t:t[1])[0]
        try:
            clusters[mu_index].append(instance)
        except KeyError:
            clusters[mu_index] = [instance]

    # If any cluster is empty then assign one point
    # from data set randomly so as to not have empty
    # clusters and 0 means.
    for cluster in clusters:
        if not cluster:
            cluster.append(data[np.random.randint(0, len(data), size=1)].flatten().tolist())

    return clusters

# randomize initial centroids
def randomize_centroids(data, centroids, k):
    for cluster in range(0, k):
        centroids.append(data[np.random.randint(0, len(data), size=1)].flatten().tolist())
    return centroids

# check if clusters have converged
def has_converged(centroids, old_centroids, iterations):
    MAX_ITERATIONS = 1000
    if iterations > MAX_ITERATIONS:
        return True
    return old_centroids == centroids


texts:
I wrote simple compiler for Brainfuck with tcc backend (dont ask for assembler/assembly code generator!). It's output runs incredibly slow. Even Hello World program takes a LOOONG while to execute. I have added some optimizations, but it didnt help. This is code i actually made; It actually doesn't hang, but output work VERY slow (i need to wait ~4 minutes to Hello World display...):

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "libtcc.h"

int minus(FILE* f){
    int c;
    int amount = 0;
    while ((c = getc(f)) == '-')
        amount++;
    ungetc(c, f);
    return amount;
}

int plus(FILE* f){
    int c;
    int amount = 0;
    while ((c = getc(f)) == '+')
        amount++;
    ungetc(c, f);
    return amount;
}

int main(int argc, char** argv){
    int pos = 0;
    int brackets = 0;
    if(argc!=3){
        printf("Brainfuck Compiler by Joel.\n");
        printf("Cannot open input file.");
        exit(0);
    }
    int amount = 1;
    FILE* f = fopen(argv[1], "r");
    printf("Brainfuck Compiler by Joel. All rights reserved.\n");
    if(f!=NULL){
        char* outbuffer = (char*)malloc(1024*1024);
        strcpy(outbuffer, "int getch(void);\nvoid putch(int);\nint mem[65537];\nint main(){\n");
        while(!feof(f)){
            char c = fgetc(f);
            if(c == '<'){
                if(pos==0)pos=65536;
                else pos--;
            }
            if(c == '>'){
                if(pos==65536)pos=0;
                else pos++;
            }
            if(c == '['){
                brackets++;
                sprintf(outbuffer, "%swhile(mem[%d]){",outbuffer,pos);
            }
            if(c == ']'){
                brackets--;
                sprintf(outbuffer, "%s}", outbuffer);
            }
            if(c == '+'){
                amount = plus(f)+1;
                sprintf(outbuffer, "%smem[%d]+=%d;",outbuffer, pos, amount);
            }
            if(c == '-'){
                amount = minus(f)+1;
                sprintf(outbuffer, "%smem[%d]-=%d;",outbuffer, pos, amount);
            }
            if(c == '.'){
                sprintf(outbuffer, "%sputch(mem[%d]);",outbuffer, pos);
            }
            if(c == '.'){
                sprintf(outbuffer, "%smem[%d]=getch();",outbuffer, pos);
            }
        }
        if(brackets == 0){
            sprintf(outbuffer, "%sreturn 0;\n}\n",outbuffer);
            printf("Translation Succesful. ");
            compile(argv[2], outbuffer);
            free(outbuffer);
        }
        else{
            printf("Comilation fault. Unbalanced brackets.");
            free(outbuffer);
        }
    }
    else{
        printf("Cannot open one of specified files.");
    }
}

I don't think it's optimal code, and i need to "optimize" output somewhat. I have generated assembly listing here (shown with output c code): link. I cant find solution, why its so SLOW. Can anyone help me?


texts: Simple surcharge algorithm could use DRY

texts:
I solved this exercise on jshero.com but I know the solution can be written more cleanly, I just don't know how.
Here are the directions:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
This challenge also supposes that you use if...else if...else to solve the exercise. The course also hasn't touched on functions within functions, so I'm mainly concerned with simplification and readability, but also curious about ternaries. Here is my attempt which works,
function addWithSurcharge(num1, num2) {
    let surcharge = 0;
    if (num1 <= 10) {
        surcharge += 1;
    } else if (num1 > 10 && num1 <= 20) {
        surcharge += 2;
    } else {
        surcharge += 3;
    }

    if (num2 <= 10) {
        surcharge += 1;
    } else if (num2 > 10 && num2 <= 20) {
        surcharge += 2;
    } else {
        surcharge += 3;
    }

    return surcharge + num1 + num2;
}

Thank you, much appreciated!


texts: Pattern for classes that provide logger objects

texts:
I need to log the activities of instances of a class. Code that uses the class should be able to disable the default class logger (which, by default, is initialized with a StreamHandler that output log messages to console) and add handlers to it (i.e., to support writing log messages out to a log file).

It appears to work fine. What irks me is that I had to rely on a decorator (per this advice) to initialize the class_logger. This may be unavoidable. I'm ok with it but if there's a better way, I'd like to know about it.

Code for Person class is something I might use in multiple modules. Are there are any outstanding issues with this implementation?

person.py

import logging

def __init_static_members(cls):
    cls.class_logger = cls._init_class_logger()
    return cls

@__init_static_members
class Person:
    class_logger = None

    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    @property
    def basic_info(self):
        return '({},{},{})'.format(self.first_name, self.last_name, self.age)

    def jump(self):
        self.__class__.class_logger.info('{} jumping!'.format(self))

    def shout(self, msg):
        self.__class__.class_logger.info('{} shouting "{}"'.format(self, msg))

    @classmethod
    def _init_class_logger(cls):
        logger = logging.getLogger('PersonClass')
        logger.setLevel(logging.DEBUG)
        console_logger = logging.StreamHandler()
        console_logger.setLevel(logging.DEBUG)
        console_logger.setFormatter(logging.Formatter('%(levelname)5s %(asctime)s:%(message)s', '%Y/%m/%d %H:%M:%S'))
        logger.addHandler(console_logger)
        return logger

    def __str__(self):
        return self.basic_info

if __name__ == '__main__':
    johnny_appleseed = Person('Johnny', 'Appleseed', 17)
    johnny_appleseed.jump() # Uses default class logger
    johnny_appleseed.shout("I'm going to plant apple trees in Pennsylvania, ONtario, Ohio, Indiana, and Illinois!")

    wendy_wonder = Person('Wendy', 'Wonder', 17)
    wendy_wonder.jump() # Uses default class logger

main.py

import os
import logging
from logging.handlers import RotatingFileHandler

import person

def _init_rfh(path):
    rfhandler = RotatingFileHandler(path, mode='a', maxBytes=1000000, backupCount=2)
    rfhandler.setLevel(logging.DEBUG)
    rfhandler.setFormatter(
        logging.Formatter('%(levelname)5s %(asctime)s:%(message)s', '%Y/%m/%d %H:%M:%S')
    )
    return rfhandler

if __name__ == '__main__':

    # Attach a RotatingFileHandler to the Person's class logger
    logpath = r'C:\Users\mtran\Desktop\Development\Python\Python_Notes\ex_classlogger\logs'
    logfilepath = os.path.join(logpath, 'main.log')
    person.Person.class_logger.addHandler(_init_rfh(logfilepath))

    bz = person.Person('Buzz', 'Lightyear', 32)
    bz.jump() # Uses class Person's default logger with RotatingFileHandler attached

    # Disable the Person class logger
    person.Person.class_logger.disabled = True
    bz.jump() # Log message to console and rotating log file is suppressed
    bz.shout('To infinity ... and beyond!')  # Suppressed

    # Enable Person class logger
    person.Person.class_logger.disabled = False
    bz.jump()
    bz.shout('To infinity ... and beyond ... AGAIN!')  # Suppressed

Console Output (main.py)

INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) shouting "To infinity ... and beyond ... AGAIN!"

main.log

INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) shouting "To infinity ... and beyond ... AGAIN!"


texts: Implementing the merge sort with only arrays, out of place

texts:
This has been asked a few times here, but I was wondering what I could do to improve the efficiency and readability of my code. My programming skill has gotten rusty, so I would like to elicit all constructive criticism that can make me write code better.

init:

#include <iostream>
using namespace std;

merge()

//The merge function
void merge(int a[], int startIndex, int endIndex)
{

int size = (endIndex - startIndex) + 1;
int *b = new int [size]();

int i = startIndex;
int mid = (startIndex + endIndex)/2;
int k = 0;
int j = mid + 1;

while (k < size)
{
    if((i<=mid) && (a[i] < a[j]))
    {
        b[k++] = a[i++];
    }
    else
    {
        b[k++] = a[j++];
    }

}

for(k=0; k < size; k++)
{
    a[startIndex+k] = b[k];
}

delete []b;

}

merge_sort()

//The recursive merge sort function
void merge_sort(int iArray[], int startIndex, int endIndex)
{
int midIndex;

//Check for base case
if (startIndex >= endIndex)
{
    return;
}

//First, divide in half
midIndex = (startIndex + endIndex)/2;

//First recursive call
merge_sort(iArray, startIndex, midIndex);

//Second recursive call
merge_sort(iArray, midIndex+1, endIndex);

//The merge function
merge(iArray, startIndex, endIndex);

}

main()

//The main function
int main(int argc, char *argv[])
{
int iArray[10] = {2,5,6,4,7,2,8,3,9,10};

merge_sort(iArray, 0, 9);

//Print the sorted array
for(int i=0; i < 10; i++)
{
    cout << iArray[i] << endl;
}

return 0;
}


texts:
I recently added this CubeMap class to my engine to make handling skyboxes easier. I would like to ask if my OpenGL coding semantics are good, and if I could improve this class in any way.

CubeMap.h:

/*
 * CubeMap.h
 *
 *  Created on: Aug 9, 2015
 *      Author: mattmatt
 */

#pragma once

#include <GL/glew.h>
#include <string>

static const GLenum GL_TEXTURE_CUBE_MAP_TYPES[6] =
                    {
                            GL_TEXTURE_CUBE_MAP_POSITIVE_X,
                            GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                            GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
                            GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
                            GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
                            GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
                    };

class CubeMap {
public:
    CubeMap(
                const char* posXFile,
                const char* negXFile,
                const char* posYFile,
                const char* negYFile,
                const char* posZFile,
                const char* negZFile
            );
    ~CubeMap();

    void Bind(GLenum unit = 0);

    void operator=(const CubeMap& other) = delete;
    CubeMap(const CubeMap& other) = delete;

private:
    GLuint m_texture;
    std::string m_fileNames[6];
};

CubeMap.cpp:

/*
 * CubeMap.cpp
 *
 *  Created on: Aug 9, 2015
 *      Author: mattmatt
 */

#include <alpha/CubeMap.h>
#include "alpha/libs/stb_image.h"
#include "alpha/LogManager.h"
#include <cassert>

CubeMap::CubeMap    (
                        const char* posXFile,
                        const char* negXFile,
                        const char* posYFile,
                        const char* negYFile,
                        const char* posZFile,
                        const char* negZFile
                    )
    :   m_texture(0)
{

    m_fileNames[0] = posXFile;
    m_fileNames[1] = negXFile;
    m_fileNames[2] = posYFile;
    m_fileNames[3] = negYFile;
    m_fileNames[4] = posZFile;
    m_fileNames[5] = negZFile;

    glGenTextures(1, &m_texture);
    glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);

    for (unsigned i = 0; i < (sizeof(GL_TEXTURE_CUBE_MAP_TYPES) / sizeof(GL_TEXTURE_CUBE_MAP_TYPES[0])); ++i){
        int w, h, bytesPerPixel;
        unsigned char*  data = stbi_load((m_fileNames[i].c_str()), &w, &h, &bytesPerPixel, 4);

        if(data == nullptr){
            LOG_ERROR_INFO("CubeMap(Texture)", "Failed to load Texture from file", m_fileNames[i]);
                assert(0);
        }
        glTexImage2D(GL_TEXTURE_CUBE_MAP_TYPES[i], 0, GL_RGB, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        stbi_image_free(data);
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    LOG_INFO("CubeMap(Texture)",  ": Has init successfully : ID is", m_texture );
}

CubeMap::~CubeMap() {
    if(m_texture != 0){
        glDeleteTextures(1, &m_texture);
        LOG_INFO("CubeMap(Texture)",  ": Delete texture object successfully : ID was", m_texture );
    }
}

void CubeMap::Bind(GLenum unit){
    assert(unit >= 0 && unit <= 31);
    glActiveTexture(unit);
    glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
}


texts: jQuery hide and show option value from a dropdown

texts:
I have form with an "add field" button that does an Ajax call to add a new field.

Each field contains a list of options to choose from. When is public is Yes, I need to remove option value = "contacts" and "file upload" from the drop and when the "Add field" button is clicked. If the is public is no, I need to show the option value "contacts" and "file upload".

My code works, but I feel I can improve it.

publicFormValidation = function(){
  $('#public').change(function(){
    if(checkForm()){
      $('.field_type option[value="file_upload"]').hide();
      $('.field_type option[value="contacts"]').hide();
      $('.add_many_fields').on('click',function(){
        setTimeout(function(){
          $('.field_type option[value="file_upload"]').hide();
          $('.field_type option[value="contacts"]').hide();
        }, 500);
      });
    }else {
      var $contacts = $('.field_type option[value="contacts"]');
      var $file_uploads = $('.field_type option[value="file_upload"]');
      $contacts.show();
      $file_uploads.show();
        $('.add_many_fields').on('click',function(){
          setTimeout(function(){
            var $contacts = $('.field_type option[value="contacts"]');
            var $file_uploads = $('.field_type option[value="file_upload"]');
            $contacts.show();
            $file_uploads.show();
        }, 500);
      });
    };
  });
}

checkForm = function(){
  var public_val = $('#public').val();
  return (public_val == "true");
}

The reason I have a setTimeout function is because when I needed to create a delay from when click to hide onto the DOM.