Function to format numbers with thousand separators and decimals I've wroted this function because I was getting trouble using toLocaleString() in google-apps-script, and after some refactorings I got to a working code:

function neat(numToFormat,prefThousands, prefDecimals) {

    var thousandSep = prefThousands == undefined ?  "." : prefThousands;

    var decimalSep = prefDecimals == undefined ?  "," : prefDecimals;

    function parseInput(numToFormat) {
        var isNumber = typeof(numToFormat) == 'number';
        var numberToFixed;
        if(isNumber){
            numberToFixed = numToFormat.toFixed(2);
        } else {
            //replacing "," for parseFloat precision
            if(numToFormat.indexOf(",") >-1){
                numToFormat = numToFormat.replace(",",".");
            }
          numberToFixed = parseFloat(numToFormat).toFixed(2);
        }
        return numberToFixed;
    }

    function placeThousands(wholesPart){
        /* To add thousands separators.
         * it iterates throught the
         * number in chunks of len 3.
         * adding a the setted prefered thousand separator.
         * just needed if wholesPart.length >=4
         *
         */
        var wholesLength = wholesPart.length;
        var wholesModulo = wholesLength % 3;
        //benefits from the mod equaling the slice end size needed
        //and if mod == 0 fstChunk = ""
        var fstChunk = wholesPart.slice(0,wholesModulo);
        var placed =wholesModulo !=0 ? fstChunk+thousandSep : fstChunk;
        for (var i=wholesModulo;i<wholesLength;i+=3) {
            var nextLoop = i+3;
            if(nextLoop<wholesLength) {
                var sliceBy = wholesPart.slice(i,nextLoop);
                placed += sliceBy +thousandSep;
            } else {
                sliceBy = wholesPart.slice(i,wholesLength);
                placed += sliceBy;
            }
        }
        return placed;
    }
    var numberToFixed = parseInput(numToFormat);
    var decimalPart = numberToFixed.slice(-3).replace('.',decimalSep);
    var wholesPart = numberToFixed.slice(0,(numberToFixed.length - 3));
    var needThousands = wholesPart.length >=4;
    var neat = needThousands ? placeThousands(wholesPart) + decimalPart : wholesPart + decimalPart;
    if(numberToFixed>= 9007199254740991){
        neat= "This number is too big, neatnumbers can't handle it";
    } else if(neat == "NaN") {
        neat= "neatnumbers only deals with numbers";
    }
    return neat;
}

It's restricted to 9007199254740991 because calling parseFloat() even on integers bigger than that is imprecise.

Speed is not an issue, I coded solo, so commenting is somewhat distressing since I'm afraid to restate the code.
But I'm open for criticizing on any aspects.

You can use default parameters to automatically assign a value if none is given.

function neat(numToFormat, thousandSep = ".", decimalSep = ",")

You should start by checking if the input is valid, instead of doing it at the end. It would also be better to throw an error, since it's not easy to tell from the result if the formatting succeeded or not.

if (typeof numToFormat == 'number') {
  if(Number.isNaN(numToFormat) || !Number.isFinite(numToFormat)) {
    throw new Error("Invalid number");
  }
}
else if(typeof numToFormat == 'string') {
  if(!/^\d+((,|\.)\d+)?$/.test(numToFormat)) {
    throw new Error("Invalid string");
  }
}
else {
  throw new Error("Can only use number or string");
}

It's not parseFloat() which is imprecise, but the numbers themselves. JavaScript uses IEEE 754, which is 64-bit floating point numbers, with 53 bits used for precision. The number you are testing against is the highest safe integer, which is 2^53-1 and can be gotten from Number.MAX_SAFE_INTEGER. But your result could still be imprecise with numbers this large, since you are not only using integers but also 2 decimal places.

With string inputs you can get around this by not converting it to a number at all. Since the result is also a string, you can keep it a string all the way through. For number inputs you can only work with the precision you've been given. Any imprecision should be handled by the code calling this function beforehand.

You will need to update your parseInput function to avoid parseFloat. Just cut of any extra decimals, or add them if they are missing. If you want to round the number it gets a bit harder, but it's still possible.

Your placeThousands function can be done a little simpler. There are several ways to do it, but I would cut the string into an array of chunks and then join them together. I would also make it easier to change the chunk size by putting it in a variable.

const chunkSize = 3;
let chunks = [];
let start = wholesPart.length % chunkSize;
if(start != 0) {
    chunks.push(wholesPart.slice(0, start));
}
for(let i = start; i < wholesPart.length; i+= chunkSize) {
    chunks.push(wholesPart.slice(i, i + chunkSize));
}
return chunks.join(thousandSep)

When I saw fstChunk the first thing I thought was 'fast chunk', but I guess it's supposed to be 'first chunk'. There is no reason make things less clear just to save 2 characters.

You don't need to check the length of wholesPart, placeThousands can handle short strings.

return placeThousands(wholesPart) + decimalPart;


Design Strategy of CSV Parser I wanted to review my design strategy for CSV parser.
I have 4 CSV files, which have different layouts as shown below.
Each row of a CSV file will be mapped to a class. For example, if CSV_FILE_A has 10 rows, a list contains 10 objects of ObjA will be returned after calling parser function. For CSV_FILE_B of 5 entries, a list of 5 ObjB will be returned.

CSV_FILE_A: LONG, STR, STR
CSV_FILE_B: LONG, LONG
CSV_FILE_C: LONG, LONG, STR, LONG
CSV_FILE_D: LONG, LONG, LONG

I designed an interface like this.

public interface CSVParser<T> {
    public List<T> parseCSVFile(String fileName);
}

And I have created 4 different parsers, which implement the interface and have a different logic of parsing the CSV file. The code below is a complete implementation for CSV_FILE_B. The other three parsers will have the same structures but different if-else statements for setting object fields and different object types in the type of List.

public class csvBParser implements CSVParser {

    @Override
    public List<ObjectB> parseCSVFile(String fileName) {

        List<ObjectB> list = new ArrayList<ObjectB>();

        try {
            ClassLoader classLoader = Thread.currentThread()
                    .getContextClassLoader();
            InputStream is = classLoader.getResourceAsStream(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line = "";
            StringTokenizer token = null;
            int lineNum = 0, tokenNum = 0;

            while ((line = br.readLine()) != null) {
                if (lineNum == 0){
                    lineNum++;
                    continue;
                }

                token = new StringTokenizer(line, ",");
                ObjectB objB = new ObjectB();

                while (token.hasMoreTokens()) {
                    String nextToken = token.nextToken();

                    boolean isTokenNull = false;
                    if (nextToken.equalsIgnoreCase("null"))
                        isTokenNull = true;

                    if (!isTokenNull) {
                        if (tokenNum == 0) {
                            objB.setObjBId(Long.valueOf(nextToken));
                        } else if (tokenNum == 1) {
                            objB.setObjBSndId(Long.valueOf(nextToken));
                        } else {
                            System.err.println("Invalid Token Number "
                                    + tokenNum);
                        }
                    }
                    tokenNum++;
                }

                list.add(objB);
                tokenNum = 0;
                lineNum++;
            }
        } catch (Exception e) {
            System.err.println("Parse Error " + e.getMessage());
        }

        return list;
    }
}

And, I finally uses a factory to create an instance of a parser.

public class CSVParserFactory {

    public static CSVParser getParser(TableType type) {

        CSVParser parser = null;
        if(type == A){
            parser = new csvAParser();
        }
        else if(type == B){
            parser = new csvBParser();
        }
        else if(type == C){
            parser = new csvCParser();
        }
        else if(type == D){
            parser = new csvDParser();
        }
        /*
         * more parsers will be added later
         */
        else{
            throw new IllegalArgumentException ("No such table type");
        }
        return parser;
    }
}

The parser is being called like this. Each element in the list is corresponding to a row in the CSV file

CSVParser parser = CSVParserFactory.getParser(TableType.A);
List list = parser.parseCSVFile(CSV_FILE_A);

Do you guys have any suggestions of this design pattern?
If I consider a code factorization, what do I need to do?

Thanks in advance.

First, there would be much duplication between the parser classes. This kind of duplication should be avoided. If you find a bug in the way the csv is being parsed, you now have to fix it in multiple places. Consider using the template method pattern. In this scenario, you would extract the common logic into an abstract superclass with 1 or more abstract "template methods" that would be implemented by the subclasses. For instance, the abstract superclass could parse the fields into an array or strings, then pass the array to a method to construct an object using those fields.

public abstract class AbstractCSVParser<T> implements CSVParser<T> {

    public List<T> parseCSVFile(String fileName) {
        List<T> list = new ArrayList<T>();

        // for each line...
        String[] fields = // parse line into an array of strings
        T obj = buildObject(fields);
        list.add(obj);

        return list;
    }

    protected abstract T buildObject(String[] fields);

}

public class csvBParser extends AbstractCSVParser<ObjectB> {

    protected ObjectB buildObject(String[] fields) {
        ObjectB obj = new ObjectB();
        // populate object with fields
        return obj;
    }

}

In the parsing code, the InputStream and BufferedReader are never closed. Make sure you close resources when you are done with them, and make sure it is happening inside a finally block.

BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
    // do work with br
}
finally {
    br.close();
}

If you are using Java 7, you should check out the try-with-resources statement. The above example could be written like this:

try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
    // do work with br
} // close is called automatically at the end of the try block

In this example, the parser classes appear to be stateless. Given this, CSVParserFactory doesn't really need to return a new instance every time. One option to simplify CSVParserFactory is to initialize a static Map containing the parser instances.

public class CSVParserFactory {

    private static final Map<TableType, CSVParser> PARSERS = new HashMap<TableType, CSVParser>() {{
        put(A, new csvAParser());
        put(B, new csvBParser());
        put(C, new csvCParser());
        // etc
    }};

    public static CSVParser getParser(TableType type) {
        CSVParser parser = PARSERS.get(type);
        if (parser == null) {
            throw new IllegalArgumentException("No such table type");
        }
        return parser;
    }

}

If you don't want this, and still want to create the parser instances each time, you could use the same strategy with the class names instead of instances, then create the instance using reflection.

Finally, you may want to consider passing an InputStream to parseCSVFile instead of a file name. This would allow more flexibility of the source of the data. The current implementation is very specific as to the source.


Understanding exceptions in a constructor (by the conversion C-string to long example) I myself is a Java-developer and now I'm trying to understand how to do it in the most efficient way in C++. After reading that answer I decided to write the following:

//Headers omitted
class integer_validator
{
public:
    integer_validator(const char* const str);
    bool is_valid();
    long get_number();
private:
    bool valid;
    long result;
};

