texts: Mapping yielding lots of warnings in use

texts:
Recently, I wrote a C header file that defines a new type called HashMap that allows for the storage of key/value pairs.

I am just learning about the wonders of void pointers and as I use them, I get lots and lots of warnings about making pointers without a cast. The header file itself does not yield any warnings, but when I use the header file, I get lots.

Here is the header file (I am leaving out all the guards and other preprocessor commands):

typedef struct {
    int size;
    void **k;
    void **v;
} HashMap;

void hashmap_init(HashMap *hm, int size) {
    hm->k = malloc(size);
    hm->v = malloc(size);
    hm->size = size;
}

void hashmap_push(HashMap *hm, void *k, void *v, int index) {
    hm->[index] = k;
    hm->[index] = v;
}

void *hashmap_get(HashMap *hm, void *k) {
    int i;
    for(i = 0; i < hm->size; i++)
        if(hm->k[i] == k)
            return hm->v[i];
}

And the file in which I am testing the header:

int main(void) {
    HashMap hm; // a new HashMap
    hashmap_init(&hm, 10); // Initialize the HashMap with 10 spots for memory

    hashmap_push(&hm, 3, 7, 0); // In the first index, put 3 as the key and 7 as it's value

    int v = (int)hashmap_get(&hm, 3); // Get the key dubbed 3 from the hashmap

    printf("%d\n", v); // => 7
    return 0;
}

I was thinking: In Java, when using a HashMap, you initialize it with 2 different values. Would it be better if I did that here? (this is just a second thought - you don't have to answer this too)


texts:
I would like to write a pseudo version of List.map with the help of the Event and Thread modules:

open Thread
open Event

let rec tmap f ls =
    let c = new_channel () in match ls with
        | [] -> []
        | h::t -> let _ = create (fun c -> sync (send c (f h :: tmap f t))) c in
            sync (receive c)

Calling the func:

# tmap (fun a -> a + a) [1;2;3;4;5;6];;
- : int list = [2; 4; 6; 8; 10; 12]

How can I make it smarter? In my case, I'm creating a thread for every list element, so if I had 10k elements this would be bad. My guess it that I should split the list, but how is it usually done?


texts: Safely include requested pages without a whitelist

texts:
Is this pretty safe from breakout attempts? I'd rather not make a whitelist and check if the requested page is in the array since theres a ton of pages. And I wanna keep it clean. So I'm looking for a safe way to include requested pages without a whitelist. Only pages within pages/ should be allowed.

$page_to_include = "pages/default.php";
$content = isset($_GET['content']) ? basename($_GET['content']) : "default";

if (is_file('pages/' . $content . '.php')) {
$page_to_include = 'pages/' . $content . '.php';
}

ob_start();
include $page_to_include;
$included_page = ob_get_clean();

require_once 'header.php';
echo $included_page;


texts: Loading images according to screen width

texts:
This uses HTML5 data attributes to load the image according to the screen width. For example, for laptops. it loads only laptop-sized images. saving bandwidth and optimizing speed.

Live example

    //---------------------------Setting ViewPort Widths-----------------------//
var sSize=768; // High End Mobile Phones
var mSize=1024; // Tables like Ipad Or Something..
var lSize=1336; // Laptop 15 Inch
var xlSize=1500;  // Desktop  22 Inch And Above

//------------------------------ Grabbing Images in Images Array ------------//
var images = document.getElementsByTagName('img');

//--------------------------------Checking Current Resolution Function -----------///
function checkRes()
{
var width = document.documentElement.clientWidth; // grab the width of the screen //
var currentFlag=""; // To Check the Final Resolution

// --------------------- Paths of Img  To Grab ---------------------------//

var  xlImgPath='data-xl';
var  lImgPath='data-l';
var  mlmgPath='data-m';
var  slmgPath='data-s';

//------------------------------  Set CurrentFlag to the Current Browser Size /////////

if (width>=xlSize) {
    currentFlag="xl";
}
else if (width>=lSize   )
{
    currentFlag="l";
}
else if (width>=mSize   )
{
    currentFlag="m";

}
else if (width<=sSize   )
{
    currentFlag="s";

}

    //-------------------------------  Cycle through all the Images And Attach the Proper Src ---------//////////
    for (var i = 0; i < images.length; i++)
    {
        var thisImage=images[i];  // Grab Current Image //
        var defaultImgSource =images[i].getAttribute('src'); // grabs the Current image src (The Default Image)

//-------------------------------------- Switch Case Accoring to Current Size ------------------

switch(currentFlag){

    case 'xl':
                if (thisImage.getAttribute(xlImgPath)!==null)  // If Desktop Image has been defined..
                {

                thisImage.src=thisImage.getAttribute(xlImgPath);   // Set The path of Image to  Desktop Path
            }
            else
            {

                thisImage.src=defaultImgSource; // Else Set the Fefaut src image

            }

            break;
            case 'l':
            if (thisImage.getAttribute(lImgPath)!==null)
            {

                thisImage.src= thisImage.getAttribute(lImgPath);
            }
            else
            {

                thisImage.src=defaultImgSource;

            }
            break;

            case 'm':
            if (thisImage.getAttribute(mlmgPath)!==null)
            {
                thisImage.src=thisImage.getAttribute(mlmgPath);
            }
            else
            {

                thisImage.src=defaultImgSource;

            }
            break;

            case 's':
            if (thisImage.getAttribute(slmgPath)!==null)
            {

                thisImage.src=thisImage.getAttribute(slmgPath);
            }

            else
            {

                thisImage.src=defaultImgSource;

            }
            break;
        }

    }
};

//---------------------------------Run The Function On Page Load ---------------------
checkRes();

HTML

        <img
src="http://s30.postimg.org/rjm6iy2kh/default.jpg"
data-s="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-m="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-l="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-xl="http://s4.postimg.org/4gmjg2m7h/image.jpg" >


texts: Implementation of tree with different node types and faux-polymorphism in C

texts:
I'm currently learning C by working on my first project.
It's a calculator with a parser that transforms input into an operator tree. These trees consist of nodes of different types: Operators (inner nodes), constants and variables. My first attempt was to create a single struct node and just put everything a Node might have in it -- which wastes a lot of memory because not all of the fields are used, depending on the actual type a Node has.

My solution:
I implemented three different structs for the three different Node types.

typedef enum
{
    NTYPE_OPERATOR,
    NTYPE_CONSTANT,
    NTYPE_VARIABLE
} NodeType;

typedef NodeType* Node;

struct VariableNode_
{
    NodeType type;
    char var_name[];
};

struct ConstantNode_
{
    NodeType type;
    double const_value;
};

struct OperatorNode_
{
    NodeType type;
    Operator *op;
    size_t num_children;
    Node children[];
};

They all have a type as their first field -- a header to let me know which type a Node actually has. A Node is always a pointer to the heap, so I typedef'ed it to hide its pointer type. A node may be created and used by the following "constructors" and accessors:

Node malloc_variable_node(char *var_name)
{
    VariableNode res = malloc(sizeof(struct VariableNode_) + (strlen(var_name) + 1) * sizeof(char));
    if (res == NULL) return NULL;
    res->type = NTYPE_VARIABLE;
    strcpy(res->var_name, var_name);
    return (Node)res;
}

Node malloc_constant_node(ConstantType value)
{
    ConstantNode res = malloc(sizeof(struct ConstantNode_));
    if (res == NULL) return NULL;
    res->type = NTYPE_CONSTANT;
    res->const_value = value;
    return (Node)res;
}

Node malloc_operator_node(Operator *op, size_t num_children)
{
    if (num_children > MAX_ARITY)
    {
        // Max. arity exceeded
        return NULL;
    }

    OperatorNode res = malloc(sizeof(struct OperatorNode_) + num_children * sizeof(Node));
    if (res == NULL) return NULL;

    for (size_t i = 0; i < num_children; i++)
    {
        res->children[i] = NULL;
    }

    res->type = NTYPE_OPERATOR;
    res->op = op;
    res->num_children = num_children;
    return (Node)res;
}

void free_tree(Node tree)
{
    if (tree == NULL) return;
    if (get_type(tree) == NTYPE_OPERATOR)
    {
        for (size_t i = 0; i < get_num_children(tree); i++)
        {
            free_tree(get_child(tree, i));
        }
    }
    free(tree);
}

NodeType get_type(Node node)
{
    return *node;
}

Operator *get_op(Node node)
{
    return ((OperatorNode)node)->op;
}

size_t get_num_children(Node node)
{
    return ((OperatorNode)node)->num_children;
}

Node get_child(Node node, size_t index)
{
    return ((OperatorNode)node)->children[index];
}

Node *get_child_addr(Node node, size_t index)
{
    return &((OperatorNode)node)->children[index];
}

void set_child(Node node, size_t index, Node child)
{
    ((OperatorNode)node)->children[index] = child;
}

char *get_var_name(Node node)
{
    return ((VariableNode)node)->var_name;
}

double get_const_value(Node node)
{
    return ((ConstantNode)node)->const_value;
}

Is this common practice? Would there be a better way to do it? Would it have been okay to just waste the space and use a single struct as I did before? This would almost always safe me a level of indirection when dealing with trees and transforming them because all Nodes would have the same size and could be recycled.
If you want to look at the full file(s): node.h hosted at GitHub

Thanks in advance :)

Edit: Changed ConstantType to double because the type was not defined in the excerpt I posted


texts: "Compress" the entry set of Integers in a Map to values incrementing by 1

texts:
What I'm trying to achieve is the following:

Given a Map, where the values may contain duplicates, I want to change the values so that they are incrementing by 1, starting from 1.

Example:

{"One"=1, "Three"=3, "Another three"=3, "Seven"=7} should result in:
{"One"=1, "Three"=2, "Another three"=2, "Seven"=3}

I do this now by:

"Inverting" the map into a com.google.common.collect.Multimap
Build a sorted list of unique values from the original map values (via Java 8 Stream API)
Iterate with ++-increments from 0 until size of unique values, and in the process get(i) the unique value from the sorted list, then map the original string to the value of the incrementing integer into a new map.

I'd be happy to learn if there is a better a.k.a. more elegant or more performant way of doing this!

The relevant JUnit test looks as follows, and passes.

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;

...

@Test
public void mappingTest() {
    Map<String, Integer> map = new HashMap<>();
    map.put("One", 1);
    map.put("Two", 2);
    map.put("AnotherTwo", 2);
    map.put("Three", 3);
    map.put("Seven", 7);
    map.put("AnotherSeven", 7);
    map.put("Ten", 10);

    // Build the "inverted" Multimap
    Multimap<Integer, String> mMap = HashMultimap.create();
    for (Entry<String, Integer> entry : map.entrySet()) {
        mMap.put(entry.getValue(), entry.getKey());
    }

    // Get a list of unique integers compiled from the original map's values
    List<Integer> uniques = map.values().stream().distinct().sorted().collect(Collectors.toList());

    // Map the original keys to the new incrementing values
    Map<String, Integer> fMap = new HashMap<>();
    for (int i = 0; i < uniques.size(); i++) {
        for (String string : mMap.get(uniques.get(i))) {
            fMap.put(string, i+1);
        }
    }

    // Asserts
    assertEquals(fMap.get("One"), Integer.valueOf(1));
    assertEquals(fMap.get("Two"), Integer.valueOf(2));
    assertEquals(fMap.get("AnotherTwo"), Integer.valueOf(2));
    assertEquals(fMap.get("Three"), Integer.valueOf(3));
    assertEquals(fMap.get("Seven"), Integer.valueOf(4));
    assertEquals(fMap.get("AnotherSeven"), Integer.valueOf(4));
    assertEquals(fMap.get("Ten"), Integer.valueOf(5));
}