integer_validator::integer_validator(const char* const str)
{
    char *endptr;
    result = strtol(str, &endptr, 10);
    if(*endptr == '\0') valid = true;
    else valid = false;
}

bool integer_validator::is_valid()
{
    return valid;
}

long integer_validator::get_number()
{
    if(!valid)
        throw std::exception();
    return result;
}
int main ()
{
    integer_validator vv("123123");
    integer_validator v("123123a");
    std::cout << vv.get_number() << std::endl; //prints the number
    std::cout << v.get_number() << std::endl;  //throws the exception
}

DEMO

And it works perfectly fine. But I'm not sure about some things I did. Is it considered good to put any piece of logic into a constructor? I actually do the validation within the constructor's body and I use only the C-functions.

So should I be afraid of throwing an exception during the construction in that case?

From the c++ specification's point of view a constructor is allowed to throw an exception (in opposite to destructor). So your code is fine.

On the other hand I don't see any advantage why it should be validated directly in the constructor. You could do it in is_valid method as well. Furthermore, if you moved the valifation code out from the constructor to a private method, you would gain an easy way to keep responsibility of handling low-level exceptions inside you class.
So, although your code is valid semantically, its design needs some improvement.

I hope I helped:)


Elevator Interview Problem OOP Can someone please critique my Elevator problem - I wanted to use OOP principles and coding standards.
Also, does logic make sense?

Once elevator starts going up it needs to finish all requests for above floors, same for down.

So I imagine that if the elevator is moving up and the request is floor below it will need to finish all up/above requests etc.

internal class Program
{
    private const string _quit = "q";

    private static void Main(string[] args)
    {
        var manager = new Manager();
        var input = string.Empty;

        while (input != _quit) {
            Console.Write("Enter floor: ");
            input = Console.ReadLine();
            int floor;
            if (int.TryParse(input, out floor))
                manager.ButtonPressed(floor);
            else if (input == _quit)
                Console.WriteLine("GoodBye!");
            else
                Console.WriteLine("You have pressed an incorrect floor, Please try again");
        }
    }
}

internal enum Status
{
    GoingUp,
    GoingDown,
    Stopped
}

internal class Elevator
{
    public int TopFloor;

    public Elevator(int topFloor)
    {
        TopFloor = topFloor;
    }

    public int CurrentFloor { get; set; } = 1;
    public Status Status { get; set; } = Status.Stopped;

    public void MoveUp(int floor)
    {
        Status = Status.GoingUp;
        Console.WriteLine("Going up to: {0}", floor);
        CurrentFloor = floor;
        OpenDoor();
        CloseDoor();
    }

    public void MoveDown(int floor)
    {
        Status = Status.GoingDown;
        Console.WriteLine("Going down to: {0}", floor);
        CurrentFloor = floor;
        OpenDoor();
        CloseDoor();
    }

    private void OpenDoor()
    {
        Console.WriteLine("Door opening");
    }

    private void CloseDoor()
    {
        Console.WriteLine("Door closing, at floor: {0}", this.CurrentFloor);
    }
}

internal class Request
{
    public Request(int floor)
    {
        Floor = floor;
    }

    public int Floor { get; set; }
}

internal class Manager
{
    private readonly Queue<Request> _downRequests = new Queue<Request>();
    private readonly Elevator _elevator = new Elevator(10);
    private readonly Queue<Request> _upRequests = new Queue<Request>();

    public void ButtonPressed(int floor)
    {
        if (floor > _elevator.TopFloor) {
            Console.WriteLine("Only have {0} floors", _elevator.TopFloor);
            return;
        }

        if (floor > _elevator.CurrentFloor)
            _upRequests.Enqueue(new Request(floor));
        else
            _downRequests.Enqueue(new Request(floor));

        Move(floor);
    }

    private void Move(int floor)
    {
        switch (_elevator.Status) {
            case Status.GoingDown:
                while(_downRequests.Count > 0)
                    _elevator.MoveDown(_downRequests.Dequeue().Floor);

                _elevator.Status = Status.Stopped;
                break;

            case Status.GoingUp:
                while(_upRequests.Count > 0)
                    _elevator.MoveUp(_upRequests.Dequeue().Floor);

                _elevator.Status = Status.Stopped;
                break;

            case Status.Stopped:
                if (floor > _elevator.CurrentFloor)
                    _elevator.Status = Status.GoingUp;
                else if (floor <= _elevator.CurrentFloor) {
                    _elevator.Status = Status.GoingDown;
                }
                Move(floor);

                break;
            default:
                break;
        }
    }
}

Revised code based on feedback: Elevator Interview Problem OOP - Revised

I see a few things I would do differently.  For one, I would not use a Queue.  At best, it's providing you an order in which floor buttons were pressed.  While the buttons may be pressed in any order, an elevator moves in sequential order be it up or down.

I would keep a simple List<bool> where true denotes a floor to stop at.  Once you stop at a floor, no need to Dequeue.  Instead just set the flag to false.  By keeping it simple, you won't have to jump through hoops if you are going up but someone presses buttons for 10, 5, 2, 9, 7.


React-Redux with functional Components This is a pretty simple working example using React-Redux to select a user from app.com/user/:userId and then fetch/display that user's info from a remote API
Most of the examples/code I can find online use class-based components but since I already have part of a project written using a functional approach I'm looking for feedback on how I'm integrating redux into functional components. I'm also not a Javascript expert by any means either so general critique of my JS is welcome as well!
Store.js:
import { createStore } from "redux";

const initialUser = { user: [] };

const userReducer = (state = initialUser, action) => {
  switch (action.type) {
    case "ADD_USER":
      return Object.assign({}, state, { user: action.user });
    default:
      return state;
  }
};

export default function Store() {
  return createStore(userReducer);
}

Actions.js:
const validResp = (resp) => {
  return resp.data.code === 200;
};

const extractUser = (resp) => {
  return resp.data.data;
};

export const addUser = (resp) => {
  let user = "";

  if (validResp(resp)) {
    user = extractUser(resp);
  }

  return {
    type: "ADD_USER",
    user: user
  };
};

index.js:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { BrowserRouter as Router, Route } from "react-router-dom";

import AppContainer from "./AppContainer";
import Store from "./Store";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={Store()}>
    <Router>
      <Route path="/user/:userId" component={AppContainer} />
    </Router>
  </Provider>,
  rootElement
);

AppContainer.js:
import React from "react";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import axios from "axios";

import { addUser } from "./Actions";

const baseUrl = "https://gorest.co.in/public-api/users/";

export default function AppContainer() {
  const url = baseUrl + useParams().userId;
  const user = useSelector((state) => state.user);
  const dispatch = useDispatch();

  useEffect(() => {
    axios.get(url).then((resp) => dispatch(addUser(resp)));
  });

  return <App user={user} />;
}

function App(props) {
  return (

      Name: {props.user.name}

      id: {props.user.id}

  );
}

Concisely merging objects can be done with spread syntax instead of Object.assign. The ADD_USER case can use:
return { ...state, user: action.user };

Using spread syntax instead of Object.assign doesn't have a big impact here, but it makes things so much easier when the state structure grows to be large and complicated.
Functional programming does not reassign variables - everything should be declared with const. If you want to be more functional, change addUser to use the conditional operator to either assign the empty string or the extractUser result to the user variable:
export const addUser = (resp) => {
  const user = validResp(resp) ? extractUser(resp) : "";
  return {
    type: "ADD_USER",
    user
  };
};

(Note that if the key is named the same as the variable the value is in, you can use shorthand property names like above. You could also return the whole object at once without declaring a user variable first.)
useEffect bug Since you didn't provide a dependency array to useEffect, its callback will run on every render. I'm pretty sure this isn't desirable - you want it to run only on the initial render, right? Pass an empty dependency array to useEffect so that the callback inside only runs on mount:
useEffect(() => {
  axios.get(url).then((resp) => dispatch(addUser(resp)));
}, []);

Error handling If the axios.get Promise rejects, no indication is given. Always .catch Promises somewhere. You might want something like
useEffect(() => {
  axios.get(url)
    .then((resp) => dispatch(addUser(resp)))
    .catch((error) => dispatch(addError(error.message)));
}, []);

or something of the sort, to show that an error occurred.


Generating hard to guess session tokens Does this code create sufficiently hard-to-guess session tokens, assuming the server and client are communicating over HTTPS?

Take 2 (thanks to this crypto.SE answer):

(ql:quickload (list :ironclad :cl-base64))

(let ((prng (ironclad:make-prng :fortuna)))
  (defun new-session-token ()
    (cl-base64:usb8-array-to-base64-string
     (ironclad:random-data 32 prng) :uri t)))

As an additional note, the previous version was using the incorrect encryption mode (ecb, instead of ctr which is preferable for this task), and using an insecure method of generating random keys ((sha256 rand)).

If not, what else is required for that goal, and why?

Are there attacks I should be worried about other than guessing and sniffing session tokens?

Your question doesn't give enough information about exactly what you want to do to know if this might work in your case.  The most important answer is simple though:  "don't do that; use a web framework instead".  Session management should almost always be done in the standard way of your framework; then you won't have to do anything other than check if your framework thinks your user is authenticated.

Let's now look at the specifics of the code.  You have used a cryptographic PRNG.  That should be fine.  You used 32 bytes = 256 bits of random data.  This should be no problem (128 bits is normally enough against brute force attack; 256 is overkill, which is likely good in this case)  your main fears should probably be seeding and leaking bits.

Seeding: the PRNG documentation says that if you don't give a random seed the PRNG will be unseeded.  In real life it seems that it actually does get seeded from /dev/random.  I deeply don't like this and would probably seed it explicitly.  Better would be discuss with the author and send a patch to the documentation for the library so that it promises to do what it actually does.  I don't have an OS without /dev/random to test on, but I think your function simply won't work there (which is good because it's safe).

Leaking bits1:  If the attacker can find a situation where response time depends on the contents there might be a problem (e.g. force regeneration of the session).  Looking up about timing attacks on Ironclad I don't think it's resistant (see e.g. https://www.mail-archive.com/pro@common-lisp.net/msg00977.html).  You need to check or protect against this.  If the contents of the message are true then you should probably switch to a better library such as LibreSSL when it comes out (possibly GNU TLS?).  If someone attempts to use the function on e.g. Windows I would simply exit with a warning.

Leaking bits2: your output is constant size but includes some special characters. If the attacker can find a situation where your message length depends on the authentication token then you have a problem.  Using Base64 encoding (a second time) should be fine.  Using maximal HTML encoding for your tokens will not be (n.b. normal HTML would be fine; but some encoders go too far).

Leaking bits3: Going further, there are standard attacks against SSL/TLS which I think you should consider; BEAST, CRIME and BREACH which leak bits https://en.wikipedia.org/wiki/Transport_Layer_Security#CRIME_and_BREACH_attacks.  Increasing the size of your random token beyond 256 bits might marginally protect against such things.  However "In the current form, the exploit uses JavaScript and needs 6 requests to extract one byte of data" (https://community.qualys.com/blogs/securitylabs/2012/09/14/crime-information-leakage-attack-against-ssltls) so I think you may find that effort would be better invested in turning off compression on all sites and user web browsers.  Personally I would go for 384 bytes just to be more conservative than the rest ;-)

Summary: probably your function is basically the same one used in many frameworks.  Because of the risk of timing attacks and bit leakage I wouldn't personally want to release it for public use until I understood the whole surrounding situation of usage much better than I currently do.

(edited lots since I misread bytes as bits in the first response)


Counting ways to divide a word into palindrome blocks I wrote this program as a solution to the 2015 British Informatics Olympiad question on "block" palindromes.
Brief overview of the task:

A palindrome is a word that shows the same sequence of letters when reversed.
If a word can have its letters grouped together in two or more blocks (each containing one or more adjacent letters) then it is a block palindrome if reversing the order of those blocks results in the same sequence of blocks.
For example, using brackets to indicate blocks, the following are block palindromes:

BONBON can be grouped together as (BON)(BON);
ONION can be grouped together as (ON)(I)(ON);
BBACBB can be grouped together as (B)(BACB)(B) or (BB)(AC)(BB) or (B)(B)(AC)(B)(B)

Note that (BB)(AC)(B)(B) is not valid as the reverse (B)(B)(AC)(BB) shows the blocks in a different order.
TASK: Write a program which reads in a word of between 2 and 10 (inclusive) uppercase letters.
You should output a single number, the number of different ways the input can be grouped to show it is a block palindrome.

What tips do you have for improving my solution:
# theonlygusti's solution to Question 1(a)

word = input()

if not (2 <= len(word) <= 10):
    print("Your input must be between 10 and 2 characters, inclusive.")
    exit()

if not word.upper() == word:
    print("Your input must be all uppercase, e.g. BBACBB")
    exit()

if not word.isalpha():
    print("Your input must contain only letters, this means characters like numbers and spaces are not allowed.")
    exit()

def number_of_block_palindrome_groupings(string):
    total_groupings = 0
    for i in range(1, len(string)//2+1):
        if (string[:i] == string[-i:]):
            total_groupings += 1 + number_of_block_palindrome_groupings(string[i:-i])
    return total_groupings

print(number_of_block_palindrome_groupings(word))

Exit code

When exiting due to an error, it's good to use a non-zero exit code.
Calling exit() without an explicit value will use the default 0, meaning success.

Naming

The name number_of_block_palindrome_groupings is a bit long an tedious.
How about count_block_palindromes?

List comprehensions

Instead of accumulating a sum with a loop,
you could use a list comprehension:

return sum([1 + count_block_palindromes(string[i:-i])
            for i in range(1, len(string) // 2 + 1)
            if string[:i] == string[-i:]])

Memoization

In case of long input with recursive patterns,
the same substrings may be computed many times repeatedly.
It could be a useful optimization to cache the results of computing each unique input.
An easy way to implement that using functools.lru_cache.

import functools

@functools.lru_cache()
def count_block_palindromes(string):
    # ...

Doc tests

Doc tests are awesome. They are executable documentations serving as unit tests, for example:

def count_block_palindromes(string):
    """
    >>> count_block_palindromes("BONBON")
    1

    >>> count_block_palindromes("ONION")
    1

    >>> count_block_palindromes("BBACBB")
    3

    >>> count_block_palindromes("BABABABABABABABA")
    15

    >>> count_block_palindromes("BABABABABABABAB")
    33

    """
    # ... the code

This is runnable in Pycharm with Control Shift R,
or in the shell with python -mdoctest yourscript.py.


DRY up Rails Navigation Code In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i would have to go through every view and add that link. I decide to make a partial view in layouts/_nav.haml which contains:

= link_to 'Home', root_path, :class => "btn #{active_page(root_path)}"
= link_to 'Sign in', sign_in_path, :class => "btn #{active_page(sign_in_path)}"
= link_to 'Account', account_path, :class => "btn #{active_page(account_path)}"

and then in my application_helper.rb i added:

def active_page(path)
  'active' if current_page?(path)
end

I know this isn't the best approach, is there any way to DRY up this solution or make it better. Im using bootstrap and i tried the simple-navigation gem but it wasn't that useful in my situation.

You could create another helper to create your navigation links:

def navigation_link_to(text, path)
  link_to text, path, class: "btn #{active_page(path)}"
end

Then in your view:

= navigation_link_to 'Home', root_path
= navigation_link_to 'Sign in', sign_in_path
= navigation_link_to 'Account', account_path


Checking if 3 numbers are an arithmetic progression Mod note: This question is being discussed on meta

I tried to create a method, that given 3 int numbers and a bool returns true if they are in strict increasing order (by the same amount) like (1, 2, 3), (3, 7, 11) or (0, 4, 8). Except if equalOk is set to true, then equality of two adjacent elements is allowed, such as (5,5,7) or (3,3,3) which should also return true;.

Is there any redundant code in my solution and how could it be done simpler?

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

namespace InOrderEqual
{
    class Program
    {
        static void Main(string[] args)
        {
            InOrderEqual(2, 5 , 11, false);  //true
            InOrderEqual(0, 5, 10, false);  //true
            InOrderEqual(5, 4, 3, true);   //false
            InOrderEqual(5, 5, 7, true);   //true
            InOrderEqual(1, 2, 3, true);   //true
            InOrderEqual(12, 12, 12, false); // false
            InOrderEqual(5, 8, 11, false); // true
            Console.ReadLine();
        }
        public static bool InOrderEqual(int a, int b, int c, bool equalOk)
        {
            bool isEqual = false;
            if (b == a || (a == b && a == c))
            {
                isEqual = true;
                if (equalOk == true)
                {
                    Console.WriteLine(true);
                    return true;
                }
                else Console.WriteLine(false);
                return false;
            }

            else if (( a + a) - b == (b + b) - c|| b - a == c - b && c > b && b > a)
            {
                Console.WriteLine(true);
                return true;
            }

            Console.WriteLine(false);
            return false;
        }
    }
}

The requirements are that (1) b - a == c - b and that (2) a < b < c, except when equalOk is true, in which case (3) a <= b <= c. If (1) is true, then it is sufficient to just check a < b for (2) and a <= b for (3).

private bool InOrderEqual(int a, int b, int c, bool equalOk) {
    if (b - a != c - b) return false; // (1)
    if (equalOk) return a <= b; // (3)
    return a < b; // (2)
}

Originally, equidistance was not an explicit requirement.

Original answer:

The requirements are that a < b < c, except when equalOk is true, in which case a <= b <= c. There's no need for anything more complex than this:

private bool InOrderEqual(int a, int b, int c, bool equalOk) {
    if (equalOk) return a <= b && b <= c;
    return a < b && b < c;
}


Python 3.4 password generator I'm pretty new to Python and I made a password generator. I would like you to check it out and give me tips on how I could do it better.

import random

def small():  # Prints a generated string of 6 chars

    list = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
    "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z")

    generatepassword = random.choice(list) + random.choice(list) + random.choice(list) + random.choice(list) +\
               random.choice(list) + random.choice(list)

    print(generatepassword)
    print("The passwords consists of: " + str(len(generatepassword))+" Characters")
    print("\n")

def med():  # Prints a generated string of 10 chars

   list2 = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
     "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
     "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
     "v", "w", "x", "y", "z")

   generatepassword = random.choice(list2) + random.choice(list2) + random.choice(list2) + random.choice(list2) +\
               random.choice(list2) + random.choice(list2) + random.choice(list2) + random.choice(list2) +\
               random.choice(list2) + random.choice(list2)

   print(generatepassword)
   print("The passwords consists of: " + str(len(generatepassword))+" Characters")
   print("\n")

def big():  # Prints a generated string of 32 chars

    list3 = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
     "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
     "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
     "v", "w", "x", "y", "z")

    generatepassword = random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3)

    print(generatepassword)
    print("The passwords consists of: " + str(len(generatepassword))+" Characters")
    print("\n")

def generate():  # This askes how long the password should be

    print("How big do you want your password? choices >> [6], [10], [32]")
    choice = input("please input the lenght >> ")

    while choice != '6' and choice != '10' and choice != '32':
         choice = input("please choose: [6], [10] or [32] >> ")

        if choice == '6':
          break

        elif choice == '10':
          break

        elif choice == '32':
          break

   if choice == '6':
       small()

   if choice == '10':
       med()

   if choice == '32':
       big()

again = 'yes'
while again == 'yes' or again == 'y':

  # From here on the user can choose to generate another password
  # If the person typed yes or y then it will run the def function generate
  # And it will restart
  # If the user types anythin else then yes or y then the program quits

  generate()
  print("\n")
  print("Do you want to generate another password? [yes] or [no] >> ")
  again = input()

Summary:

If you have multiple function that does similar tasks, make it as one that passes an arg.
If you have to repetitively type the something over and over again, there's probably a better way to do it
Include some error checking in spots such as input()
Take advantage of the string module. For example: string.ascii_letters is the same as 'abcdef...ABCDEF...'

Note to the OP:

Here's a more concise version of your code. I also made it be able to take any amount of length. Read the comments cause they explains every change I made

import random
import string

def gen_pass(length):  # Prints a generated string of any length of chars

    # don't name anything list or other type name. Use a name like word_list instead
    word_list = list(string.ascii_letters+string.digits) # use string module to make it shorter, so you dont need to type everything

    generatepassword = "".join([random.choice(word_list) for i in range(length)]) # typing the same thing over and over again is redundent
                                                                        # use a variable for the length instead of making multiple functions

    print(generatepassword)
    print("The passwords consists of: {} Characters\n".format(length)) # use str.format instead of + to make it look neater.
                                                            # isn't length the same as len(generatepassword)?
                                                    # add the \n on to the previous print statement

# don't need the other functions now

def generate():  # This askes how long the password should be

    print("How long do you want your password? ") # now it supports any length of password
    while 1: # do some checking, while 1 is an infinite loop until it's breaked
        try: # do some error checking as well
            choice = int(input("please input the length >> ")) # make it an integer
            if choice < 1: # should not be less than 1
                raise TypeError()

        except TypeError: # if choice < 1:
            print("Length should not be less than 1") # show an error message

        except ValueError: # if choice is not a number:
            print("Please input a valid integer") # show an error message

        except:
            print("Some other error occured... :(") # show an error message if some other error occured, though I don't think it's possible

        else:
            break # if no error occured

    gen_pass(choice) # generates a password with any length
    # everything else isn't needed