texts: Criticize my first attempt at using the itertools module

texts:
Here's the exercise:

  Given a string of X's and O's and a maximum number of swaps, determine
  the longest possible sequence of X's after swaps.

Here's my solution using itertools.

import itertools as iter

def swaps_gen(s):
    '''This generator yields all the possible outcome of applying one swap
    to the input string'''
    X_positions = [i[0] for i in enumerate(s) if i[1] == "X"]
    O_positions = [i[0] for i in enumerate(s) if i[1] == "O"]

    for x in X_positions:
        tmp_x = X_positions[:]
        tmp_o = O_positions[:]

        tmp_x.remove(x)
        tmp_o.append(x)

        for o in O_positions:
            ttmp_x = tmp_x[:]
            ttmp_o = tmp_o[:]

            ttmp_o.remove(o)
            ttmp_x.append(o)

            s = []
            for i in ttmp_x: s.insert(i, "X")
            for i in ttmp_o: s.insert(i, "O")
            yield "".join(s)

def flatten(l):
    '''flatten one level. [[a], [b, c]] --> [a, b, c]'''
    return iter.chain.from_iterable(l)

def max_x_after_swap(s, n):
    '''repeat the generate swap_gen n times.
    I used a set() to avoid duplicates.
    Then returns the highest number of consecutive "X"s it finds.'''
    outcomes = [s]
    while n > 0:
        outcomes = set(flatten([list(swaps_gen(x)) for x in outcomes]))
        n -= 1
    return max(map(nbr_of_consecutive_x, outcomes))

def nbr_of_consecutive_x(s):
    '''return the number of consecutive "X" '''
    return max([len(list(v)) for k, v in iter.groupby(s) if k == "X"])

def main():
    input = "XXOXOXOXO"
    swaps_nbr = 2
    print(max_x_after_swap(input, swaps_nbr))

main()

Any criticism is welcome. It'd be great if you could point out any anti-pattern I may present, or show me better (by better I mean more pythonic) way to do things. I am more interested in improving my Python style than improving my algorithm.

I used Python3.1 to run the above.


texts: Cons of declaring derived class type member in another derived class (both of which share the same base class)

texts:
I'd like some input on the way I've structured some things in a side-project I'm working on.