again = 'yes'
while again.lower() in ['yes','y']: # use lower in case they capped it, use this kind of checking method
  generate()
  again = input("\nDo you want to generate another password? [yes] or [no] >> ") # put the print statements inside the input()


Faster and cleaner SHA-1 leading zero histogram with Python I've written a python code for finding the distribution of the leading zeros of SHA-1. Using random inputs and hashing-then-counting. Normally it is expected to fit the n/2^i curve where n is the number of trials. After this, a plot is drawn.
import hashlib
import random
import matplotlib.pyplot as plt

leading = [0] * 160

trials = 10000000000

for i in range(trials):

    randomInput= random.getrandbits(128)

    hasvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()

    b = bin(int(hasvalue, 16))
    c= b[2:].zfill(160)
    zeroes = str(c).index('1')
    leading[zeroes] = leading[zeroes] + 1

The most time-consuming part of this code is of course the SHA-1 calculation and we cannot do something for that except parallelization with pymp or some other library. What I'm not mostly unhappy here is the whole conversions between str, bin and back.
Any improvements for a cleaner code and little speed up?

Instead of str(random.getrandbits(128)).encode('ASCII') I'd use os.urandom(16). Much simpler, ought to be more random, shorter result, and a bit faster (at least for me). Or convert your random number to bytes directly, even faster (at least for me):
>>> timeit(lambda: str(random.getrandbits(128)).encode('ASCII'))
1.320366100000001
>>> timeit(lambda: os.urandom(16))
0.7796178000000111
>>> timeit(lambda: random.getrandbits(128).to_bytes(16, 'big'))
0.6476696999999945

From the doc:

os.urandom(size)
Return a string of size random bytes suitable for cryptographic use.

And to count zeros, perhaps use digest(), make an int from it and ask for its bit length:
    hashvalue = hashlib.sha1(os.urandom(16)).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

Benchmark results (numbers are times, so lower=faster):
0.56 zeroes_you
0.31 zeroes_me
0.29 zeroes_me2
0.26 zeroes_me3

0.60 zeroes_you
0.31 zeroes_me
0.28 zeroes_me2
0.24 zeroes_me3

0.57 zeroes_you
0.31 zeroes_me
0.28 zeroes_me2
0.24 zeroes_me3

Benchmark code:
import hashlib
import random
import os
from timeit import repeat

def zeroes_you():
    randomInput= random.getrandbits(128)
    hashvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()
    b = bin(int(hashvalue, 16))
    c= b[2:].zfill(160)
    zeroes = str(c).index('1')

def zeroes_me():
    hashvalue = hashlib.sha1(os.urandom(16)).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

def zeroes_me2():
    randomInput = random.getrandbits(128)
    hashvalue = hashlib.sha1(randomInput.to_bytes(16, 'big')).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

def zeroes_me3(randbits=random.getrandbits, sha1=hashlib.sha1, int_from_bytes=int.from_bytes):
    hashvalue = sha1(randbits(128).to_bytes(16, 'big')).digest()
    zeroes = 160 - int_from_bytes(hashvalue, 'big').bit_length()

for _ in range(3):
    for zeroes in zeroes_you, zeroes_me, zeroes_me2, zeroes_me3:
        t = min(repeat(zeroes, number=100000))
        print('%.2f' % t, zeroes.__name__)
    print()


Helper method to shuffle cards list for online gaming I have written this code to shuffle a deck of cards. I would like to hear your inputs.

public static class Helper
{

    public static Int32 GetRandomNo(this RNGCryptoServiceProvider rng, byte[] data)
    {
        rng.GetBytes(data);
        var randomNo = BitConverter.ToInt32(data, 0);
        return randomNo;
    }

    public static void Shuffle<T>(this List<T> source)
    {
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            // Buffer storage.
            byte[] data = new byte[4];

            source =
                source.Select(element => new {element, randomValue = rng.GetRandomNo(data)})
                    .OrderBy(entry => entry.randomValue)
                    .Select(entry => entry.element)
                    .ToList();
        }
    }
}

4 bytes is only 4,294,967,296
Consider there are 52! possible shuffles = 8 * 10^67

Use a proper shuffle like Fisher Yates. You get a proper shuffle with only 0-51 random.  Also shuffle from the prior shuffle (not a sorted deck). If you look closely Fisher Yates it produces exactly 52! deals.  It is perfect.

I am not sure about your algorithm but I think the problem is that it will produce too many shuffles and they will not have uniform distribution.  I think it will produce 52^52 deals.

A perfect random with a less than perfect algorithm is a bigger vulnerability than a perfect algorithm and a less than perfect random.

You can use the regular Random and a proper algorithm and not be exploited unless they know the seed.  But it does not hurt to use RNGCryptoServiceProvider.

Poker security


Universal CSS template for global styles I 'm trying to create a universal CSS template for global styles. I can not find unambiguous recommendations. After inspecting various sites, I have compiled the following template . I ask your advice . Thank you!

*,
*:after,
*:before {
    box-sizing: border-box;
}

html,
body {
    overflow-x: hidden;
    overflow-y: hidden;
    width: 100%;
    height: 100%;
}

html {
    font-size: 62.5%;
    // background-color: x;
}

body {
    position: relative;
    z-index: 0;
    min-height: 100%;
    color: x;
    background-color: x;
    font-family: x;
    font-size: 1.6rem;
    font-weight: x;
    font-style: normal;
    line-height: x;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
}

.wrapper {
    margin: 0 auto;
    min-width: 320px;
    padding: x;
}

I can not find unambiguous recommendations. After inspecting various sites, I have compiled the following template

The canonical example domain exists for such a purpose. Here is its style declaration:

body {
    background-color: #f0f0f2;
    margin: 0;
    padding: 0;
    font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

}
div {
    width: 600px;
    margin: 5em auto;
    padding: 50px;
    background-color: #fff;
    border-radius: 1em;
}
a:link, a:visited {
    color: #38488f;
    text-decoration: none;
}
@media (max-width: 700px) {
    body {
        background-color: #fff;
    }
    div {
        width: auto;
        margin: 0 auto;
        border-radius: 0;
        padding: 1em;
    }
}


Simple mathematical operations (add, sub, mul, div) in C++11 template I made a simple script to implement basic mathematics operations by using variadic functions. I would like to know if my implementation is correct.

The code only works for Visual C++ compiler Nov 2013 CTP (CTP_Nov2013).

#include <iostream>
#include <string>
#include <exception>
using namespace std;

template <typename T>
T add(T&& item = T())
{
    return forward<T>(item);
}

template <typename T, typename ... Types>
auto add(T&& first, Types&& ... rest)
    -> decltype(first + add(forward<Types>(rest)...))
{
    return forward<T>(first) + add(forward<Types>(rest)...);
}

template <typename T>
T sub(T&& i = T())
{
    return forward<T>(i);
}

template <typename T, typename ... Types>
auto sub(T&& first, Types&& ... rest)
-> decltype(forward<T>(first) - sub(forward<Types>(rest)...))
{
    return forward<T>(first) - sub(forward<Types>(rest)...);
}

template <typename T>
T multiple(T&& i = T())
{
    return forward<T>(i);
}

template <typename T, typename ... Types>
auto multiple(T&& first, Types&& ... rest)
-> decltype(forward<T>(first) * multiple(std::forward<Types>(rest)...))
{
    return forward<T>(first) * multiple(forward<Types>(rest)...);
}

template <typename T>
T divide(T&& item = T())
{
    return forward<T>(item);
}

template <typename T, typename ... Types>
auto divide(T&& first, Types&& ... rest)
    -> decltype(forward<T>(first) / divide(forward<Types>(rest)...))
{
    if (divide(forward<Types>(rest)...) == 0)
        throw "Opps divided by Zero";
    return forward<T>(first) / divide(forward<Types>(rest)...);
}

template<typename... Types>
void termnate(Types&&...)
{
    std::cout << '\n';
}

template<typename... Types>
void result(Types&&... t)
{
    termnate{ ([&]{ std::cout << forward<Types>(t) << ' '; }(), 1)... };
}

int main()
{
    result(     add(1, 2.5, 3, 4, 5), " = ", "1 + 2,5 + 3 + 4 + 5");

    result(sub(sub(sub(sub(1, 2.5), 3), 4), 5), " = ", "1 - 2.5 - 3 - 4 - 5"); // OK = -13.5

    result(multiple(1, 2.5, 3, 4, 5), " = ", "1 x 2.5 x 3 x 4 x 5");

    result(divide(divide(divide(divide(1, 2.5), 3), 4.5), 5), " = ", "1 / 2.5 / 3 / 4 / 5"); // OK = .005926

    cout << add("\nTest ", "template: ", string("PASS\n"));
}

When passing around move references, the recommended is to forward the parameters to ensure that the move reference is preserved:

template <typename T, typename ... Types>
auto add(T&& first, Types&& ... rest)
    -> decltype(first + add(std::forward<Types>(rest)...))
{
    return first + add(std::forward<Types>(rest)...);
}

Note that you have to explicitly provide the template type to std::forward(). It would deduce the wrong type otherwise.


K&R exercise 1-19: reversing each line of input This is my solution for exercise 1-19 of K&R:

  Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.1

It works, but I'm trying to write good programs. I think the fact that I can't use the length of the vector when already got the line in function getlinea makes me think I could do better. The function reverse(s) uses 3 for sentences, which might be a little ugly. I know it doesn't mean it's not good but having to "read" the line 4 times is kind of a little stupid to me. I still can't think of a different solution.

/*
 * main.c
 *
 *  Created on: 19/3/2015
 *      Author: utnso
 */

#include <stdio.h>

#define MAXLINE 1000

void reverse (char s [] );
int getlinea (char s [] , int lim);

int main ()
{
    int len;
    char palabra [MAXLINE];
    while ( ( len = getlinea ( palabra, MAXLINE ) )  >= 0 )
        if (len > 0)
            printf ("%s\n", palabra);
    return 0;

}

int getlinea ( char s [], int lim )
{
    int i, c;
    i = 0;
    while ( ( c = getchar() ) != EOF && c != '\n' && i < lim-1 )
    {
        s [i] = c ;
        ++ i;
    }
    s [i] = '\0';
    if ( i > 0 )
        reverse ( s ) ;
    else
        if ( c == EOF )
            return -1;
    return i ;
}

void reverse ( char turnaround [] )
{
    int i, j;
    int h = 0;
    char aux [MAXLINE];
    for ( i = 0; turnaround [i] != '\0' ; ++i )
        ;
    for ( j = i-1 ; j >= 0 ; --j)
    {
        aux [h] = turnaround [j];
        ++h;
    }
    for ( i = 0 ; turnaround [i] != '\0' ; ++i )
        turnaround [i] = aux [i];
}

This is the output for

$ ./1-19 < main.c

(it also deletes white lines)

*/
c.niam *
*
5102/3/91 :no detaerC  *
osntu :rohtuA      *
/*
>h.oidts< edulcni#
0001 ENILXAM enifed#
;) ][ s rahc( esrever diov
;)mil tni , ][ s rahc( aenilteg tni
)( niam tni
{
;nel tni
;]ENILXAM[ arbalap rahc
) 0 =>  ) ) ENILXAM ,arbalap ( aenilteg = nel ( ( elihw
)0 > nel( fi
;)arbalap ,"n\s%"( ftnirp
;0 nruter
}
) mil tni ,][ s rahc ( aenilteg tni
{
;c ,i tni
;0 = i
) 1-mil < i && 'n\' =! c && FOE =! ) )(rahcteg = c ( ( elihw
{
; c = ]i[ s
;i ++
}
) 0 > i ( fi
{
;'0\' = ]i[ s
; ) s ( esrever
}
esle
) FOE == c ( fi
;1- nruter
; i nruter
}
) ][ dnuoranrut rahc ( esrever diov
{
;j ,i tni
;0 = h tni
;]ENILXAM[ xua rahc
) i++ ; '0\' =! ]i[ dnuoranrut ;0 = i ( rof
;
)j-- ; 0 => j ; 1-i = j ( rof
{
;]j[ dnuoranrut = ]h[ xua
;h++
}
) i++ ; '0\' =! ]i[ dnuoranrut ; 0 = i ( rof
;]i[ xua = ]i[ dnuoranrut
}

1http://cs.indstate.edu/~cbasavaraj/cs559/the_c_programming_language_2.pdf -
 Page 31

getlinea does too much: it reads the line and reverses it. A Single Responsibility Principle mandates restructuring the code:

while((len = getlinea(...)) > 0) {
    reverse();
    print();
}

Avoid naked loops. Each loop represent an important action, and deserves a name. The code:

reverse(char turnaround[])
{
    char aux[...];
    int len = length_of_string(turnaround);
    copy_backwards(aux, turnaround, len);
    copy(turnaround, aux, len);
}

is much easier to reason about.
The length of the input is known to the caller. Consider passing it as parameter:

reverse(char turnaround[], int len)
{
    char aux[...];
    copy_backwards(aux, turnaround, len);
    copy(turnaround, aux, len);
}

Finally, a string can be reversed in place. There is no need for aux. I hope you can figure a solution yourself.


A closer look at the chat's mumblings The Go Playground was boring so I decided to make a small application that throws me into the language. It basically queries the chatroom every second for new messages and displays them in the output pane (minus the bots their messages).

It's all new to me so any insight is welcome. One thing I've been particularly unsure about are my return statements and whether I'm using them correctly. Likewise, there are a bazillion different ways to declare a variable; have I done it correctly so far?

package main

import (
    "encoding/json"
    "fmt"
    sanitize "github.com/kennygrant/sanitize"
    "html"
    "io/ioutil"
    "net/http"
    "net/url"
    "strconv"
    "time"
)

type ChatEvent struct {
    Event_type    int8
    Time_stamp    int64
    Content       string
    User_id       int64
    User_name     string
    Message_id    int64
    Parent_id     int64
    Show_parent   bool
    Message_Edits int8
    Message_Stars int8
}

type ChatEvents struct {
    Events []ChatEvent
    Time   int64
    Sync   int64
    Ms     int8
}

const (
    Mode         = "Messages"
    ChatUrl      = "http://chat.stackexchange.com/chats/8595/events"
    FKey         = "68f5a3ce293c47399c96ffcd85e0d280" // Go to the chat, F12, reload, look at the /events call and steal its fkey property
    MessageCount = 100                                // Never use this value directly: SE only uses it as a hint and might return a bit more when it feels like it
    Since        = 0
)

var (
    lastMessage int64
)

func main() {
    ticker := time.NewTicker(1 * time.Second)
    quit := make(chan struct{})

    for {
        select {
        case <-ticker.C:
            body := sendRequest()
            parsedJson := parseJson(body)
            newestMessages := getNewestMessages(parsedJson.Events)

            for i := 0; i < len(newestMessages); i++ {
                var currentMessage = newestMessages[i]
                if currentMessage.User_id == -263 || currentMessage.User_id == 125580 {
                    // Ignore Captain Obvious & Duga
                    continue
                }

                fmt.Printf("[%v] %s: %s\n",
                    time.Unix(currentMessage.Time_stamp, 0).Format("15:04:05"),
                    currentMessage.User_name,
                    currentMessage.Content)
            }
        case <-quit:
            ticker.Stop()
            return
        }
    }
}

func sendRequest() (content []byte) {
    response, err := http.PostForm(ChatUrl, url.Values{
        "mode":     {Mode},
        "msgCount": {strconv.Itoa(MessageCount)},
        "fkey":     {FKey},
        "since":    {strconv.Itoa(Since)}})

    if err != nil {
        fmt.Println("Error retrieving response")
        fmt.Println(err.Error())
        return nil
    }

    defer response.Body.Close()
    content, err = ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Error reading response")
        fmt.Println(err.Error())
        return nil
    }

    return
}

func parseJson(body []byte) (parsedJson ChatEvents) {
    err := json.Unmarshal(body, &parsedJson)
    if err != nil {
        fmt.Println("Error parsing json")
        fmt.Println(err.Error())
        return
    }

    return
}

func getNewestMessages(events []ChatEvent) (output []ChatEvent) {
    output = make([]ChatEvent, 0)

    for index := 0; index < len(events); index++ {
        if events[index].Time_stamp > lastMessage {
            events[index].Content = html.UnescapeString(sanitize.HTML(events[index].Content))
            output = append(output, events[index])
            lastMessage = events[index].Time_stamp
        }
    }

    return
}

Disclaimer: I don't know Go.

Error handling

The sendRequest method may fail,
returning nil,
but the caller in main continues happily as if nothing happened.
In fact, looking at the context of the call in main,
my first impression was that sendRequest magically always succeeds,
which is not the case, and so a bit misleading.

Likewise, parseJson may also fail,
parsing nothing,
but from where you call it,
this is not obvious, which is again a bit misleading.

Naming

It seems [the common convention][1] is to use camelCase or PascalCase for names,
no underscores.
So I suggest to rename the fields of the ChatEvent struct.
I'd go as far as to say use PascalCase for types and camelCase for variables, but this is not so clear in the docs.

The variable parsedJson says nothing about what kind of object it is.
So I'd rename it to chatEvents.

Exceptional users

The list of such users would be better in a global set:

if currentMessage.User_id == -263 || currentMessage.User_id == 125580 {
    // Ignore Captain Obvious & Duga
    continue
}

Too wide lines

The line-end comments in the constant definitions make me scroll to the far right to read them.
Even worse,
while reading the code further down,
when I see lines that seem to end near the right end of the text,
the presence of the horizontal scrollbar makes me wonder if there's something more if I scroll right.
And usually there's nothing, as expected, but this is really annoying.
Please avoid line-end comments if they make the line wider than the longest real line of code.
Or better yet, avoid line-end comments if they will make the line exceed 70 characters.


Implementing a zipwithindex predicate in prolog I want to implement a predicate of the form:

zipwithindex(?List1, ?List2)

which is true when the elements of List2 are the same as in List1 but are paired with the index of the element.

This is what I have:

zipwithindex([],I,S,S).
zipwithindex([H|T],I,S0,S):-
  append(S0,[H/I],S1),
  I1 is I+1,
  zipwithindex(T,I1,S1,S).
zipwithindex(List1,List2):-
  zipwithindex(List1,0,[],List2).

Is there a better way to implement this?

sure:

zipwithindex(List1, List2) :-
   findall(E/I, nth0(I, List1, E), List2).

Edit - after Tudor' comment

bagof/3 it's much better than findall/3, as it doesn't introduce unwanted new variables. This can be of utmost importance when working with constrained variables - i.e. CLP(FD) or CHR


Reading SQL query from a resource, with error logging I've created a utility class that expects a logger to be passed at a method level, since I prefer legitimate errors to be written out for troubleshooting later on.  Another developer hates passing the logger to the method, because he does not care.

Cannot use optional attribute, since ILogger is not a constant.
Cannot use params because it would be a singleton, not a collection.

So I implemented it in the following manner:

public static class EmbeddedResourceUtility
{
     public static string GetSqlQuery(string namespaceAndFileNameWithExtension, ILogger logger)
     {
          try
          {
               using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
                   using(var reader = new StreamReader(stream, Encoding.UTF8))
                        return reader.ReadToEnd();
          }

          catch(Exception exception)
          {
               logger.Error($"Failed to read query file {namespaceAndFileNameWithExtension}. {Environment.NewLine}{exception.HResult}: {exception.Message}");
               throw new Exception(exception.Message);
          }
     }
}

Would be incorrect to expect someone to pass an ILogger even if they do not intend to use it?  Or would there be a better way to handle this?

The most unforgivable aspect of this code is that it rethrows a degraded exception.  The original type of the exception (likely an IOException) and the stack trace information are lost when you throw new Exception(…).

Two acceptable approaches are:

Log the failure (if a non-null logger was passed).  Then re-throw the original exception.

 public static string GetSqlQuery(string namespaceAndFileNameWithExtension, ILogger logger)
 {
      try
      {
           using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
           using(var reader = new StreamReader(stream, Encoding.UTF8))
           {
                return reader.ReadToEnd();
           }
      }
      catch (Exception exception)
      {
           logger?.Error($"Failed to read query file {namespaceAndFileNameWithExtension}.{Environment.NewLine}{exception.HResult}: {exception.Message}");
           throw;
      }
 }

Throw a custom exception, wrapping the original exception.

 public static string GetSqlQuery(string namespaceAndFileNameWithExtension)
 {
      try
      {
           using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
           using(var reader = new StreamReader(stream, Encoding.UTF8))
           {
               return reader.ReadToEnd();
           }
      }
      catch (Exception exception)
      {
           throw new EmbeddedResourceException($"Failed to read query file {namespaceAndFileNameWithExtension}", exception);
      }
 }

In this case, requiring an ILogger just isn't worth it.  The caller has all of the information in the EmbeddedResourceException, and can log it if it wants.

I recommend the second approach, because it respects the principle of separation of concerns.


Print initial letter of an entered name Just started learning python and I'm solving some beginner problems. I wrote a solution for a question without any edge cases like user not entering anything, entering numbers etc.:

  Question: Write a program to print initial letter of an entered name?

  Expected output: If the user inputs,

  Ram Chandra Giri -> R.C.Giri
  Ram chandra Giri -> R.C.Giri

My solution works as expected but I would like insight on whether I am following best practice or not and if there is better and easier way to do it. Question is from Class 10 book for students to learn Q-BASIC.

My solution:

def initial_of_name(c):
    word_list = c.split(" ")
    i = (len(word_list) - 1)
    new_list = []
    for w in range(0, i):  # this loop leaves last name and creates a new list.
        word = word_list[w]
        word = word[0:1].upper()  # sliced word into initial letter
        new_list.append(word)
    new_list.append(word_list[-1])  # added last name to the list before joining.
    initial = '.'.join(new_list)
    print("The initial of your name is {0}.".format(initial))
    return

name = input("Please enter your name?\n>")
initial_of_name(name)

In general, I think that's a great start - it's consistently formatted and sensibly structured.

def initial_of_name(c):

c isn't a great name for a parameter, it tells the reader nothing about what the function is expecting to get. It might also be helpful to add a docstring to provide a bit more information.

word_list = c.split(" ")

If you're splitting on spaces, note that you can just use .split(), which will also have the effect of counting consecutive whitespace as a single space. This is helpful if someone accidentally types My  Name instead of My Name; with the current formulation you'd get ['My', '', 'Name'].

i = (len(word_list) - 1)
...
for w in range(0, i):
    word = word_list[w]

Iterating over a list by index in Python is a bit of an anti-pattern, there are lots of better tools for dealing with iteration. In this case, you could iterate over a slice of all but the last item in the list:

for word in word_list[:-1]:

Talking of slicing:

word = word[0:1].upper()

You don't need the 0, that's the default start to a slice, so it could be word[:1]. But what you want is the first character, which is perhaps more clearly expressed as word[0].

new_list = []
for ...:
    ...
    new_list.append(...)

Creating an empty list, iterating and appending is often not the most efficient way to build a new list. Instead, consider a list comprehension (if this is unfamiliar to you, see e.g. Python for-in loop preceded by a variable).

print("The initial of your name is {0}.".format(initial))

In general, I wouldn't use print in a function like this. This is part of separation of concerns; building the appropriate string and displaying the result to the user are two completely different tasks, so they shouldn't be in the same function. Additionally, printing rather than returning the result makes it harder to test the function.

With all of that considered, here's how I would implement the same requirements.

def initial_of_name(name):
    """Converts a name to initials and surname.

    Ensures all initials are capitalised, even if the
    first names aren't.

    Examples:

      >>> initial_of_name('Ram Chandra Giri')
      'R.C.Giri'
      >>> initial_of_name('Ram chandra Giri')
      'R.C.Giri'

    """
    parts = name.split()
    initials = [part[0].upper() for part in parts[:-1]]
    return '.'.join(initials + [parts[-1]])

if __name__ == '__main__':
    name = input("Please enter your name?\n>")
    initial = initial_of_name(name)
    print("The initial of your name is {0}.".format(initial))

If the last part is unfamiliar, see What does if __name__ == "__main__": do?

Note that including examples in the docstring in the form of an interactive Python session not only gives the reader a good idea of exactly how to use the function, but also allows doctest to validate the code and examples for you. If you save the above into a file initial.py:

$ python -m doctest initial.py --verbose
Trying:
    initial_of_name('Ram Chandra Giri')
Expecting:
    'R.C.Giri'
ok
Trying:
    initial_of_name('Ram chandra Giri')
Expecting:
    'R.C.Giri'
ok
1 items had no tests:
    initial
1 items passed all tests:
   2 tests in initial.initial_of_name
2 tests in 2 items.
2 passed and 0 failed.
Test passed.


First project in Javascript: NearestNeighbor Calculator I just finished my first project in Javascript. It takes an array of locations (with coordinates on position 6 and 7) as Input, then the first location is checked against all other locations. After that it takes the closest neighbor and adds it to the route. Then it takes the coordinates of the neighbor which it just found and does same for it (excluding locations that already have a connection). In the end it returns to the starting point. Please give me some hints how i can write better, cleaner and more readable code. Any feedback is appreciated.

var listCoordinates = [
  [1, "München", "Robert-Bürkle-Straße", "1", 85737, "Ismaning", 48.229035, 11.686153, 524, 854],
  [2, "Berlin", "Wittestraße", "30", 13509, "Berlin", 52.580911, 13.293884, 648, 302],
  [3, "Braunschweig", "Mittelweg", "7", 38106, "Braunschweig", 52.278748, 10.524797, 434, 341],
  [4, "Bretten", "Edisonstraße", "2", 75015, "Bretten", 49.032767, 8.698372, 276, 747],
  [5, "Chemnitz", "Zwickauer Straße", "16a", 9122, "Chemnitz", 50.829383, 12.914737, 622, 525],
  [6, "Düsseldorf", "Gladbecker Straße", "3", 40472, "Düsseldorf", 51.274774, 6.794912, 138, 455]
];
//Haversine formula: calulate distance between two locations
const haversineDistance = ([lat1, lon1], [lat2, lon2], isMiles = false) => {
  const toRadian = angle => (Math.PI / 180) * angle;
  const distance = (a, b) => (Math.PI / 180) * (a - b);
  const RADIUS_OF_EARTH_IN_KM = 6371;
  const dLat = distance(lat2, lat1);
  const dLon = distance(lon2, lon1);
  lat1 = toRadian(lat1);
  lat2 = toRadian(lat2);
  //Haversine Formula
  const a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
  const c = 2 * Math.asin(Math.sqrt(a));
  let finalDistance = RADIUS_OF_EARTH_IN_KM * c;
  if (isMiles) {
    finalDistance /= 1.60934;
  }
  return finalDistance;
};
//heuristic strict nearest neighbor (points that already have a connection do not get calculated)
function nearestNeighbor(coordinates) {
  var route = {
    msg: '',
    distance: 0,
    route: [0]
  }
  var currentPoint = 0;
  for (var i = 0; i <= coordinates.length - 2; i++) {
    var nearestNeighbor = {
      key: 0,
      distance: 0
    }
    var pointaLat = coordinates[currentPoint][6],
      pointaLon = coordinates[currentPoint][7];
    for (var j = 0; j <= coordinates.length - 1; j++) {
      if (j != currentPoint) {
        if (!route.route.includes(j)) {
          var pointbLat = coordinates[j][6],
            pointbLon = coordinates[j][7];
          var currentDistance = haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0);
          if (nearestNeighbor.distance === 0 || nearestNeighbor.distance > currentDistance) {
            nearestNeighbor.key = j;
            nearestNeighbor.distance = currentDistance;
          }
        }
      }
    }
    route.distance += nearestNeighbor.distance;
    route.route.push(nearestNeighbor.key)
    currentPoint = nearestNeighbor.key;
  }
  //return to start point
  var pointaLat = coordinates[0][6],
    pointaLon = coordinates[0][7],
    pointbLat = coordinates[route.route[route.route.length - 1]][6],
    pointbLon = coordinates[route.route[route.route.length - 1]][7];
  route.distance += haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0);
  route.route.push(0);
  route.distance = Math.round((route.distance + Number.EPSILON) * 100) / 100;
  route.msg = "Die kürzeste Strecke beträgt " + route.distance + " km";
  return route;
}

console.log(nearestNeighbor(listCoordinates));

Are you hoping for the arc length around a sphere or the Earth? What about going through the earth in a straight line? Currently your math solves the sphere but not Earth.
The earth has 2 radi that are used to solve the arc length.
R = √ [ (r1² * cos(B))² + (r2² * sin(B))² ] / [ (r1 * cos(B))² + (r2 * sin(B))² ]
B = Latitude
R = Radius
r1 = radius at equator
r2 = radius at the poles

But your Haversine method is otherwise correct =D


Check if an element is present within a linked list I am given a task to ask for a number and then check if it is present within a linked list or not.

class Node:
    def __init__(self,item):
        self.data = item
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self, newnext):
        self.next = newnext

class Linkedlist:
    def __init__(self):
        self.head = None

    def add_member(self,data):
        temp = Node(data)
        temp.setNext(self.head)
        self.head = temp

    def search_member(self,item):
        current = self.head
        while current != None:
            if current.getData() ==item:
                return True
            else:
                current =current.getNext()
        return False

llist = Linkedlist()
llist.add_member(23)
llist.add_member(98)
llist.add_member(415)
llist.add_member(123)
llist.add_member(981)
llist.add_member(454)
llist.add_member(213)
llist.add_member(198)
llist.add_member(455)
llist.add_member(253)
llist.add_member(978)
llist.add_member(45)
llist.add_member(203)
llist.add_member(918)
llist.add_member(45)
item = int(raw_input("Enter the number you want to search : "))
print llist.search_member(item)

How can I improve this code?

First, you need to realize that Python is not Java. Python is a "consenting adult language." (Watch Raymond Hettinger's talk for more.)

What that means is the bizarre fetish for mutators/accessors/getters and setters that permeates Java and C# doesn't exist in Python. You don't need to write:

class Node:
    def getData(self):
    def getNext(self):
    def setData(self,newdata):
    def setNext(self, newnext):

Instead, you can just write this:

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

And let people access node.data and node.next directly. (Python provides a mechanism, @property, for dealing with the case where you want to turn a member access into a function call. But it's not the first thing to do.)
The next thing that struck me about your code was this:

llist = Linkedlist()
llist.add_member(23)
llist.add_member(98)
llist.add_member(415)
llist.add_member(123)

That's a lot of letters to get 4 numbers into a list. You can, and should, do better!

"How can I do this better," you ask? Well, post it on CodeReview of course! But also, consider how the Python list class (and set, and dict, and tuple, and ...) is initialized. And how the Mutable Sequence Types are expected to work.

Because your code is implementing a "mutable sequence type." So there's no reason that your code shouldn't work the same way. In fact, if you want other people to use your code, you should try to produce as few surprises as possible. Conforming to an existing interface is a good way to do that!
Create an initializer that takes a sequence.

class LinkedList:
    def __init__(self, seq=None):
        ...
        if seq is not None:
            self.extend(sequence)

Implement as many of the mutable sequence operations as possible.
Use the standard method names where possible: clear, extend, append, remove, etc.
Implement special dundermethods (method names with "double-underscores" in them: double-under-methods, or "dundermethods") as needed to make standard Python idioms work:

def __contains__(self, item):
    for i in self:
        ...

def __iter__(self):
    node = self.head

    while node:
        yield node.value
        node = node.next

Implement your test code using standard Python idioms, to prove it's working:

llist = LinkedList([23, 98, 415, 123, 981, 454, 213, 198, ...])

while True:
    item = int(raw_input("Enter a number to search for: "))

    if item in llist:
        print "It's in there!"
    else:
        print "Sorry, don't have that one."


Null check when enabling Up navigation in Android This upvoted SO answer and this upvoted SO answer both check for null in a similar way: they call a function in the if or assert statement and "throw away" the result and then call the same method again in the success clause and operate on the result.

I am new to Android development and have limited knowledge of Java, but my experience in other languages (and every bone in my body) tells me it would be better to store the result of the function in a local variable, test that in the if statement and then use that local variable value in the success clause like this:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Am I missing something (because the answers on SO are upvoted and no-one has suggested this alternative); is my suggestion above flawed in Java?

Assuming java conventions are being followed, methods that begin with get should return an already-computed value with no business logic performed. In that case, the only real 'cost' tradeoff is the overhead of a second method call vs. the memory for new pointer to the value. Both should be insignificant. It's generally a matter of style as to which approach is preferable.


Project Euler #4 (largest palindrome product) in Swift A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit numbers.

What I've so far learned about Swift is that while the Playground is very cool for tinkering around, it definitely does not like big loops.  So this time, I coded parts in the playground, but moved it over to an actual executable project to run the final code.

I'm interested in knowing any Swift tricks I missed.  I did implement a new trick I learned in this solution, the stride feature.

import Foundation

func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed for \(title): \(timeElapsed) s")
}

extension Int {
    func isPalindrome() -> Bool {
        return self == self.reversed()
    }

    func reversed() -> Int {
        var original: Int = self
        var reversed: Int = 0

        while original > 0 {
            reversed *= 10
            reversed += original % 10
            original /= 10
        }

        return reversed
    }
}

func largestPalindrome() {
    var left: Int = 999
    var right: Int = 999

    var largestPalindrome: Int = 0

    for left in stride(from: 999, through: 100, by: -1) {
        for right in stride(from: left, through: 100, by: -1) {
            let product: Int = left * right
            if product > largestPalindrome && product.isPalindrome() {
                largestPalindrome = product
            }
        }
    }

    println(String(largestPalindrome))
}

printTimeElapsedWhenRunningCode("Largest Palindrome", largestPalindrome)

The printTimeElapsedWhenRunningCode function is borrowed from Brad Larson's answer here, and on my computer, it says the code is running in about 0.27 to 0.28 seconds.

Style

The reversed() function is only called from the isPalindrome function. Since the isPalindrome function is a 1-liner, it strikes me that there is no value added by exposing the reversed functionality at all, and that it can all be emedded in to the isPalindrome() call. There is no need for the method extraction in this case, it is overkill, and adds no significant value, while adding bulk to an extension on Int.

The problem constant 999 strikes me as being a good candidate for an input parameter. Instead you have encoded it as a magic number (three times) in the largestPalindrome() method. I feel it is more natural to have the input defined in the same way as the problem, use 3-digit numbers:

func largestPalindrome(limit: Int) -> Int {

note, the function receives the input limit, and it also returns the largestPalindrome from that limit. Note that the single-responsibility principle suggests that a function should return the value, and that you should print the result outside the function. The print in the function is.... ugly.

The code to turn the value 3 (for 3 digit numbers), would be:

limit max (exclusive) \$10^3\$
limit min (inclusive) \$10^{(3 - 1)}\$

Performance

There is a trivial, but effective optimization available for you, by breaking the inner loop when the product will always be less than the previously found largest.

Consider the code:

for left in stride(from: 999, through: 100, by: -1) {
    for right in stride(from: left, through: 100, by: -1) {
        let product: Int = left * right
        if product > largestPalindrome {
            if product.isPalindrome() {
                largestPalindrome = product
            }
        } else {
            break
        }
    }
}

In the above code, there is no point in testing smaller right values if they will never beat the current largest palindrome.


Java Recursive Depth First Search I've created a recursive depth-first search implementation in Java as an example for an article I am writing on my website. It needs to be concise in order to fit on the page easily (independent of screen sizes), hence the lack of extra spacing.

public static boolean depthFirstSearch(TreeNode find, TreeNode top){
   if(top == null || find == null) return false;
   else if(top.equals(find)) return true;
   Enumeration children = top.children();
   while(children.hasMoreElements()){
       TreeNode next = (TreeNode) children.nextElement();
       if(depthFirstSearch(find, next)){
           return true;
       }
   }
   return false;
}

I am using javax.swing.tree.TreeNode so that I don't have to include any custom node implementations and the search is only looking for the presence of a node, not position.

The context of this code example is not very clear, so in my remarks below I will suppose that the code is about a generic implementation of depth-first search.

TreeNode

If this is a generic implementation, my first question then is why TreeNode interface is there? This interface is part of Swing API, which has it own sphere of application. The objects implementing this interface may (or may not) be convenient here; anyway, they tend to be used in Swing/GUI-related situations and I'd not interfere with their scope for a generic case.

There is also something even more important concerning TreeNode. As you know, it has children() method which returns an Enumeration. This type is a very old Java thing (since JDK1.0), introduced even before Collections, and currently it looks like a rudiment. And it's not very pleasant to iterate on.

But if you still need/want to keep TreeNode, a type bound mark Enumeration<TreeNode> should be added, in order to avoid compilation warnings.

To replace TreeNode, I'd suggest to create a short and concise Node class, which points to a Collection (or even a Stream) of children Nodes and overrides hashCode and equals methods. This class would also be useful in other examples of your article.

Code Blocks

I understand that conciseness and lack of extra space is the priority in this code, but when I see this

if(top == null || find == null) return false;
else if(top.equals(find)) return true;

it looks for me more like code obfuscation. Please find a place to use braces:

if (top == null || find == null) {
    return false;
}
else if (top.equals(find)) {
     return true;
}

It can be very confusing and error-prone when the instruction that immediately follows a condition is not wrapped in a block.


Python code to guess the roots of any integer I'm new to programming and python,this one of my biggest codes in python yet...
I just wanted to know if you can simplify it further...
English is not my first language, so corrections in the language are also welcomed!
Thank You In advance!
x = int(input('Enter an integer who\'s root value you need: '))

e = int(input('Enter an +ve integer for root value: '))

#Removing the possiblities of zero in eihter of the variables

if x==0:
    print('Zero power anything is zero!')
elif e==0:
    print('Anything power zero is one!')
else:
    while e < 0:
        print('I SAID +VE INTEGER FOR ROOT!')
        x = int(input('Enter an integer who\'s root value you need: '))
        e = int(input('Enter an +ve integer for root value: '))

    while e %2 == 0 and x < 0:
        print('-ve nos. can\'t have root value for even roots!')
        x = int(input('Enter an integer who\'s root value you need: '))
        e = int(input('Enter an +ve integer for root value: '))
    epsilon = 0.0000001
    numGuesses = 0
    if x>0:
        low = -x
    elif x<0:
        low = x
    if x>0:
        high = max(1.0,x)
    elif x<0:
        high = max(1.0,-x)
    ans = (high + low)/2.0
    while abs(ans**e - x) >= epsilon:
        print('low =', low, 'high =', high, 'ans =', ans)
        numGuesses += 1
        if ans**e < x:
            low = ans
        else:
            high = ans
        ans = (high + low)/2.0
    print('numGuesses =', numGuesses)
    print(ans, 'is close to the value of', e, 'root', x)

Ignoring points already made in comments...
Escapes
x = int(input('Enter an integer who\'s root value you need: '))
I find reading this line of code jarring.  There is an escape \' in the middle of the string.  Python gives many different types of literal strings with allow you to embed special characters in strings without using escapes.  At the simplest end of the spectrum, a double-quoted string will allow you to embed a single quote without an escape.
x = int(input("Enter an integer who's root value you need: "))
There are also triple-quoted strings """...""" or '''...''' both of which will allow you to embed unescaped single and double quotes, as well as new lines.  You don't need this here, but it is good to be aware of.
Input Validation
Your validation has holes.
At the first pair of prompts, enter "1" and "-1".  This causes you to enter the while e < 0: loop, where you can enter another pair, like "-1" and "2".  This will cause you to enter the while e %2 == 0 and x < 0: loop, where you can enter "0" and "0".
At this point, x is neither greater than or less than zero, so neither low nor high are assigned a value, causing an exception at ans = (high + low)/2.0
You want the earlier tests to be repeated for the new inputs.  This is easiest achieved with a single while loop around the input.
while True:
    x = int(input("Enter an integer who's root value you need: "))
    e = int(input("Enter an +ve integer for root value: "))

    if e < 0:
        print("I SAID +VE INTEGER FOR ROOT!")
    elif e % 2 == 0 and x < 0:
        print("-ve nos. can't have root value for even roots!")
    else:
        # The input is now good, exit the while-loop.
        break

if x==0:
    print("Zero power anything is zero!")
elif e==0:
    print("Anything power zero is one!")
else:
    epsilon = 0.0000001
    numGuesses = 0
    ...

Now, the input is requested.  If it fails either test, the while loop repeats, and all the validation checks are repeated with the new input.
Exceptions
If the user enters a non-integer value, int(...) will raise an ValueError exception.  You could be kind and capture that as well.
while True:
    try:
        x = int(input("Enter an integer who's root value you need: "))
        e = int(input("Enter an +ve integer for root value: "))

        if e < 0:
            print("I SAID +VE INTEGER FOR ROOT!")
        elif e % 2 == 0 and x < 0:
            print("-ve nos. can't have root value for even roots!")
        else:
            # The input is now good, exit the while-loop.
            break
    except ValueError:
        print("Only integer values are permitted.")

if x == 0:
    ...
...

Unnecessary conditionals
    if x>0:
        low = -x
    elif x<0:
        low = x
    if x>0:
        high = max(1.0,x)
    elif x<0:
        high = max(1.0,-x)

You are testing x>0, x<0, x>0, and x<0.  We can remove half of these, by combining the two if-elif statements:
    if x>0:
        low = -x
        high = max(1.0,x)
    elif x<0:
        low = x
        high = max(1.0,-x)

This is arguably clearer.  But the second test, x<0 is unnecessary.  We've already checked for x == 0 earlier, and now have just tested x>0.  The only other possibility is x < 0, so we can get away with just an else:
    if x>0:
        low = -x
        high = max(1.0,x)
    else:
        low = x
        high = max(1.0,-x)

PEP 8
The Style Guide for Python Code lists many conventions which Python programs should follow, for maximum readability by other Python programmers.

Binary operators should be surrounded by one space.  For instance, you should write x == 0, e % 2 == 0, x > 0 and (...) / 2.0 instead of x==0, e %2 == 0, x>0 and (...)/2.0.
snake_case should be used for function names and variables.  For example, num_guesses instead of numGuesses.
constants should be in UPPER_CASE.  For example, EPSILON = 0.000_000_1 instead of epsilon = 0.0000001 if the value never changes.
Use _ in long numerical constants to group digits for easier readability, as in above example.
Commas should be followed by a space.  For instances, max(1.0, x) instead of max(1.0,x).


Printing a Tic-Tac-Toe board in Ruby I have two implementations of a function that prints out a basic board for Tic-Tac-Toe.

Which of these should I include and why?

def display_board(board)
  for i in 0...9
    print " #{ board[i] }"
    if (i+1)%3 != 0
      print " |"
    elsif i != 9
       print " \n#{'-'*11}\n"
    end
  end
end

def display_board(board)
  puts " #{board[0]} | #{board[1]} | #{board[2]} "
  puts "-----------"
  puts " #{board[3]} | #{board[4]} | #{board[5]} "
  puts "-----------"
  puts " #{board[6]} | #{board[7]} | #{board[8]} "
end

Surely version two.

It makes no use of control structures such as for or if, it has very low Kolmogorov complexity because of that, and it is good, as it is directly related to difficulty in understanding.
It lets you see in a single glance what the output will look like.


Showing or hiding groups of three text fields

        <input id="input0_0" class="input" type="text" />

        <input id="input0_1" class="input" type="text" />

        <input id="input0_2" class="input" type="text" />

        <input id="input1_0" class="input" type="text" />

        <input id="input1_1" class="input" type="text" />

        <input id="input1_2" class="input" type="text" />

        <input id="input2_0" class="input" type="text" />

        <input id="input2_1" class="input" type="text" />

        <input id="input2_2" class="input" type="text" />

add-more remove-last</>

js part that we need to deal with:

$("#inputRow1").hide();
$("#inputRow2").hide();
$("#remove-last").hide();

$("#add-more").click(function(){

    //count how many *direct children* elements are hidden.
    var hiddenElements = $('#members >:hidden').length;

    $("#remove-last").show();

    if (hiddenElements === 2) {
        $("#inputRow1").show();
    } else if(hiddenElements === 1) {
        $("#inputRow2").show();
        $(this).hide();
    }
});

$("#remove-last").click(function(){

    //count how many *direct children* elements are hidden.
    var hiddenElements = $('#members >:hidden').length;
    $("#add-more").show();

    if (hiddenElements === 0) {
        $("#inputRow"+2).hide();
    } else if (hiddenElements === 1) {
         $("#inputRow"+hiddenElements).hide();
        $(this).hide();
    }

});

Working example:
http://jsfiddle.net/URkuW/

What problem are you trying to solve? I've left your code doing the same things but rather than interrogate the DOM each time I've cached everything in local variables.

// Execute code in an Immediately Invoked Function Expression (IIFE)
// This helps stop your variables polluting the global scope.
(function () {

    // opt in to ECMAScript 5's strict mode
    "use strict";

    // As we aren't changing the DOM just store all of the selectors in
    // local variables - it's cheaper than hitting the DOM each time.
    var inputRow1 = $('#inputRow1').hide(),
        inputRow2 = $('#inputRow2').hide(),
        addRowLink = $('#add-more'),
        removeRowLink = $("#remove-last").hide(),
        // rather than checking the DOM for number of hidden children,
        // just keep track of the last row visible (0, 1 or 2)
        lastRowVisible = 0;

    addRowLink.click(function(event) {
        // stop the default action of the click event.
        event.preventDefault();

        // This is the initial state with only the first 3 input boxes showing
        // we need to show row 1 and the remove last link as well as increment the
        // last row visible to 1.
        if (lastRowVisible === 0) {
            removeRowLink.show();
            inputRow1.show();
            ++lastRowVisible;
        // The first two rows are visible. Show the last row and hide the add-more
        // link as well as increment the last row visible to 2.
        } else if (lastRowVisible === 1) {
            addRowLink.hide();
            inputRow2.show();
            ++lastRowVisible;
        }
    });

    removeRowLink.click(function(event){
        // stop the default action of the click event.
        event.preventDefault();

        // All 3 rows currently visible: need to hide the last row, show
        // the add-more link and decrement the last row visible to 1.
        if (lastRowVisible === 2) {
            addRowLink.show();
            inputRow2.hide();
            --lastRowVisible;

        // 2 rows currently visible: need to hide the second row and the
        // remove-last link and decrement the last row visible to 0.
        } else if (lastRowVisible === 1) {
            removeRowLink.hide();
            inputRow1.hide();
            --lastRowVisible;
        }
    });
}());

Here's a working fiddle: http://jsfiddle.net/RobH/CDVBs/1/

Have you considered a solution that starts with only 3 inputs and then creates extra inputs instead of showing ones that are already declared but hidden?


Store a hash in a cookie to identify the user's account to keep logged in after close browser I made a option to user choose to stay logged in even after he closes the browser. It's really simple to implement, but i'm not sure about the hash i used to identify the user that is stored in a cookie.

To generate the hash i used bin2hex(random_bytes(59/2)) this function generate a string like this one:

118f9bc738e28b5079cf04bc3c88b2754f8ae04c9f1e1127d020389c49

To make sure that it's unique for each user, before register new accounts i check all hashes that i already have in my database.

I only use this hash to identify the user using the cookie, is it safe? The lenght of the hash is good enough to a Brute force attack be impossible, right?

What do you guys think about my code?

register.php

$hash = bin2hex(random_bytes(59/2));

login.php

##
## Get data from database using $_POST variable from <form>
##
if(!empty($_POST['stay_loggedIn'])){
  setcookie('stay_loggedIn', $fetch_data['hash'], strtotime('+14 days'), '/');
}

index.php

if(!empty($_COOKIE['stay_loggedIn']) && empty($_SESSION['logged_cookie'])){

    ## Set this session variable to run this code only one time
    $_SESSION['logged_cookie'] = 1;

    $hash = $_COOKIE['stay_loggedIn'];
    $logeIn = $conn->prepare("SELECT * FROM users WHERE `hash` = :hash");
    $logeIn->bindValue(':hash', $hash, PDO::PARAM_STR);
    $logeIn->execute();
    $user_data = $logeIn->fetch(PDO::FETCH_ASSOC);
    ##
    ## Set session variables
    ##
}

logout.php

$params = session_get_cookie_params();
setcookie('stay_loggedIn', '', time() - 3600, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));

I think this is a bad approach on two fronts (the second one is more important):

Having to check a randomly generated 'hash' against the database, to see if it has been used before, is inefficient. First of all, this is not a hash, it's a random string. A hash is created from something sensible, to verify it later. Can I assume you already have an unique identifier for each user in your database? You could store that in the cookie, it tells you which user it is. User id's don't need to be a secret. However, you don't want someone to change it and see information from another to user. To prevent this, you could add a small random string to the cookie, and in your database, to verify that they are who they say they are. Such a string is called a 'token'. An user is only valid if the user id and the token in the cookie match with the id and token in the database. Your queries will now probably be quicker because you can use the user id to look up the token.
Staying 'logged in' after closing the browser is done by not erasing the session cookie when the browser closes. It's as simple as that. See: https://www.php.net/manual/en/function.session-set-cookie-params.php (see 'lifetime', it defaults to 0).


Instead of writing two cases depending on the length of the chunk, you could certainly make one general way for each task. Doing so you simplify the code inside maxAtIntervals and get rid of findmax (as you can use .sort().slice(-n) to get the max n numbers).

The return of maxAtIntervals is [values]. If values is already an array, why would you create an array of 1 array?

There are so many comments I could not even focus on the code. Be succinct!

After applying this changes and removing unnecessary variables, the function looks like this:

function maxAtIntervals (intervalLength, grab, xs) {
    const comparator = (a, b, _) => a - b;
    const temp = [];

    for (var i = 0; i < xs.length; i += intervalLength) {
        const interval = xs.slice(i, i + intervalLength);
        temp.push(interval.sort(comparator).slice(-grab));
    }

    return temp;
}

Your original code makes 111ms on my machine. After my changes it goes to 51ms.


Project Euler # 29: Distinct powers in Python Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

  2 ** 2 = 4, 2 ** 3 = 8, 2 ** 4 = 16, 2 ** 5 = 32
  3 ** 2 = 9, 3 ** 3 = 27, 3 ** 4 = 81, 3 * 5 = 243
  4 ** 2 = 16, 4 ** 3 = 64, 4 ** 4 = 256, 4 ** 5 = 1024
  5 ** 2 = 25, 5 ** 3 = 125, 5 ** 4 = 625, 5 ** 5 = 3125

  If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

  4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

  How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

from time import time

def distinct_terms(n):
    """Assumes n an integer > 1.
    returns the sequence generated of a ** b for a and b in range(n)"""
    return (x ** y for x in range(2, n + 1) for y in range(2, n + 1))

if __name__ == '__main__':
    time1 = time()
    print((len(set(distinct_terms(100)))))
    print(f'Time: {time() - time1}')

Your docstring is misleading.

The function does not return a sequence; it returns a generator.
It states “for a and b in range(n)”, which is incorrect.  They are in range(2, n+1).  If you don’t want to confuse the issue with range() excluding the last value, say “for a and b in the range from 2 to n, inclusive”.
The problem refers to a “sequence”, where the values are in ascending order and duplicates have been removed, which is completely different from the sequence of values produced by the generator, which is not sorted and can have duplicates.

time1 is a terrible variable name; there is no time2.  Perhaps use start_time.

print((len(...))) has an unnecessary extra pair of parenthesis.

Is distinct_terms(n) too specific of a function?  Perhaps distinct_terms(m, n) could be more general, where you can generate terms for m <= a,b <= n, instead of always the lower limit of m=2.  Or with separate limits for the a and b values.

Python is an easy language to solve this problem in, because \$100^{100}\$ is just another integer in Python, despite having 201 digits.  If you were to solve this in another programming language, one where integers were restricted to (say) 128 bits, what would you do?

With 99 different values for a and b, you have \$99^2 = 9801\$ different \$a^b\$ expressions.  How many of those will be equivalent?  Ie, \$a^b = c^d\$?  For example, \$2^4 = 2^{2*2} = {(2^2)}^2 = 4^2\$.  Can you generalize that?  Can you count the number of occurrences where that happens, and subtract that from 9801?