I declare an abstract class, CelestialObj, which will contain the common elements between Planets, and Moons (both of which I'd like to be derived from CelestialObj, obviously).

Now, a Planet must keep track of its Moon objects. Therefore, each of my Planet objects will contain a vector<Moon*> stack. I was wondering if this is bad practice or can cause me trouble later down the line? I can't really find much information regarding this issue on various forums/google searches. Here's a SCCCE version of the code:

class CelestialObj {
protected:
    int size;
    //virtual function definitions here, imaging they're in Moon/Planet too
};

class Moon : public CelestialObj {
public:
    int distFromPlanet;
    Moon() : distFromPlanet(10), size(1000) { }
};

class Planet : public CelestialObj {
public:
    vector<Moon> moons;
    Planet() : size(2000) { Moon mun; moons.push_back(mun); }
};

The actual code is much more organized, with members declared protected/private where appropriate, but this conveys the intended logic.

Is there anything that stands out as dangerous? Or that should be avoided? Minor things such as size being const, and public/private/protected declarations should not be discussed, as they're fine in my actual code. It's just the organization I'm kind of worried about. Is there an alternate organization method anyone recommends? If so, why?


texts: Performing substitutions according to a word list in a database

texts:
A bit of history

I had about 40,000 words in the database. I need words to correct the texts entered incorrectly by users. User enter text in any non-legal format and I use my words in the database to correct them. Everything was great before when when I had less than 50,000 words on my database. Now I have more than 100,000 words on the database.

What method do I use to correct words?

To start, I add all the words to a single database by query to the database.
Example array with correct words:

$correctWords = array{
   "тоҷик",
   "ӯзбек",
   "қазоқ",
   "қирғиз"
   .......,
   "ғайратҷон"
}

With this array, I create another array by replacing some letters(ҷ,ӯ,қ,ғ to ч,у,к,г) with ordinary letters. In a result will be created an associative array from first array with correct words:

$wordBase = array{
   "точик"=>"тоҷик",
   "узбек"=>"ӯзбек",
   "казок"=>"қазоқ",
   "киргиз"=>"қирғиз"
   ................,
   "гайратчон"=>"ғайратҷон"
}

As you can see in the key of the array the wrong variants of words were transferred and the correct version of words was passed to the value of the array. From the text entered by users, I will search for words using words from the array key and replace them with a value to correct the text.

Usage wordbase array to correct incorrect typed words in the text:

$text = "Точик УЗБЕК казок КирГИЗ Гайратчон";

$dictionary = array{
   "точик"=>"тоҷик",
   "узбек"=>"ӯзбек",
   "казок"=>"қазоқ",
   "киргиз"=>"қирғиз"
   ................,
   "гайратчон"=>"ғайратҷон"
}

$output = preg_replace_callback("/\pL+/u", function ($m) use ($dictionary) {
$word = mb_strtolower($m[0]);
if (isset($dictionary[$word])) {
    $repl = $dictionary[$word];
    // Check for some common ways of upper/lower case
    // 1. all lower case
    if ($word === $m[0]) return $repl;
    // 2. all upper case
    if (mb_strtoupper($word) === $m[0]) return mb_strtoupper($repl);
    // 3. Only first letters are upper case
    if (mb_convert_case($word,  MB_CASE_TITLE) === $m[0]) return mb_convert_case($repl,  MB_CASE_TITLE);
    // Otherwise: check each character whether it should be upper or lower case
    for ($i = 0, $len = mb_strlen($word); $i < $len; ++$i) {
        $mixed[] = mb_substr($word, $i, 1) === mb_substr($m[0], $i, 1)
            ? mb_substr($repl, $i, 1)
            : mb_strtoupper(mb_substr($repl, $i, 1));
    }
    return implode("", $mixed);
}
return $m[0]; // Nothing changes
}, $text);

echo $output;

Result

Тоҷик ӮЗБЕК қазоқ ҚирҒИЗ Ғайратҷон

When I have 100,000 words in the database, the function is to fix this text within 13-17 seconds. It takes a lot of time. What can I do to optimize the process of correcting the text with a large number of words? How not to use the whole word from the database to fix a few words? Now my code for fixing 2 words also uses the weight of an array of words and for 1000 words too I use the same. Can I solve the problem with queries on the database itself? If you need a large number of words for testing then please contact me. I will send them to you by reference.


texts: Move two element of an array to the front - Javascript

texts:
I want to move two element of my array to the beginning.
This solution works but I would like to know a better approach since using sort() twice is probably not the best.
Array Input:
colors = [{name: yellow}, {name: blue}, {name: green}, {name: red}, {name: orange}]

JS Function:
sort(){
let green= colors.find(color=> color.name === "green")
let red= colors.find(color=> color.name === "red")

colors.sort(function(x,y){ return x == red? -1 : y == red? 1 : 0; });
colors.sort(function(x,y){ return x == green? -1 : y == green? 1 : 0; });
}

Output:
colors = [{name: green}, {name: red}, {name: yellow}, {name: blue}, {name: orange}]

PS: I want green to always the above red


texts:
I have a dictionary of parameters and value, and the function creates a URL query string from it:

Private Function _BuildUrlFromPermalinkArgumentDictionnary(ByVal oParameters As Dictionary(Of String, String))
    Dim returnString As String = ""
    For Each kvp In oParameters
        returnString += kvp.Key + "=" + kvp.Value + "&"
    Next
    Return Left(returnString, Len(returnString) - 1)
End Function

For example, the input dictionary

A -> 12356
B -> foo
C -> bar

have the output A=12356&B=foo&C=bar

I would like to improve this, not really for performance, because the dictionary is small enough that it will be really fast no matter what, but as an opportunity to learn what I could have done in a better way.

In particular, the way I remove the trailing & feels wrong.


texts: Efficiently compare 2 lists to replace and order

texts:
I have 2 list containing some Objects (Fruit class). I am using a 3rd list to add these elements based on following 2 criteria.

I want every object in the 1st list added to 3rd list. But if I have a matching object in the 2nd list (matching based on id and isChecked), I want to add the object from the 2nd list to the 3rd list and ignore the one in 1st list.
If I did the switch mentioned on point one, I want to move that object up to the first element of the 3rd list.

I have it working with following code. But I find it very inefficient. Is there a better way around it?

Bear in mind I have no control over the second list, but the first list is coming from a Rest endpoint and I am currently capturing it as a list. Unsure if I should have opted for a Map. Please advice.

Example:

In the following example, expected list output is [f2, f5, f1, f3, f4] (based on name).

It is cos I have all the elements from the first list. f2 and f5 went in front of the order as they came from second list (they matched elements in first list and had isChecked set to true).

import lombok.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class App {
    public static void main(String[] args) {

        Fruit fruit1 = new Fruit("1", "f1", false);
        Fruit fruit2 = new Fruit("2", "f2", false);
        Fruit fruit3 = new Fruit("3", "f3", false);
        Fruit fruit4 = new Fruit("4", "f4", false);
        Fruit fruit5 = new Fruit("5", "f5", false);

        List<Fruit> firstList = Arrays.asList(fruit1, fruit2, fruit3, fruit4, fruit5);

        Fruit fruit6 = new Fruit("2", "f2", true);
        Fruit fruit7 = new Fruit("7", "f7", false);
        Fruit fruit8 = new Fruit("5", "f5", true);
        Fruit fruit9 = new Fruit("9", "f9", false);
        Fruit fruit10 = new Fruit("10", "f10", false);

        List<Fruit> secondList = Arrays.asList(fruit6, fruit7, fruit8, fruit9, fruit10);

        List<Fruit> finalList = new ArrayList<>();

        // expected list = [f2, f5, f1, f3, f4]

        // this loop is checking and adding objects to finalList.
        // must match the first list and isChecked.
        // in this case, only f6 and f8 matches the first list (id match) and is also 'checked'.
        for (Fruit first : firstList){
            for (Fruit second : secondList){
                if(first.getId().equals(second.getId()) && second.isChecked()){
                    finalList.add(second);
                    break;
                }
            }
        }

        // not done yet. Still need to loop and add back the elements from the first list
        // which were not added in the above loop
        boolean addedFirst = false;
        outer:
        for(Fruit first : firstList){
            for(Fruit finalFruit : finalList){
                if(first.getId().equals(finalFruit.getId())){
                   continue outer;
                }
            }
            finalList.add(first);
        }

        for(Fruit fruit : finalList){
            System.out.println(fruit);
        }
    }
}

@Getter
@Setter
@ToString
class Fruit{
    private String id;
    private String name;
    private boolean isChecked;

    Fruit(String id, String name, boolean isChecked) {
        this.id = id;
        this.name = name;
        this.isChecked = isChecked;
    }
}


texts:
I am new to javascript and want to make sure I am on the right track when playing a sound. Is there anything I should not be doing better or not be doing at all. Below is a simple function.

  Click here to hear a sound

I am not sure whether I should be using the audio tag or not. I appreciate any feedback


texts:
The purpose of this class is to wrap a std::vector in a class so that never a new object is added. We don't allocate a new object on the stack but we trying to fit it on the current memory page, or create a new page for it.

#include <vector>

template<class T>
class  PagedVector {

public :
    PagedVector(int initialCapacity, float load_factor = 1.5f):
    pageSize(static_cast<size_t>(load_factor*initialCapacity*sizeof(T))),
    current_byte_offset(0),
    current_page(0)
    {
        data.reserve(initialCapacity);

        //initialise one page:
        char* ptr = static_cast<char*>(malloc(pageSize));
        pages.push_back(std::make_pair(ptr, pageSize));
    }

    template<class U>
    U* create() {
        char* memoryPtr = getNextAdress(sizeof(U), std::alignment_of<U>::value);
        U* objectPtr = new (memoryPtr) U();
        data.push_back(objectPtr);
        return objectPtr;
    }

    ~PagedVector() {
        //delete objects
        for(T* obj : data) {
            obj->~T();
        }

        //free memory
        for(auto& pair : pages) {
            free(pair.first);
        }
    }

    void reset() {
        //delete objects
        for(T* obj : data) {
            obj->~T();
        }
        data.clear();

        //keep memory but reset page count
        current_page = 0;
        current_byte_offset = 0;
    }

    const std::vector<T*>& getData() const {
        return data;
    }

private :
    std::vector<T*> data;
    std::vector< std::pair<char* , size_t > > pages;

    size_t pageSize;
    size_t current_byte_offset;
    int current_page;

    char* getNextAdress(size_t size, size_t align) {
        //get next available adress for type with given size and aligment

        char* current_page_adress = pages[current_page].first + current_byte_offset;
        char* end_page_adress = pages[current_page].first + pages.back().second;

        size_t remainder_align = reinterpret_cast<uintptr_t>(current_page_adress) % align;
        size_t extra_alignment_padding = remainder_align==0 ? 0 : (align - remainder_align);

        char* next_aligned_adress = current_page_adress + extra_alignment_padding;
        char* end_aligned_adress = next_aligned_adress + size;

        if(end_aligned_adress < end_page_adress) {
            current_byte_offset += size + extra_alignment_padding;
            return next_aligned_adress;
        }

        //no more space on the current page, have to reallocate a new one:

        //in the rare case where the object size > page size
        size_t nextPageSize = std::max(pageSize, size);

        char* ptr = static_cast<char*>(malloc(nextPageSize));
        pages.push_back(std::make_pair(ptr, nextPageSize));
        current_byte_offset = size;
        ++current_page;
        return ptr;
    }

    //non-copiable:
    PagedVector(PagedVector&);
    PagedVector& operator=(PagedVector&);
};

Usage:

PagedVector<Base> pv(5);
    pv.create<Base>();
    Derived* p = pv.create<Derived>();

I'm wondering if this is correct (not relying on UB). I've never dealt that much with placement new and manual memory management.


texts:
This is just a little number guessing game. I know it's simple but I am a newbie in C and I think such a little example can be enough for finding simple design flaws that can than be eliminated.

If you know how parts of the code can be written more beautiful and more safe, please let me know!

/*
 * In this program the user has to guess a number between 1 and 99.
 * He has six tries.
 */

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

int generate_random_number(int lower_range, int upper_range)
{
    srand(time(0));
    return (rand() % (upper_range - lower_range + 1)) + lower_range;
}

// this function stops the program until useless input is entered
void pause()
{
    int useless;
    scanf("%i", &useless);
}

int main()
{
    // generate random number
    const int lower_range = 1;
    const int upper_range = 99;
    const int random_number = generate_random_number(lower_range, upper_range);

    // start of game
    printf("You have to guess a number between 1 and 99.\n");
    printf("You have six tries.\n");
    const int tries = 6;
    for (int i = 0; i < tries; i++)
    {
        printf("> ");
        int guess;
        scanf("%i", &guess);

        if (guess > random_number)
        {
            printf("The secret number is smaller.\n");
        }
        else if (guess < random_number)
        {
            printf("The secret number is higher\n");
        }
        else if (guess == random_number)
        {
            printf("You found the secret number!\n");
            pause();
            return 0;
        }
    }

    printf("You haven't found the secret number.\n");
    printf("The secret number was %i.\n", random_number);
    pause();
}


texts: Copying data from an Excel sheet to Word

texts:
This code copies a specific range and a chart from an Excel sheet to Word. This code works fine but it is very slow. I have used delays(Wait) to work properly while dealing with clipboard copy-paste. If I don't use delays as error occurs.

This program copies 140 Excel-ranges and 140 charts, so it takes a lot of time. Any suggestions to make the program execute faster?

Sub ExcelToWord()
    Dim fileName, Pathname As String
    Dim WB As Workbook
    Dim mychart As ChartObject
    Pathname = "c:\Charts\"
    vArr = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")
    For Each vFile In vArr
        fileName = Dir(Pathname & vFile & "\" & "*.xlsx")
        Dim WdObj As Object
        Set WdObj = CreateObject("Word.Application")
        WdObj.Documents.Add
        'Loop for all files begins
        Do While fileName <> ""
            Set WB = Workbooks.Open(Pathname & vFile & "\" & fileName)
            ActiveSheet.Columns("C:C").Select
            Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            Dim rLastCell As Range
            Dim ColLtr As String
            Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=ActiveSheet.Cells(1, 1), LookIn:=xlFormulas, Lookat:= _
            xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
            ColLtr = Replace(Cells(1, rLastCell.Column).Address(True, False), "$1", "")
            ActiveSheet.Columns(ColLtr).Copy
            ActiveSheet.Columns("C").Select
            ActiveSheet.Paste
            Application.CutCopyMode = False
            Dim lastrow As Long, lastcol As Long
            Dim rngTemp As Range
            With ActiveSheet
                If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                    lastrow = .Cells.Find(What:="*", _
                                          After:=.Range("A1"), _
                                          Lookat:=xlPart, _
                                          LookIn:=xlFormulas, _
                                          SearchOrder:=xlByRows, _
                                          SearchDirection:=xlPrevious, _
                                          MatchCase:=False).Row
                    lastcol = 3
                Else
                    lastrow = 1: lastcol = 1
                End If
                Set rngTemp = .Range("A1:" & Split(.Cells(, lastcol).Address, "$")(1) & lastrow)
                Set mychart = ActiveSheet.ChartObjects(1)
            End With
            WdObj.Visible = True
            WdObj.Activate
            rngTemp.Select
            Application.Wait (Now + TimeValue("0:00:01"))
            Selection.Copy
            DoEvents
            Application.Wait (Now + TimeValue("0:00:01"))
            WdObj.Selection.PasteSpecial
            Application.CutCopyMode = False
            mychart.Select
            Application.Wait (Now + TimeValue("0:00:01"))
            Selection.Copy
            DoEvents
            Application.Wait (Now + TimeValue("0:00:01"))
            WdObj.Selection.PasteSpecial
            Application.CutCopyMode = False
            Const wdPageBreak = 7
            Application.Wait (Now + TimeValue("0:00:01"))
            WdObj.Selection.InsertBreak (wdPageBreak)
            Application.Wait (Now + TimeValue("0:00:01"))
            Application.CutCopyMode = False
            WB.Close SaveChanges:=False
            fileName = Dir()
        Loop
        Dim fname As String
        fname = "Converted and Combined.docx"
        Application.CutCopyMode = False
        With WdObj
            .ChangeFileOpenDirectory "C:\Charts\" & vFile & "\"
            .ActiveDocument.SaveAs fileName:=fname
        End With
        With WdObj
            .ActiveDocument.Close
            .Quit
        End With
        Set WdObj = Nothing
    Next
End Sub


texts: Generating a complicated data structure in a more efficient manner

texts:
I need to convert some CSV data into a format recognizable by some old script my work uses. Changing the format is pretty much out of the question. So I've written this:

$rate_plan_terms = [
  "pp",
  "01",
  "12",
  "24",
  "36"
]

def generate(fname)
  puts "generating doc for #{fname}"
  file = File.open(fname)
  standard_offer_hash = {}
  features_hash = {}

  file.readlines[1..-1].each do |row|
    # standard_offers
    _region, offer_cid, _offer_code, offer_name, product_cid, product_name, component_name, component_cid = *row.split(",")
#used? no   yes        no          yes         kinda        yes           yes             yes

    standard_offer_hash[product_cid] ||= {}
    standard_offer_hash[product_cid][:offerType] = product_name # just keep it as product_cid?
    standard_offer_hash[product_cid][:ratePlan] ||= []

    $rate_plan_terms.each do |term|
      rate_plan = {
        :ratePlanName       => offer_name,
        :ratePlanCode       => offer_cid,
        :ratePlanTerm       => term,
        :offerEffectiveDate => "",
        :ratePlanMRC        => ""
      }

      standard_offer_hash[product_cid][:ratePlan] << rate_plan unless standard_offer_hash[product_cid][:ratePlan].include? rate_plan # they will be repeated because of features
    end

    # features
    features_hash[component_cid] ||= {
      :featureName          => component_name,
      :featureCode          => component_cid,
      :featureType          => "FEATURE",
      :featureTerm          => "",
      :featureEffectiveDate => "",
      :featureMRC           => ""
    }

  end
  feature_arr = features_hash.map {|k,f| f}
  standard_offer_arr = standard_offer_hash.map {|k,o| o}
  product_arr = []

  pricelist = {
    :features => { :feature => feature_arr }
    :ChannelOrgType => "OCM",
    :Region => "ALL",
    :product => product_arr,
    :businessRelationship => "",
    :standardOffer => standard_offer_arr,
  }

  {:PriceList => pricelist}
end

Yeah, complicated. This is running on up to a million lines per file, usually two files, every day. So it needs to be faster than it currently is.

FYI, the CSV is loosely separated into many products belong to many offers, and products have many features, but two different products can have the same features. So there is a lot of repeating.

There seem to be two time sinks here. One is the Array#include? I'm running over and over again. I wanted to transform that into a build hash -> convert to array later approach I took with features_arr and standard_offers_arr to avoid doing searches. But it depends on the product_cid, which (could) change per row.

The second is those two hashes to arrays at the end. The standard_offer_hash is going to be huge. That's can't be very fast.

To be completely honest I just don't see a way to optimize this further. Any suggestions?

I can show some output for what the generated structure needs to look like, if it would help.


texts:
I have a Word Search algorithm, the main function (wsearch) takes a grid of letters as an input and a 'word' to search for. The output is the number of occurence of the 'word' in the grid.

First, I break down the problem into three functions (including wsearch).

The nword is for looking the number of occurence of a 'word' in a string. For example: string bananana has 4 occurence of word nana. Note that occurence of anan is counted as nana (backward).
The fdiags stands for 'find all diagonals' or the grid/matrix. It returns a list of all strings representing the diagonals.
Finally, the wsearch uses the 2 functions above.

Example:

grid = [list(input()) for j in range(5)]
word = input()
wsearch(grid, word)

input:

gogog
ooooo
godog
ooooo
gogog
dog

The output will be 8 (horizontal, vertical, and diagonal form of dog).

How to make it more readable and efficient?

The functions:

def nword(string, word):
    normal = string
    listed = list(normal)
    listed.reverse()
    reverse = ''.join(listed)

    n = len(word); count = 0;

    idx = 0; start = 0;
    while idx >= 0:
        idx = normal.find(word, start)
        if idx >= 0:
            count+=1
        start=idx+1
    idx = 0; start = 0;
    while idx >= 0:
        idx = reverse.find(word, start)
        if idx >= 0:
            count+=1
        start=idx+1

    return count

def fdiags(grid):
    n = len(grid[0])
    m = len(grid)

    diags = []
    Ll = [(1, n-1)] + [(0, i+1) for i in range(n-1)]
    Lr = [(1, 0)] + [(0, i) for i in range(n-1)]
    for l,r in zip(Ll, Lr):
        diags.append(''.join([ grid[l[0]+j][l[1]-k] for j, k in zip(range(m-l[0]), range(l[1]+1)) ]))
        diags.append(''.join([ grid[r[0]+j][r[1]+k] for j, k in zip(range(m-r[0]), range(n-r[1])) ]))

    return diags

def wsearch(grid, word):

    n = len(grid[0])
    m = len(grid)
    if n == 1:
        from_cols = sum([nword(''.join(i), word) for i in zip(*grid)])
        return from_cols
    if m == 1:
        from_rows = sum([nword(''.join(i), word) for i in grid])
        return from_rows
    from_diags = sum([nword(i, word) for i in fdiags(grid)])
    from_cols = sum([nword(''.join(i), word) for i in zip(*grid)])
    from_rows = sum([nword(''.join(i), word) for i in grid])
    return from_diags+from_cols+from_rows


texts:
I want to create an adjacency list based on data I get from a text file. Could I make this simpler?

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

struct Vertex;
struct Edges;

struct Edges
{
    // edges link the vertex
    Vertex * linkTo;
    // pointer to vertex node
    Edges * next;
};

struct Vertex
{
    int parent;
    int child1;
    int child2;
    int child3;
    int child4;
    int child5;
    int child6;
    int child7;
    int child8;
    Vertex * next;
    Edges * Links;
    // pointer to edges list
    void Add_data(Vertex * node);
};

class Graph
{
    public:
      Vertex vertices;
    // call the vertex struct to the Graph
    private:
      void BFS();
};

//-------------------------------- Function Implementation--------------------------

void Add_data(Vertex * node)
{
    ifstream file("Table.txt");
    string line;
    int parent;
    int child1;
    int child2;
    int child3;
    int child4;
    int child5;
    int child6;
    int child7;
    int child8;

    while(getline(file,line))
    {
        istringstream data(line);
        if(!(data>>parent>>child1>>child2>>child3>>child4>>child5>>child>>6>>child7>>child8))
        {
            cout << "Error " <<endl;
        }
        else
        {
            node->parent = parent;
            node->child1 = child1;
            node->child2 = child2;
            node->child3 = child3;
            node->child4 = child4;
            node->child5 = child5;
            node->child6 = child6;
            node->child7 = child7;
            node->child8 = child8;
            node->next = NULL;
        }
    }
}


texts:
I've written code to parse dollars and cents entered by the user.  The value returned is the total number of cents.

For example:

f('$1.50') = 150

f('1.5') = 150

f('0') = 0

f('1000') = 1000

f('$12,500.00') = 12500000

functions.GetTotalCents = function (dollarsAndCentsString) {
    // Cast the value passed in to a string in case a number was passed in.
    dollarsAndCentsString = dollarsAndCentsString.toString();
    // First, discard the '$' glyph, if it was passed in.
    if (dollarsAndCentsString.split('$').length == 2)
        dollarsAndCentsString = dollarsAndCentsString.split('$')[1];
    // If the user delimmited the groups of digits with commas, remove them.
    dollarsAndCentsString = dollarsAndCentsString.replace(/,/g, '');
    // Next, divide the resulting string in to dollars and cents.
    var hasDecimal = (dollarsAndCentsString.split('.')).length == 2;
    var dollarsString, centsString;
    dollarsString = dollarsAndCentsString.split('.')[0];
    var centsString = hasDecimal ? dollarsAndCentsString.split('.')[1] : '0';
    var dollars = parseInt(dollarsString, 10);
    var cents;
    if (centsString.length == 1)
        cents = parseInt(centsString, 10) * 10;
    else cents = parseInt(centsString, 10);
    if (cents > 99 || isNaN(cents) || isNaN(dollars) || !isFinite(dollars) || !isFinite(cents))
        return 0;
    var totalCents = dollars * 100 + cents;
    return totalCents;
};

Anyone care to critique my code?


texts: Combine keycode regex and variable array

texts:
I am using the following code to try and only allow letters, numbers, backspace, space, dashes, slashes, and ampersands. I also want all other keys including the function keys (F1, F2, etc) to be disallowed. I feel like this code can be optimized to make it more streamlined.

This function is part of a live search feature, and I dont want the ajax request to be sent if on of the "prohibited" keys are pressed.

searchBox.keyup(function (e) { // DYNAMIC AUTO SEARCH FUNCTION

        var functionKey = [112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123].indexOf(e.which) > -1;

        if (!String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]\x08/) && !functionKey) {

        // code to execute if key is allowed

        }

});


texts: Miller-Rabin Prime test (Speed is the main goal)

texts:
The code below is for testing Primes.

testPrime(100000);
testPrime(1000000);
testPrime(10000000);
testPrime(100000000);

Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for IsPrime?

import java.util.ArrayList;
import java.math.*;

class Primes {

    private static long[] as = {2, 7, 61};

    private static long modpow(long x, long c, long m) {
        long result = 1;
        long aktpot = x;
        while (c > 0) {
            if (c % 2 == 1) {
                result = (result * aktpot) % m;
            }
            aktpot = (aktpot * aktpot) % m;
            c /= 2;
        }
        return result;
    }

    private static boolean millerRabin(long n) {
        outer:
        for (long a : as) {
            if (a < n) {
                long s = 0;
                long d = n - 1;
                while (d % 2 == 0) {
                    s++;
                    d /= 2;
                }

                long x = modpow(a, d, n);
                if (x != 1 && x != n - 1) {
                    for (long r = 1; r < s; r++) {
                        x = (x * x) % n;
                        if (x == 1) {
                            return false;
                        }
                        if (x == n - 1) {
                            continue outer;
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean IsPrime(long num) {
        if (num <= 1) {
            return false;
        } else if (num <= 3) {
            return true;
        } else if (num % 2 == 0) {
            return false;
        } else {
            return millerRabin(num);
        }
    }
    public static int[] primes(int min, int max) {
           ArrayList<Integer> primesList = new ArrayList<Integer>();

           for( int i=min; i<max; i++ ){
                if( IsPrime(i) ){
                   primesList.add(i);
                }
           }

           int[] primesArray = new int[primesList.size()];
           for(int i=0; i<primesArray.length; i++){
               primesArray[i] = (int) primesList.get(i);
           }

           return primesArray;
        }

    public static String tostring (int [] arr){
        String ans="";
        for (int i=0; i<arr.length;i++){
            ans= ans+arr[i]+ " ";
        }
        return ans;
    }
     public static int closestPrime(int num) {
            int count=1;
            for (int i=num;;i++){

                int plus=num+count, minus=num-count;
                if (IsPrime(minus)){

                    return minus;

                }

                if (IsPrime(plus)) {
                    return plus;

                }
                count=count+1;
            }
        }

    }

//end class


texts: Deleting rows from a spreadsheet where Column C is blank

texts:
I have a script which I use to delete rows from a Excel Sheet, dependent on the Column C cell of that row being blank.

I believe deleting a range might be quicker than deleting individual rows, but I'm unsure.

Sub Shorter()

'47ms to remove blanks rows of 80 rows

'Searches the designated Column and checks for a Blank Cell
'It then Sets a Marker and then continues until it finds a cell with data in it.
'That blank range is then deleted.

    t = GetTickCount
    With ActiveSheet

        Firstrow = 20
        LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

        For i = LastRow To Firstrow Step -1

            If i = StartRow - 1 Then GoTo EndSubAutoDeleteRowsFromEndRow
            If .Cells(i, "C") = Empty Then

                DelRangeStartRow = i

                ii = 0

                Do While .Cells(i - ii, "C") = Empty
                    DelRangeEndRow = (i - ii)
                    ii = ii + 1
                Loop

                Range(.Rows(DelRangeStartRow), .Rows(DelRangeEndRow)).Delete Shift:=xlUp

            End If
        Next i
    End With
    'Come here if you are finished deleting

    EndSubAutoDeleteRowsFromEndRow:

    SecondsElapsed = GetTickCount - t

End Sub


texts: Checking string length limitation and add items to it in a shorter way with Linq

texts:
This method has three parameters. If the extension is not null, for each item in list try to add extension to main text in a way that length of result doesn't exceed 20.

I wrote this code, but I don't like its style. I like to use Linq and newer styles for doing this, in order to make it shorter.

public string AddExtension(IList<string> extension, bool needDefaultAdd, string text )
{
    if (needDefaultAdd)
    {
        if (extension==null)
        {
            string tempText = text + "deafult extension txt";
            if (text.Length >20)
            {
                return text;
            }
            else
            {
                return tempText;
            }
        }
        else
        {
             string finalResult = null;
            foreach (var e in extension)
            {

                string tempText = text + "deafult extension txt";
                if (text.Length > 20)
                {
                    finalResult=text;
                }

                var temp2Text = tempText +e;
                if (text.Length > 20)
                {
                    finalResult=tempText;
                }
                else
                {
                    finalResult = finalResult + temp2Text;
                }
            }
            return finalResult;
        }

    }
    return text;
}


texts: A simple web-app code - user registration. Is the layering ok?

texts:
So knowing the little pieces is something different and putting them together is something different.

Here is the code where I try to follow good oop practices and 3 - layered structure.

Any review is greatly appreciated:

The form is located at registirationform.jsp.

The view layer:

public class RegistirationServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {

        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");

        try {
            UserRegistirationService userRegistirationService
                    = new UserRegistirationService(new AppUserAccessObject(new DatabaseConnectionImpl()));

            String username = httpServletRequest.getParameter("username");
            String password = httpServletRequest.getParameter("password");
            String email = httpServletRequest.getParameter("email");

            if(username.equals("")
                    || password.equals("")
                        || email.equals("")){
                List<String> errors = new ArrayList<String>();
                errors.add("Can you make sure you fill all the fields?");
                httpServletRequest.setAttribute("errors",errors);

                if(!username.equals("")){
                    httpServletRequest.setAttribute("username",username);
                }

                if(!email.equals("")){
                    httpServletRequest.setAttribute("email",email);
                }

                httpServletRequest.getRequestDispatcher("/registirationform.jsp").forward(httpServletRequest, httpServletResponse);
            }

            else {
                userRegistirationService.registerAppUser(username, password, email);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            List<String> errors = new ArrayList<String>();
            errors.add("Registiration was not successful. Maybe username/email was already taken?");
            httpServletRequest.setAttribute("errors",errors);
            httpServletRequest.getRequestDispatcher("/registirationform.jsp").forward(httpServletRequest, httpServletResponse);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

and the service layer:

public class UserRegistirationService {

    private AppUserAccessObject appUserAccessObject;

    public UserRegistirationService(AppUserAccessObject appUserAccessObject) {
        this.appUserAccessObject = appUserAccessObject;
    }

    public void registerAppUser(String username, String password, String email) throws SQLException {
        appUserAccessObject.insertUser(username, password, email);
    }
}

and the db layer:

public class AppUserAccessObject extends DataAccessObjectImpl implements DataAccessObject {

    public AppUserAccessObject(DatabaseConnectionImpl databaseConnection)
            throws IOException, SQLException, ClassNotFoundException {
        super(databaseConnection);
        setTableName("app_user");
    }

    public void insertUser(String username, String email, String password) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + tableName + "(username,email,password) VALUES(?,?,?)");
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, email);
        preparedStatement.setString(3, password);
        preparedStatement.execute();
    }

}

Is all the code at correct layers?


texts: Detecting properly nested parenthesis using functional programming

texts:
So I have this code that is my attempt at a coding test from Codility. While my code produces correct results according to the requirements, (which unfortunately are copyrighted so I don't think I can reproduce them here), but I feel like it could be better organized, and in some places use a more functional approach to solving the problem.

So the basic idea is that it tests if the string if its properly nested parenthesis, or can be split into 2 halves which are properly nested.

let rec isNested (s : System.String) =
    let s = s.ToCharArray()
    let s = List.ofArray s
    match s with
    | [] -> true //if its empty then its properly nested
    | _ ->
        match s.Length % 2 with
        //if its even split the list in to 2 halves and test them
        | 0 -> //test form VW

            let len = s.Length
            let half = len / 2
            let mutable firsthalf = []
            let mutable secondhalf = []
            for i in 0..half - 1 do
                firsthalf <- s.[i] :: firsthalf
            for i in half..len - 1 do
                secondhalf <- s.[i] :: secondhalf
            firsthalf <- List.rev firsthalf
            secondhalf <- List.rev secondhalf
            let VWtest =
                isNested (new string(Array.ofList (firsthalf))) && isNested (new string(Array.ofList (secondhalf)))
            match VWtest with
            | true -> true
            | false ->
                match (s.[0], s.[s.Length - 1]) with
                | ('(', ')') ->
                  //remove the first and last elements
                    let sublist =
                        s.Tail
                        |> List.rev
                        |> List.tail
                        |> List.rev
                    isNested (new string(Array.ofList (sublist)))
                | _ -> false
        | _ -> false //not a string with an even number of chars therefore can't be properly nested

let test = isNested >> Console.WriteLine
//let expect (b : bool) = Console.WriteLine(" expected ", b)
test "()"     // expect true
test ")("     // expect false
test "(())"   // expect true
test "()()"   // expect true
test "()(()"  // expect false
test "(()())" // expect true


texts:
everyone!I have created a bit ugly looking Tic Tac Toe console game using Java. I'm learning how to code and I would love to hear some comments about my code. Because it's quite streatforward, I'm not using classes and objects ( my assignment was not to use any ). Thank you in advance!
package com.company;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static Scanner scan = new Scanner(System.in);

    public static char[][] table = {
        {'1', '2', '3'},
        {'4', '5', '6'},
        {'7', '8', '9'}
    };

    public static ArrayList<Character> picksTillNow = new ArrayList<Character>();
    public static char playerOne = ' ';
    public static char playerTwo = ' ';

    public static void main(String[] args) {

    for(char i = '1'; i <= '9'; i++){
        picksTillNow.add(i);
    }

    printTable();

    while (true){
        playerOneChoice();
        endGame();
        playerTwoChoice();
        endGame();
    }
}

/**
 * Prints the table with no players choices made ( 1 - 9 )
 */
public static void printTable() {

    for (int i = 0; i < table.length; i++) {
        for (int j = 0; j < table[i].length; j++) {
            System.out.print(table[i][j] + " ");
        }
        if (table[i][2] != 9) {
            System.out.println();
        }
    }
}

/**
 * Prints the table with the players choice included
 * @param player - player 1 or player 2
 * @param choice - char from 1 - 9
 */
public static void printTable(int player, char choice){

    for (int i = 0; i < table.length ; i++) {
        for (int j = 0; j < table[i].length; j++) {
            if(choice == table[i][j] && player == 1){
                //X
                table[i][j] = 'X';
            }else if(choice == table[i][j] && player == 2){
                //O
                table[i][j] = 'O';
            }
            System.out.print(table[i][j] + " ");
        }
        if(table[i][2] != 9){
            System.out.println();
        }
    }
}

/**
 * Asks for player one choice method and prints the table, checks if that position has been chosen
 */
public static void playerOneChoice(){
    System.out.print("Играч 1: ");
    playerOne = scan.next().charAt(0);
    if(picksTillNow.contains(playerOne)){
        picksTillNow.remove(picksTillNow.indexOf(playerOne));
        printTable(1, playerOne);
    }else{
        playerOneChoice();
    }
}

/**
 * Asks for player one choice method and prints the table, checks if that position has been chosen
 */
public static void playerTwoChoice(){
    System.out.print("Играч 2: ");
    playerTwo = scan.next().charAt(0);
    if(picksTillNow.contains(playerTwo)){
        picksTillNow.remove(picksTillNow.indexOf(playerTwo));
        printTable(2, playerTwo);
    }else{
        playerTwoChoice();
    }
}

/**
 * Checks for a winner. If yes - exits program
 */
public static void endGame(){
    for(int i = 0; i < table.length; i++){
        if(table[i][0] == table[i][1] && table[i][1] == table[i][2] && table[0][i] != 'О'){
            System.out.println("Победа!");
            System.exit(0);
        }
    }

    for(int j = 0; j < table.length; j++){
        if(table[0][j] == table[1][j] && table[1][j] == table[2][j] && table[j][0] != 'O'){
            System.out.println("Победа!");
            System.exit(0);
        }
    }

    if(table[0][0] == table[1][1] && table[1][1] == table[2][2] && table[0][0] != 'O'){
        System.out.println("Победа!");
        System.exit(0);
    }

    if(table[0][2] == table[1][1] && table[1][1] == table[2][0] && table[0][2] != 'O'){
        System.out.println("Победа!");
        System.exit(0);
    }

    if(picksTillNow.isEmpty()) System.exit(0);
 }
}


texts: str_replace vs array_map & trim on URL segments

texts:
Are there any advantages on using array_map & trim vs using simple str_replace? The input for both is an array of matched URL segments. I find it nice to be able to provide extra logic when using array_map but seems to be ~2 times slower. I did some trivial benchmarking

for ($i = 0; $i < 10000; $i ++) {
    array_map(function($argument) {
        return trim($argument, '/');
    }, array_slice($match, 1));
}

$end_time = microtime(TRUE);

echo $end_time - $start_time;

echo "<br/>";

$start_time = microtime(TRUE);

for ($i = 0; $i < 10000; $i ++) {
    str_replace('/', '', array_slice($match, 1));
}

$end_time = microtime(TRUE);

echo $end_time - $start_time;

Outputs:

0.0675988197327
0.0296301841736


texts: Game where you guess whether an article is from theOnion or notTheOnion

texts:
How can I make my code better?

function generateRandNum(min, max) {
    minimum = Math.ceil(min);
    maximum = Math.floor(max);
    return Math.floor(Math.random() * (maximum - minimum)) + minimum;
}

function generateNewPost(json_data) {
    var rand_num = generateRandNum(0, json_data.length);
    console.log("generateNew length: ", json_data.length);
    var rand_post = json_data[rand_num];
    return rand_post;
}

var post_title = document.getElementById("post-title");
var onion_button = document.getElementById("onion-chosen");
var not_onion_button = document.getElementById("not-onion-chosen");
var score_display = document.getElementById("score");

var req = new XMLHttpRequest();
var json_url = "https://api.myjson.com/bins/s474n";
var score = 0;

req.open('GET', json_url);
req.onload = function() {

    if (req.status === 200) {
        var json_data = JSON.parse(req.responseText);
        var rand_post = generateNewPost(json_data);

        post_title.innerHTML = rand_post.content;
        score_display.innerHTML = score;

        onion_button.onclick = function() {
            if (rand_post.sub === "theonion") {
                score++;
                score_display.innerHTML = score;
            } else {
                score--;
                score_display.innerHTML = score;
            }

            // update title
            rand_post = generateNewPost(json_data);
            var index = json_data.indexOf(rand_post);

            console.log("Index: ", index);
            console.log("Length of json_data: ", json_data.length);
            json_data.splice(index, 1);
            console.log("Length of json_data after splice: ", json_data.length);

            post_title.innerHTML = rand_post.content;

        }

        not_onion_button.onclick = function() {
            if (rand_post.sub === "nottheonion") {
                score++;
                score_display.innerHTML = score;
            } else {
                score--;
                score_display.innerHTML = score;
            }

            // update title
            rand_post = generateNewPost(json_data);
            var index = json_data.indexOf(rand_post);

            console.log("Index: ", index);
            console.log("Length of json_data: ", json_data.length);
            json_data.splice(index, 1);
            console.log("Length of json_data after splice: ", json_data.length);

            post_title.innerHTML = rand_post.content;
        }

    } else {
        console.log("Error");
    }
};

req.send();


texts:
I started practicing in web-scraping few days ago. I made this code to extract data from a wikipedia page. There are several tables that classify mountains based on their height. However there is a problem with the size of the matrices. Some of them contain 5 columns while others 4. So I made this algorithm to extract all the names and the attributes of the mountains into separate lists. My approach was to create a length list that contains the number of
<td> within the <tr> tags. The algorithm finds which table contains four columns and fills the column in excess (in the case of 5 columns) with NONE. However, I believe that there is a more efficient and more pythonic way to do it especially in the part where I use the find.next() function repedetly.  Any suggestions are welcomed.

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL="https://en.wikipedia.org/wiki/List_of_mountains_by_elevation"
content=requests.get(URL).content

soup=BeautifulSoup(content,'html.parser')

all_tables=soup.find_all("table",{"class":["sortable", "plainrowheaders"]})

mountain_names=[]
metres_KM=[]
metres_FT=[]
range_Mnt=[]
location=[]

lengths=[]

for table in range(len(all_tables)):

  x=all_tables[table].find("tr").find_next("tr")
  y=x.find_all("td")
  lengths.append(len(y))

  for row in all_tables[table].find_all("tr"):

        try:
            mountain_names.append(row.find("td").text)
            metres_KM.append(row.find("td").find_next("td").text)
            metres_FT.append(row.find("td").find_next("td").find_next("td").text)
            if lengths[table]==5:
                range_Mnt.append(row.find("td").find_next("td").find_next("td").find_next("td").text)
            else:
                range_Mnt.append(None)
            location.append(row.find("td").find_next("td").find_next("td").find_next("td").find_next("td").text)
        except:
            pass


texts: jQuery Toggle Between Functions Fn1 Fn2 Fn3 On Click

texts:
Is there a better way of toggling between different functions, on click events ? Something maybe that use "on" "off" methods or simpler alternative ?

(function($) {
        $.fn.clickToggle = function(func1, func2, func3) {
            var funcs = [func1, func2, func3];
            this.data('toggleclicked', 0);
            this.click(function() {
                var data = $(this).data();
                var tc = data.toggleclicked;
                $.proxy(funcs[tc], this)();
                data.toggleclicked = (tc + 1) % 3;
            });
            return this;
        };
    }(jQuery));

    $('#b1').clickToggle(
        function() {alert('First handler');},
        function() {alert('Second handler');},
        function() {alert('Third handler');}
        );


texts: Linked list operations for a competition

texts:
After checking some incoming coding competitions, I feel I may want to develop a little bit more on my coding skills and style using some basic algorithms/data structures.

The following two pieces of Java code are about some LinkedList operation. Can you take a quick look and give me some feedback about the accuracy, efficiency, better solution, or code style?

The Java code includes some simple comments, test cases, and it is tested at Java 6 and reviewed by myself.

/*
* purpose of program - for a singly linkedList, switch the elements at odd number positions with
* the ones at even number positions
*
input sample : 1>2>3>4>5; expecting output: 2>1>4>3>5;
input sample : 1>2>3>4; expecting output: 2>1>4>3;

*/

ListTwister.java

package com.algo;

/*
 * purpose of program - for a singly linkedList, switch the elements at odd number positions with
 * the ones at even number positions
 *
input sample : 1>2>3>4>5; expecting output: 2>1>4>3>5;
input sample : 1>2>3>4;   expecting output: 2>1>4>3;

 */

public class ListTwister {

    /* for odd sequence element (array index = 0, 2, etc), store a "branch head", store prev node, and move to next;
    for even sequence element (array index = 1, 3, etc), store the "nextNode", twist current and prev node, link the "branch head" to the currentNode, and link the "prev node" to cached "nextNode"
     */
    public static Node twist(Node head) {
        Node current = head, newHead = null, branchHead = null, tempNext = null, prev = null ;
        int index = 0;

        if (head!=null & head.next!=null ) {
            newHead = head.next;
        }
        else {
            newHead = head;
        }

        while (current != null) {
            //odd sequence
            if (index % 2 == 0) {
                branchHead  = prev;
                prev = current;
                current = current.next;
            }
            //even sequence
            else {
                tempNext = current.next;
                current.next = prev;
                if (branchHead != null ) {
                    branchHead.next = current;
                }
                prev.next = tempNext;
                current = tempNext;
            }

            index ++;
        } // end of while

        return newHead;

    } // end of twist()

    public static void main (String args[]) {
        Node head_list1 = new Node(1, null);
        Node node2_list1 = new Node(2, null);
        Node node3_list1 = new Node(3, null);
        Node node4_list1 = new Node(4, null);
        Node node5_list1 = new Node(5, null);

        head_list1.add(node2_list1 );
        node2_list1.add(node3_list1 );
        node3_list1.add(node4_list1 );
        node4_list1.add(node5_list1 );

        Node head_list2 = new Node(1, null);
        Node node2_list2 = new Node(2, null);
        Node node3_list2 = new Node(3, null);
        Node node4_list2 = new Node(4, null);

        head_list2.add(node2_list2 );
        node2_list2.add(node3_list2 );
        node3_list2.add(node4_list2 );

        head_list1.print();
        //expect to output : 2->1->4->3->5->END.
        twist(head_list1).print();

        head_list2.print();
        //expect to output : 2->1->4->3->END.
        twist(head_list2).print();

    } // end of main()

} // end of class

Node.java

package com.algo;

/*
Node for singly LinkedList;
 */

public class Node {
    public int value;
    public Node next;

    public Node (int value, Node next) {
        this.value = value;
        this.next = next;
    }

    public void add(Node node) {
        this.next = node;
    }

    public void print() {
        Node current = this;
        while (current!=null ) {
            System.out.print(current.value + "->");
            current = current.next;
        }
        if (current==null) {
            System.out.println("END.");
        }
    }
} // end of class


texts:
A friend of mine and I recently started a project and at this moment we are writing a common library. He began writing an N-ary three and he is convinced that he has the best design with which I am not agree.

I want to convince him, that his design of the N-ary Tree is very bad, and with this design we will face problems. Due to lack of experience in complex projects from my side -- I can't convince him with my arguments.

Here is the current design and implementation:

template <typename T>
class Tree {
private:
    T data;
    vector< Tree<T> > successors;

public:
    Tree(T x) {
      data = x;
    }

    T root() {
        return data;
    }
    vector< Tree<T> > succ() {
        return successors;
    }
    void addChild(Tree<T> t) {
        successors.push_back(t);
    }
    void member(T element) {
        if (element == data)
            return true;
        for (int i = 0; i < successors.size(); i++) {
            if(successors[i].member(element)) {
                return true;
            }
        }
        return false;
    }
    void fromRightParentToLeft() {
        if (successors.empty()) {
            cout << data << "\n";
            return;
        }
        if (successors.size() == 1) {
            successors[0].fromRightParentToLeft();
            cout << data << "\n";
        }
        else {
          for (int i = succ().size(); i > 1; i--) {
            succ()[i-1].fromRightParentToLeft();
          }

          cout << data << "\n";
          succ()[0].fromRightParentToLeft();
        }
    }
};

So far I can see few problems:

We will face problem when he will implement a method for node deletion, because it is somehow wrong a node to have the ability to delete itself.
He traverses the tree in a inorder-ish manner, which is pointless when dealing with general N-ary trees.

Can someone point other potential traps with this approach?

The tree must meet the following requirements:

Inteface: node addition, node deletion, search for a particular node, basic tree traversal.
Other: It should be: easily maintainable, with fast performance.

In the general case the tree will have ~10k nodes, which will contain integers.


texts: Confirm code is correct - crossover methods in Java

texts:
I did this code for somebody but need it to be double checked before I pass it onto them. Code seems fine but I need someone to confirm I have coded the crossover methods correctly.

Would be great if somebody that is familiar with genetic algorithms and crossover methods, could confirm that I have the correct logic and code behind each crossover method.

 //one crossover point is selected, string from beginning of chromosome to the
 //crossover point is copied from one parent, the rest is copied from the second parent

 // One-point crossover

public void onePointCrossover(Individual indi) {
    if (SGA.rand.nextDouble() < pc) {
        // choose the crossover point
        int xoverpoint = SGA.rand.nextInt(length);

        int tmp;
        for (int i=xoverpoint; i<length; i++){
            tmp = chromosome[i];
            chromosome[i] = indi.chromosome[i];
            indi.chromosome[i] = tmp;
        }
    }
}
//two crossover point are selected, binary string from beginning of chromosome to
//the first crossover point is copied from one parent, the part from
// the first to the second crossover point is copied from the second parent
// and the rest is copied from the first parent

// Two-point crossover
    public void twoPointCrossover(Individual indi) {
        if (SGA.rand.nextDouble() < pc) {
            // choose the crossover point
            int xoverpoint = SGA.rand.nextInt(length);
            int xoverpoint2 = SGA.rand.nextInt(length);

            int tmp;
            //swap
            if (xoverpoint > xoverpoint2){
                tmp = xoverpoint;
                xoverpoint = xoverpoint2;
                xoverpoint2 = tmp;
            }

            for (int i=xoverpoint; i<xoverpoint2; i++){
                tmp = chromosome[i];
                chromosome[i] = indi.chromosome[i];
                indi.chromosome[i] = tmp;
            }
        }
    }

    //  For each gene, create a random number in [0,1]. If
    // the number is less than 0.5, swap the gene values in
    // the parents for this gene; otherwise, no swapping

// Uniform Crossover
    public void UniformCrossover(Individual indi) {
        if (SGA.rand.nextDouble() < pc) {
        for (int i= 1; i<length; i++){
            boolean tmp =  SGA.rand.nextFloat() < 0.5;
            if(tmp){
                chromosome[i] = indi.chromosome[i];

            }
            }

        }

Parent 1 = chromosome    Parent 2= indi.chromosome

I am turning the parents into children inplace.


texts: Exposing a directive's computed variable

texts:
I have a directive called meetingList with its own isolated scope that receives a list of meetings and displays the filtered items based on some criteria. The controller for this directive holds two variables the meetingList and the filteredMeetingList. The scope where this directive is created needs to know how many items the directive is displaying (filteredMeetingList.length) in order to do something (outside the directive). I am currently exposing this variable using two way databinding on the isolated scope to send the variable outside.

Is there a better way of doing this? is there some kind of standard for this?

I set up a simple Plunker to illustrate the scenario.

HTML

      <meeting-list meeting-list="appCtrl.meetingList" filtered-meetings-count="appCtr.filteredMeetingsCount"></meeting-list>
      Total meetings {{appCtrl.meetingList.length}}

      Meetings being displayed by the meetingList directive {{appCtr.filteredMeetingsCount}}

Javascript

  var app = angular.module('test', []);

  app.directive('meetingList', function(){
    return{
      restrict: 'E',
      scope: {
        meetingList: '=',
        //this is the variable that I use to expose the length of the filtered meetings to the external scope
        filteredMeetingsCount: '='
      },
      controller: function($scope){
        var self = this;
        var meetingList = $scope.meetingList;
        var filteredMeetingList = $scope.filteredMeetingList = [];

        filterMeetings();
        //Here I set the value after filtering
        $scope.filteredMeetingsCount = filteredMeetingList.length;
        function filterMeetings()
        {
          filteredMeetingList.push(meetingList[1]);
          filteredMeetingList.push(meetingList[2]);
        }

      },

      template: '
 {{meeting}}
'
    }
  });

  app.controller('AppCtrl', function($scope){
    var self = this;
    self.meetingList = ["meeting1", "meeting2", "meeting3"];
  });


texts: What if any design issues are there in this method of loading configuration data from YAML in Ruby?

texts:
I am actually pretty excited about this approach, but for sanity's sake I wanted to hear some thoughts on others on my strategy here. My basic goal is to parse a YAML file and recursively create module constants using eval. The core business logic is here:

#
#   configure application based on an easily-managed .yml file -- use 'eval'
#   to generate constants based on the structure of the hash we get from the yaml.
#   most of the business logic for recursively parsing a hash and creating module
#   constants basically just involves tracking module names properly.
#
def parse_and_recursively_create_constants!(hash, module_context = [])
  hash.each do |key, value|
    if value.is_a? Hash
      module_name = convert_string_to_camel_case(key)
      context = module_context.dup << module_name
      parse_and_recursively_create_constants! hash[key], context
    else
      value_is_a_module = false

      if value.is_a? String
        if value.include? "::"
          value_is_a_module = true
        else
          value = "\"#{value}\""
        end
      end

      if value_is_a_module
        # explicitly build out this module (since it doesn't exist) so that we can talk about it
        expression = value.split('::').map { |module_name| "module #{module_name}; "}.join(' ')
        value.split('::').count.times { expression << "end; "}
        eval(expression, $__global_scope)
      end

      # define the given constant
      depth = module_context.count
      expr = module_context.map { |module_name| "module #{module_name}; " }.join(" ")
      expr << "#{key.upcase} = #{value}; "
      depth.times { expr << "end; "}
      expr = "module #{@project_name}; #{expr}; end"
      eval(expr, $__global_scope)
    end
  end

Note I am having to bind the default scope to a global $__global_scope which occurs just before the class definition containing this method. I was wondering if there were some cleaner way of handling that, but either way the behavior certainly is what I want it to be. Here's an example configuration file:

key: value
numeric_data: 3.221
sample_module:
    some_key: another value
key_should_be_module: I::Am::A::Module

And the associated test case:

configure! "Sample", "spec/resources/sample.yml"

Sample::KEY.should == 'value'
Sample::NUMERIC_DATA.should == 3.221
Sample::SampleModule::SOME_KEY.should == 'another value'
Sample::KEY_SHOULD_BE_MODULE.should be_a_kind_of(Module)
Sample::KEY_SHOULD_BE_MODULE.should == I::Am::A::Module

I have released this as a gem, and if you'd like more context the full source is on Github here.


texts:
I was trying to solve the following Programming Praxis problem:

  Write a function that takes a string and determines if the delimiters
  in the string are balanced. The pairs of delimiters are (), [], {},
  and <>, and delimiters may be nested. In addition, determine that
  string delimiters ‘ and ” are properly matched; other delimiters lose
  their magical delimiter-ness property within quoted strings. Any
  delimiter is escaped if it follows a backslash.

Here's my attempt to solve the problem:

import java.util.*;
public class BalancedDelimiters{
    private Map<Character,Integer> delimitMap;
    private Map<Character,Character> charMap;
    public BalancedDelimiters(){
         delimitMap = new LinkedHashMap<Character,Integer>();
         charMap = new LinkedHashMap<Character,Character>();
         initDelimitDics(delimitMap);
         initCharMap(charMap);
    }

    private void initCharMap(Map<Character,Character> charMap){
        charMap.put('(',')');
        charMap.put(')','(');
        charMap.put('[',']');
        charMap.put(']','[');
        charMap.put('{','}');
        charMap.put('}','{');
        charMap.put('<','>');
        charMap.put('>','<');
    }

    private void initDelimitDics(Map<Character,Integer> delimitMap){
        delimitMap.put('(',0);
        delimitMap.put(')',0);
        delimitMap.put('[',0);
        delimitMap.put('{',0);
        delimitMap.put('<',0);
        delimitMap.put('>',0);
        delimitMap.put(']',0);
        delimitMap.put('}',0);
    }

    public boolean checkForBalance(String extractedString){
        int balancedIndicator = 0;
        char[] charArr = extractedString.toCharArray();
        for(char c:charArr){
            if(delimitMap.containsKey(c)){
                delimitMap.put(c,delimitMap.get(c)+1);
            }
        }
        for(Map.Entry<Character,Integer> entry:delimitMap.entrySet()){
            System.out.println("Entry Key:"+entry.getKey()+"Entry value:"+entry.getValue());
            System.out.println("Complementary delimiter:"+charMap.get(entry.getKey()));
            if(delimitMap.get(charMap.get(entry.getKey())) != entry.getValue())
                return false;
        }

        return true;
    }

}

Can somebody review my code and let me know how I would be able to improve this snippet?


texts:
Goal: To create a countdown to our next available live stream.

Details: We live stream six times a week all (PST).
1. Sunday at 8:00 a.m.
2. Sunday at 10:00 a.m.
3. Sunday at 12:00 p.m.
4. Sunday at 6:30 p.m.
5. Wednesday at 7:00 p.m.
6. Saturday at 10:00 a.m.

My approach: I check what day it is and what time it is then create the countdown to the next stream.

I'm sure what I have done can be cleaned up and improved, so tell me how.

<?php
// Countdown Stuff
$year = date(Y);
$month = date(m);
$month_day = date(d);
$day = date(w);
$hour = date(G);
$min = date(i);
$addDay = 0;

// It's Sunday
if ( $day == 0 ) {
    if ( $hour < 8 ) {
       $hour = 8;
       $min = 0;
    }
    else if ( $hour < 10 ) {
       $hour = 10;
       $min = 0;
    }
    else if ( $hour < 12 ) {
       $hour = 12;
       $min = 0;
    }
    else if ( $hour <= 18 && $min < 30 ) {
       $hour = 18;
        $min = 30;
    }
    else {
     $addDay = 3;
       $hour = 19;
       $min = 0;
    }
}
// It's Monday
else if ( $day == 1 ) {
    $addDay = 2;
      $hour = 19;
      $min = 0;
}
// It's Tuesday
else if ( $day == 2 ) {
    $addDay = 1;
      $hour = 19;
      $min = 0;
}
// It's Wednesday
else if ( $day == 3) {

    if ( $hour < 19 ) {
       $hour = 19;
       $min = 0;
    } else {
     $addDay = 3;
       $hour = 10;
       $min = 0;
    }
}
// It's Thursday
else if ( $day == 4 ) {
    $addDay = 2;
      $hour = 10;
      $min = 0;
}
// It's Friday
else if ( $day == 5 ) {
    $addDay = 1;
      $hour = 10;
      $min = 0;
}
// All that's left is Saturday
else {

    if ( $hour < 10 ) {
       $hour = 10;
       $min = 0;
    } else {
     $addDay = 1;
       $hour = 8;
       $min = 0;
    }
}

$build_date = $year . '-' . $month . '-' . $month_day . ' ' . $hour . ':' . $min . ':00';
$date = new DateTime($build_date);

if ( $addDay ) {
    $date->modify("+$addDay day");
}

$date = strtotime($date->format("Y-m-d G:i:s"));
$now = strtotime("now");
$count = $date - $now;
?>

<script type="text/javascript">
var myTime = <?=$count?>;
$('#countdown').countdown({ until: myTime});
</script>


texts: Decide if the sum of three numbers is even or odd

texts:
Exercise from an Assembly course I'm enrolled into:

  Write a program that takes three numbers x,y,z as input, and returns:

  0 if (x+y+z) is even.
  1 if (x+y+z) is odd.

  (Note that here + means arithmetic addition). Do it without actually
  adding the numbers. HINT: Use the XOR instruction.

Full exercise-sheet here: GitHub

Here's the code I've written. Please mind the comments I've added for to explain my ideas.

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:

    call    read_hex              ; Provided by the teacher. Reads a hexadecimal number from stdin.
    mov     ebx,    eax
    call    read_hex
    add     ebx,    eax
    call    read_hex
    add     ebx,    eax

    mov     eax,    ebx           ; Move the sum of the three given numbers into eax.
    xor     eax,    0x1           ; If the number is odd then the lowest bit becomes 0. If the number is even then the lowest bit becomes 1.
    ror     eax,    0x1           ; Rotate the lowest bit out of the register. So that the carry-flag gets a new state.
    jc      evenNumber            ; jc == Jump if the carry-flag has become 1. Means the last bit has been a 1, which in turn means that the number is even.
    mov     eax,    0x1           ; Otherwise just write 0 into eax, which signals an odd number. And prints this to stdout.
    jmp     print_result

evenNumber:
    mov     eax,    0x0

print_result:
    call    print_eax_binary    ; Provided by the teacher. Prints a binary number to stdout.

        ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'

I'm not completely sure if I have gotten the exercise-task correctly. But let's assume that the entered three numbers have to be summed up and that one has to use xor in some way.

How could I improve my solution? Is there a better solution?


texts: Error handling best practices using a custom error handling module

texts:
I am trying to learn how to effectively use error handling in my code. To do this, I have created a class inside main.py which reads the value of a specified curve at a specified date.

I then have my file data_reader.py, which reads in the specified curve (into a Pandas dataframe) from a CSV file. The index of this curve is a date.

Finally, I have my error handling file, error_handler.py.

main.py

from data_reader import read_curve
from datetime import datetime, timedelta
import sys
from error_handler import CustomException, CurveValueNotFoundError

def get_curve_value(curve_name, lookup_date):

    lookup_date = datetime.strptime(lookup_date, '%d/%m/%Y')

    curve_value = None
    tries_remaining = 5

    while curve_value is None:
        try:
            curve_value = read_curve(curve_name, lookup_date, tries_remaining)
            return curve_value

        except CurveValueNotFoundError as e:
            e.return_to_user()
            tries_remaining -= 1
            lookup_date -= timedelta(days=1)

        except CustomException as e:
            e.return_to_user()
            if e.fatal:
                sys.exit(1)

if __name__ == '__main__':
    print('Curve value: {}'.format(get_curve_value('RPI2019', '30/06/2019')))

data_reader.py

import pandas as pd
import pathlib
import error_handler

def read_curve(curve_name, lookup_value, tries_remaining):
    try:
        curve = pd.read_csv('{}/curves/{}.csv'.format(str(pathlib.Path().absolute()), curve_name), index_col='Date', parse_dates=True)
        val = float(curve.loc[lookup_value])
        return val
    except pd.errors.EmptyDataError as e:
        raise error_handler.NoCurveValuesError(curve_name, __name__, fatal=True)
    except FileNotFoundError:
        raise error_handler.CurveNotFoundError(curve_name, __name__, fatal=True)
    except KeyError:
        raise error_handler.CurveValueNotFoundError(curve_name, lookup_value, tries_remaining, __name__)
    except Exception as e:
        raise error_handler.CustomException(e, __name__, fatal=True)

error_handler.py

class CustomException(Exception):
    def __init__(self, message, raised_from, fatal):
        self.message = message
        self.raised_from = raised_from
        self.fatal = fatal

    def return_to_user(self):
        print("The following error occurred in the module {}.py: {}".format(self.raised_from, self.message))

class CurveNotFoundError(CustomException):
    def __init__(self, curve_name, raised_from, fatal=True):
        message = "The curve {} could not be found.".format(curve_name)
        CustomException.__init__(self, message, raised_from, fatal)

class NoCurveValuesError(CustomException):
    def __init__(self, curve_name, raised_from, fatal=True):
        message = "The curve {} was successfully loaded but contains no data.".format(curve_name)
        CustomException.__init__(self, message, raised_from, fatal)

class CurveValueNotFoundError(CustomException):
    def __init__(self, curve_name, lookup_value, tries_remaining, raised_from, fatal=False):
        message = "The curve {} is not defined for the lookup '{}'. Tries remaining: {}.".format(curve_name, lookup_value, tries_remaining)
        CustomException.__init__(self, message, raised_from, fatal)
        if tries_remaining == 0:
            raise CustomException("Too many missing values", __name__, fatal=True)

Errors that should terminate execution include:

If the CSV file containing the user-specified curve cannot be found
If the CSV file for the curve is empty
If, after 5 tries (changing the lookup date by -1 days per try), no curve values can be found

Is my approach towards error handling (including my handling of fatal / non-fatal errors) a good approach? How can I improve this?


texts:
I see that my code smells.  The first file is a controller, and createAction.  But I don't know where to delegate this.

BookController.php - Whole controller class

So this is most 'smelly' code to me:

public function createAction(Request $request) {
    $user = $this->get('security.context')->getToken()->getUser();

    $book = new Book();

    $form = $this->createForm(new BookType($user->getId()), $book);

    $form->handleRequest($request);

    if($form->isValid()) {
        $book->upload();
        $em = $this->getDoctrine()->getManager();
        $em->persist($book);
        $em->flush();

        $covers = $request->files->get('covers');
        foreach ($covers as $cover) {
            $coverObj = new BookCover();
            $coverObj->setFile($cover);
            $coverObj->setBook($book);
            $coverObj->upload();

            $em->persist($coverObj);
        }
        $em->flush();
        return $this->redirect($this->generateUrl('matiit_book_homepage'));
    }

    return $this->render('MatiitBookBundle:Book:new.html.twig', ['form' => $form->createView()]);
}

Rest of files:

new.html.twig
Book.php
BookType.php
BookCover.php

Uploading in entities is the second thing which bothers me.

It would be nice to know what is worth testing here - I have no experience with tests so it would be very useful for me.


texts:
I wrote a brute-force algorithm which shall find all possible combinations of ASCII-values that can sum up to a specific value (int hashval).

The algorithm is derived from a recursive algorithm that could print all binary numbers that are possible within a specific length characters. I modified it, so it now iterates over all ints between first and last, thus building all combinations there are. If the sum of the combination is equal to hashval, then the combination is saved in vector<vector<int[]>> combinations. When all possible combinations are found the content of combinations is printed into a file.

I already use some little tricks I learned for competitive programming, but the algorithm is still too slow. At the moment it is running for approximately 3 hours for no more than 13 characters, with no end in sight, file I/O hasn't even started yet. I know that its Big-O for runtime is horrible, no doubt. (if I get it right it is O(m^n) ).

I considered adding a check for n=1 since that would leave only one possibility for the last character, saving some recursive calls, but that would add another if to be called in every function call, either.

What more ways are there to improve the speed? Any improvements are not bound to C++, I will take a look at every programming language which might be more efficient in this case, though I guess there scarcely will be one.

The algorithm:

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <cstdio>

using namespace std;
using namespace std::chrono;

//values in decimal
int first = 32, last = 126, characters = 13, hashval = 1207;

vector<vector<int>> combinations;

void brute(int n, int it, vector<int> values) {
    if (n == 0) {
        int sum = 0;

        //sum up recent values
        for (int j = 0; j < characters; ++j) {
            sum += values[j];
        }
        //save values if matching to hash
        if (sum == hashval) {
            combinations.push_back(values);
        }
    } else {
        for (int i = first; i <= last; ++i) {
            values[it] = i;
            brute(n - 1, it + 1, values);
        }
    }
}

Printing the output to a file:

void printToFile(){
    freopen("fileContent.brute", "w", stdout);
    cout << "\n\nFound " << combinations.size() << " combinations." << endl;
    int counter = 0;
    for (auto combo = combinations.begin(); combo != combinations.end(); ++combo){
        for (int i = 0; i <  characters; ++i) {
            cout << (char) combinations.at(counter).at(i) << " ";
        }
        cout<< "\r\n";
        counter++;
    }
}

The main-method:

int main() {
    auto start = high_resolution_clock::now();
    //characters = 3, first = 0, last = 3, hashval = 6;
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    vector<int> values;

    for (int i = 0; i < characters; ++i) {
        values.push_back(first);
    }

    brute(characters, 0, values);

    printToFile();
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<seconds>(stop - start);
    cout << "Brute-forcing needed " << duration.count() << " seconds.\r\n";

    cout.flush();

    return 0;
}


texts:
Note: If you googled this by the title of this question, don't use this script unless you know what it is supposed to do.

This is a script in bash 3+ that I have used for long for preventing rm * and rm -rf * from accidentally invoked and removing important files by mistake. I put it in my ~/.bash_aliases.

alias rm='set -f;rm'
rm(){
    if [[ "$-" == *i* ]]
    then
        if [ "$1" = "*" ] || [ "$2" = "*" ] || [ "$1" = "./*" ] || [ "$2" = "./*" ]
        then
            echo "Abort: refusing to remove *, please go to the parent folder and do rm <folder_name>/*" 1>&2
            set +f
            return 1
        fi
    fi
    set +f
    /bin/rm -i $@
}

set +f

I would like to know whether there are any vulnerabilities and whether it can be improved.


texts:
I'm programming code with MySQLi prepared statements. I'm a beginner and just want to ask to experts if my code is correct.

function getPaymentMethodName( $id ) {
    global $mysqli;
    if ( $stmt = $mysqli->prepare( 'SELECT name FROM `payment_methods` WHERE id = ?' ) ) {
        if ( $stmt->bind_param( 'i', $id ) ) {
            if ( $stmt->execute() ) {
                $stmt->bind_result( $name);
                if ( $stmt->fetch() ) {
                    $stmt->close();
                    return $name;
                }
            }
        }
    }
    $stmt->close();
    return false;
}


texts:
I have written the following Bash script which includes an Nginx WordPress bootstrapper: A program establish WordPress apps fast on a Debian-Nginx environment.

It utilizes CertBot for HTTPS, SSHguard for protection from BFA (see Nginx conf), WP-CLI for creating a WP app dir and conf file fast, MySQL CLI to create a dbstack and a local function named rse to restart the server and giving proper permissions to the app dir.

#!/bin/bash
domain="$1" && test -z "$domain" && exit 2

environment() {
    read -sp "Please enter the app DB root password:      " dbrootp_1 && echo
    read -sp "Please enter the app DB root password again:" dbrootp_2 && echo
    if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched. Please try again." && exit 2 fi

    read -sp "Please enter the app DB user password:      " dbuserp_1 && echo
    read -sp "Please enter the app DB user password again:" dbuserp_2 && echo
    if [ "$dbuserp_1" != "$dbuserp_2" ]; then echo "Values unmatched. Please try again." && exit 2 fi
}
environment

wordpress() {
    rm -rf "$drt"/"$domain"/ 2>/dev/null
    wp core download --path="$drt"/"$domain"/ --allow-root
    wp config create --path="$drt"/"$domain"/ --dbname="$domain" --dbuser="$domain" --dbpass="$dbuserp" --dbhost="localhost" --allow-root
}
wordpress

nginx() {
    rm "$s_a/$domain.conf" 2>/dev/null
    rm "$s_e/$domain.conf" 2>/dev/null

    cat <<-EOF > "$s_a/$domain.conf"
        server {
            root ${drt}/${domain}/;
            server_name ${domain} www.${domain};
            location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {expires 365d;}
            location "/wp-login\.php" {access_log "/var/log/httpd/wordpress-logins.log";}
        }
    EOF

    ln -sf "$s_a"/"$domain".conf "$s_e"
    rse
}
nginx

certbot() {
    certbot --nginx -d "$domain" -d www."$domain"
    rse
}
certbot

database() {
    cat <<-EOF | mysql -u root -p"$dbrootp_1"
        DROP USER IF EXISTS "$domain"@"localhost";
        DROP database IF EXISTS "$domain";
        CREATE USER "$domain"@"localhost" IDENTIFIED BY "$dbuserp_1";
        CREATE DATABASE "$domain";
        GRANT ALL PRIVILEGES ON "$domain".* TO "$domain"@"localhost";
    EOF
}
database

finalize() {
    echo "Change http to http2 in your Nginx app conf and run rse"
}
finalize

Note

Before executing the script I declared in the end of $HOME/.bashrc:

drt="/var/www/html"
s_a="etc/nginx/sites-available"
s_e="etc/nginx/sites-enabled"


texts: integer log base 10 function without using java.lang.Math?

texts:
I am assigned to a task of creating a function int logBase10Estimate(int n) that returns the log of a number base 10. The answer is integer part only.(w/o using the Math class)

Is this okay?

static int logBase10Estimate(int n){
    int count = 0;
    for(int x = 10; ;x*=10){
        if(x < n){
            count+=1;
            System.out.println(x);
        }
        else if(x == n){
            count+=1;
            break;
        }
        else{
            break;
        }
    }
    return count;
}


texts:
I put together this code to for the Udacity cs101 exam. It passes the test, but I feel their must be a more elegant way to manage this problem. Some help from a module (like itertools).

Question 8: Longest Repetition

Define a procedure, longest_repetition, that takes as input a
 list, and returns the element in the list that has the most
 consecutive repetitions. If there are multiple elements that
 have the same number of longest repetitions, the result should
 be the one that appears first. If the input list is empty,
 it should return None.

def longest_repetition(alist):
    alist.reverse()
    largest = []
    contender = []
    if not alist:
        return None
    for element in alist:
        if element in contender:
            contender.append(element)
            if len(contender) >= len(largest):
                largest = contender
        else:
            contender = []
            contender.append(element)

    if not largest:
        return contender[0]
    else:
        return largest[0]

#For example,

print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])
# 3

print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd'])
# b

print longest_repetition([1,2,3,4,5])
# 1

print longest_repetition([])
# None


texts: error management when parsing multiple floats

texts:
I am writing a handler to render a GIF of a Lorentz attractor. I need to parse floating point numbers from the some querystrings attached to the GIF path. If any of them are bad, I need to log an error.

func lorenzHandler(w http.ResponseWriter, r *http.Request) {
    var e error
    rho := atof(r.FormValue("r"), &e)
    sigma := atof(r.FormValue("s"), &e)
    b := atof(r.FormValue("b"), &e)
    if e != nil {
        log.Printf("bad parameters: r=%s; s=%s; b=%s;\n", r.FormValue("r"), r.FormValue("s"), r.FormValue("b"))
    } else {
        // draw lorenz GIF with parameters rho, sigma and b
        // but until then...
        log.Println("yay!", rho, sigma, b)
    }
}

func atof(s string, e *error) float32 {
    if *e == nil {
        var x float64
        x, *e = strconv.ParseFloat(s, 32)
        return float32(x)
    }
    return 0
}

Is passing around an error, then cleaning it up, correct?