texts: Basic web app that returns a JSON of information

texts:
My web application can take URL-encoded strings and return a JSON that contains information, like API calls.

My main concerns are with security. I need a cheap and easy (but secure) way to do certain commands. This part is handled by the adminhandle section of the code. My code is currently designed to be able to be deployed on a heroku app, but simply changing:

port = int(os.environ.get('PORT', 17995))

at line 12 to:

port = 80

should be fine, allowing you to access this server from http://localhost. Inside the code itself contains a hashed password and a salt. The password I use I generated with the random module (perhaps it is worth noting, since there are "more secure" RNGs out there).

My server is currently operational at here.

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import ssl, reactor
from twisted.python.modules import getModule
import urllib.parse
import cgi
import json
import os
import hashlib
admin_salt = ''
realpass = ''
port = int(os.environ.get('PORT', 17995))
class FormPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        out = {}
        print(request.uri)
        x = (request.uri).decode('ascii')
        x = x[1:]
        x = todi(x)
        request.setHeader('Content-Type', 'text/plain; charset=UTF-8')
        valid = False
        if 'adminaccess' in x:
            vlr = adminhandle(x)
            out.update({'ADMIN':vlr[0]})
            if len(vlr) != 1:
                out.update({'CMDRES':vlr[1]})
        if 'key' in x:
            if x['key'] == 'chess':
                valid = True
                out.update({'my_name':'Bob'})
        out.update({'success':valid})
        return json.dumps(out).encode('UTF-8')

##    def render_POST(self, request):
##        x = request.content.read()
##        print(x)
##        return x

def todi(st):
    if len(st) == 0:
        return '{}'
    if st[len(st)-1] == '/':
        st = st[:-1]
    if len(st) == 0:
        return '()'
    if st[0] == '?':
        st = st[1:]
    st = urllib.parse.parse_qsl(st)
    return dict(st)

def adminhandle(di):
    rawupass = (admin_salt+di['adminaccess']).encode('ascii')
    hashupass = hashlib.sha512(rawupass).hexdigest()
    result = [False]
    if hashupass == realpass:
        #access granted!
        del result[0]
        result.append(True)
        if 'command' in di:
            if di['command'] == 'listdir':
                result.append(str(os.listdir(os.getcwd())))
    return result

#certData = getModule(__name__).filePath.sibling('server.pem').getContent()
#certificate = ssl.PrivateCertificate.loadPEM(certData)
factory = Site(FormPage())
reactor.listenTCP(port, factory)
#reactor.listenSSL(443, factory, certificate.options())
reactor.run()


texts:
I have created a simple component in Swing that lets me place other components such as buttons on top of each other.

They fill their parent horizontally but not vertically, which is exactly as I want it. I called this parent component VerticalPanel and this is how it looks:

I can't shake the feeling though that there could be a more elegant solution. Especially the need for my VerticalPanel to know the number of components it will hold in advance is something I'm not entirely happy with.

Here's the VerticalPanel:

public class VerticalPanel extends JPanel {
    private static final long serialVersionUID = 1L;

    public VerticalPanel(int nrOfComps) {
        LayoutManager layout = getVerticalLayout(nrOfComps);
        setLayout(layout);
    }

    @Override
    public Component add(Component comp) {
        return add(comp, getComponentCount());
    }

    @Override
    public Component add(Component comp, int index) {
        final GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        // Allocate extra width to the buttons
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.NORTH;
        gbc.gridx = 0;
        gbc.gridy = index;
        add(comp, gbc);
        return comp;
    }

    private LayoutManager getVerticalLayout(int nrOfComps) {
        GridBagLayout layout = new GridBagLayout();

        double[] rowWeights = new double[nrOfComps];
        rowWeights[nrOfComps - 1] = Double.MIN_VALUE;
        layout.rowWeights = rowWeights;
        return layout;
    }
}

This creates the example from the screenshot above:

public class VerticalButtons {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager
                            .getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException
                        | IllegalAccessException
                        | UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame();

        frame.getContentPane().add(createVerticalButtons());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);
    }

    private static JComponent createVerticalButtons() {

        VerticalPanel buttons = new VerticalPanel(2);

        JButton b1 = new JButton("1");
        JButton b2 = new JButton("2");
        buttons.add(b1);
        buttons.add(b2);

        return buttons;
    }
}


texts:
I just wrote my first Nim module and was hoping someone with some experience with Nim or similar languages could take a look. In particular I was hoping someone could speak if the use of template is idiomatic (or if they'd be better as a proc) as I have no experience using them in any other programming language.

I was also curious if it'd be a good idea to macro the two add implementations to reduce the amount of redundant code

import macros

type
  RingBuffer*[T] = object
    ## A ring buffer is a sequence-like type which can store
    ## up to `length` elements. After `length` elements are
    ## added to the buffer, new items will begin to replace
    ## the oldest ones (i.e. the elements at the start of the
    ## buffer).
    data: seq[T]
    # indicates where elements should be positioned in data
    head, tail: int
    size, length*: int

template adjustHead(b: expr): stmt =
  b.head = (b.length + b.tail - b.size + 1) mod b.length;

template adjustTail(b, change: expr): stmt =
  b.tail = (b.tail + change) mod b.length

proc newRingBuffer*[T](length: int): RingBuffer[T] =
  ## Construct a new Ringbuffer which can hold up to `length` elements
  let s = newSeq[T](length)
  RingBuffer[T](data: s, head: 0, tail: -1, size: 0, length: length)

proc `[]`*[T](b: RingBuffer[T], idx: int): T {.inline} =
  ## Get an item at index (adjusted)
  b.data[(idx + b.head) mod b.length]

proc `[]=`*[T](b: var RingBuffer[T], idx: int, item: T) {.raises: [IndexError].} =
  ## Set an item at index (adjusted)
  if idx == b.size: inc(b.size)
  elif idx > b.size: raise newException(IndexError, "Index " & $idx & " out of bound")

  b.data[(idx + b.head) mod b.length] = item

proc len*(b: RingBuffer): int = b.size

proc add*[T](b: var RingBuffer[T], item: T) =
  ## Add an element to the buffer
  adjustTail(b, 1)
  b.data[b.tail] = item
  b.size = min(b.size + 1, b.length)
  adjustHead(b)

proc add*[T](b: var RingBuffer[T], data: openArray[T]) =
  ## Add elements to the buffer
  for item in data:
    adjustTail(b, 1)
    b.data[b.tail] = item
  b.size = min(b.size + len(data), b.length)
  adjustHead(b)

proc pop*[T](b: var RingBuffer[T]): T =
  ## Remove an element from the buffer and return it
  result = b.data[b.tail] # Note: will throw error if oob
  adjustTail(b, -1)
  b.size -= 1
  adjustHead(b)

iterator `items`*[T](b: RingBuffer[T]): T =
  for i in 0..b.size - 1:
    yield b[i]

iterator `pairs`*[T](b: RingBuffer[T]): tuple[a: int, b: T] =
  for i in 0..b.size - 1:
    yield (i, b[i])

proc `@`*[T](b: RingBuffer[T]): seq[T] =
  ## Convert the buffer to a sequence
  var s = newSeq[T](b.size)
  for i, item in b:
    s[i] = item
  result = s

converter toSeq*[T](b: RingBuffer[T]): seq[T] = @b


texts:
Please review my Queue implementation and let me know if you have any suggestions. I am not returning an exception for any of the methods defined here. As we know the exception is thrown only for add and remove functions and not for poll or offer functions.

    public class QueueImplementation<T> {
    private QueueNode<T> first;
    private QueueNode<T> last;
    private int size;

    private static class QueueNode<T> {
        private T val;
        private QueueNode<T> next;

        public QueueNode(T val) {
            this.val = val;
            this.next = null;
        }

        public void setNext(QueueNode<T> nextNode) {
            next = nextNode;
        }

        public QueueNode<T> getNext() {
            return next;
        }

        public T getValue() {
            return val;
        }

        @Override
        public String toString() {
            if(val == null) {
                return "null";
            }
            return val.toString();
        }

    }

    public void offer(T val) {
        QueueNode<T> cur = new QueueNode(val);
        if(size == 0) {
            cur.setNext(first);
            first = cur;
            last = cur;
            size++;
            return;
        }

        last.setNext(cur);
        last = cur;
        size++;
    }

    public T peek() {
        if(!isEmpty()) {
            return first.getValue();
        }
        else {
            return null;
        }
    }

    public QueueNode<T> poll() {
        if(isEmpty()) {
            return null;
        }

        QueueNode<T> cur = first;
        first = first.getNext();
        size--;
        return cur;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        size = 0;
        first = null;
        last = null;
    }

    public int size() {
        return size;
    }

    @Override
    public String toString() {
        if(size == 0) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder();
        QueueNode<T> cur = first;
        sb.append(cur.getValue() + "<-");

        while(cur.getNext() != null && !cur.equals(last)) {
            sb.append(cur.getNext().getValue() + "<-");
            cur = cur.getNext();
        }

        return sb.append("null").toString();
    }

    public static void main(String[] args) {
        QueueImplementation<Integer> q = new QueueImplementation<>();
        System.out.println(q.size());
        System.out.println(q.poll()); //returns null;
        System.out.println(q.peek()); //return null;
        q.offer(1);
        q.offer(10);
        q.offer(100);
        System.out.println(q.size());
        System.out.println(q.peek());
        System.out.println(q.poll());
        System.out.println(q.size());
        System.out.println(q.peek());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.size());
        System.out.println(q.poll());
    }
}


texts:
I am writing a control that has a toggle on (show/hide password). The UITextfield has a UIImageView in that acts as the toggle.

The question is, is it better to create the state images once and store them in the control, or to create them on demand?

Essentially this:

if let imageView = imgToggle {
    if self.isSecureTextEntry {
        imageView.image = UIImage(named: "eye.png")
    } else {
        imageView.image = UIImage(named: "no_eye.png")
    }
}

vs this:

private var showPassword: UIImage? = UIImage(named: "eye.png")
private var hidePassword: UIImage? = UIImage(named: "no_eye.png")

///...

if let imageView = imgToggle {
    if self.isSecureTextEntry {
        imageView.image = showPassword
    } else {
        imageView.image = hidePassword
    }
}

Is there any overhead in constantly recreating the image? How does that compare to storing the image in the control?


texts:
I'm working on a game with Slick2D and am just working through the Entity class. I'm making every variable protected and then accessing them with getters and setters. Yet it feels like I'm over-complicating things and it is more efficient to simply let some of these properties be public.

public abstract class Entity {
    protected Point location;
    protected Vector2f vector;
    protected boolean visible;
    protected Image image;

    public Entity() {
        location = new Point();
        vector = new Vector2f();
    }

    public void setLocation(int x, int y) {
        location.setX(x);
        location.setY(y);
    }

    public void setVelocity(int vx, int vy) {
        vector.x = vx;
        vector.y = vy;
    }
    public void update(){
        location.setX(Math.round(location.getX() + vector.x));
        location.setY(Math.round(location.getY() + vector.y));
    }

    public void setImage(String path) {
        try {
            image = new Image("res/" + path + ".png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getX(){
        return location.getX();
    }
    public int getY(){
        return location.getY();
    }

    public Image getImage(){
        return image;
    }

Then in the main Game class:

public void render(GameContainer gc, Graphics g) throws SlickException {
    g.drawImage(player.getImage(), player.getX(), player.getY());
...
}

It just feels like additional work using so many methods as opposed to directly accessing the field.

Additionally, is there any particular reason Vector2f()'s x and y fields are public while Point's x and y must be accessed through getters/setters?


texts: Find positive integer with a minimum number of binary 1's such that its bitwise AND with all array elements is not 0

texts:
Task

  You have an array of positive integers. Your task is to find an
  integer x such that the following are true:

  Bitwise AND between x and each array element is non-zero.
  Number of ones in the binary expression of x is minimum.
  If there are many such x, you should find smallest of them.

  Input Format

  The first line contains a single integer n, the number of elements
  in the array. The second line contains n space-separated integers.

  Constraints

  1<=n<=10,000
  array elements are in range [1; 2^26)

Please find a full description of the problem here.

My Effort

Count a number of binary 1's for each number from 1 to \$2^{26} - 1\$.
Sort each number from 1 to \$2^{26} - 1\$ by its number of binary 1's. Use a normal std::sort(). Unfortunately, the counting sort is not an option here as its space complexity is too high for Hackerrank environment.
Check each sorted number from the previous step against the array numbers. If its AND with all of them is not 0 - we've found the answer.

This approach has a \$O(m \cdot \log(m) \cdot n)\$ time and \$O(m)\$ space complexity where m - maximum value of an array element and n - size of the array. So, it produces a timeout error for every test case. It produces the correct result, though - I ran it locally for a couple of test cases.

I've tried a \$O(m \cdot n)\$ time and \$O(2 \cdot m)\$ space complexity solution (using the counting sort)  but it didn't work due to a segmentation fault. As stated before, there's a limit as to how much memory one can use for this problem and that one was exceeded.

Code

#include <vector>
#include <iostream>
#include <algorithm>
#include <bitset>

uint32_t solve(std::vector<uint32_t>& array) {
    const uint32_t upperBoundValue = (1 << 26);

    std::vector<uint32_t> candidateNumbers(upperBoundValue);
    for (uint32_t i = 0; i < upperBoundValue; i++) {
        candidateNumbers[i] = i;
    }

    // sort all possible x's by their binary 1's in ascending order
    std::sort(candidateNumbers.begin(), candidateNumbers.end(), [](const auto& a, const auto& b) {
        std::bitset<26> bitSet1(a);
        std::bitset<26> bitSet2(b);

        size_t count1 = bitSet1.count();
        size_t count2 = bitSet2.count();

        if (count1 < count2) {
            return true;
        } else if (count2 < count1) {
            return false;
        } else {
            return a < b;
        }
    });

    // exclude duplicates from the array to reduce its size
    std::sort(array.begin(), array.end());
    array.erase(unique(array.begin(), array.end()), array.end());

    uint32_t candidateIndex;
    for (candidateIndex = 0; candidateIndex < upperBoundValue; candidateIndex++) {
        bool candidateFound = true;

        for (uint32_t index = 0; index < array.size(); index++) {
            if (!(candidateNumbers[candidateIndex] & array[index])) {
                candidateFound = false;
                break;
            }
        }

        if (candidateFound) {
            break;
        }
    }

    return candidateNumbers[candidateIndex];
}

int main() {
    //read an array size
    uint32_t size;
    std::cin >> size;

    //save each value into the corresponding array position
    std::vector<uint32_t> array(size);
    for (auto& element : array) {
        std::cin >> element;
    }

    uint32_t bestMask = solve(array);
    std::cout << bestMask << "\n";

    return 0;
}

Question

Is there a way to improve the time complexity of this solution without exceeding the space limitation? Should a completely different approach be used here?


texts: Stop Django Rest Framework API execution and return appropriate response

texts:
I am writing an API function using Django Rest Framework where it accesses many resources like AWS, Database, External APIs etc., I want the API execution to stop if it fails in any of the steps and return an appropriate response.
I initially used ValueError to raise exceptions manually when something failed, but this resulted in traceback being printed in logs for manually raised exceptions, and the logs became messy.
Later, I used separate except statement for "ValueError" and "Exception" but this led to traceback not being printed for naturally occuring (not manually raised) exceptions and debugging them were hard.
So I created a custom exception which takes an error code, and an error message like below.
class CustomException(Exception):
def __init__(self, status, msg):
    self.status = status
    self.message = msg
    super().__init__(self.message + ': ' + str(self.status))

    def __str__(self):
        return 'ErrorCode: ' + str(self.status) + ' ErrorMessage:' + str(self.message)

And I came up with the below code structure for the API function,
def place_order(request):
    err_msg = 'Problem in placing order. Please contact us'
    try:
        response = get_product_details_from_db()
        if response.status == 0:
            err_msg = 'Failed to get product details from DB'
            raise CustomException(0, err_msg)

        # Do something...

        response = access_aws_s3_files()
        if response.status == 0:
                err_msg = 'Failed trying to access s3'
                raise CustomException(0, err_msg)

        # Do something...

        response = call_external_api()
        if response.status == 0:
            err_msg = 'Failed in accessing external API'
            raise CustomException(0, err_msg)

        # Do something...

        response_data = {
            'status': 1,
            'order_id': '1235'
        }
    except CustomException as e:
        response_data = {
            'status': e.status,
            'error_message': e.message
        }
    except Exception as e:
        traceback.print_exc()
        print(e)
        response_data = {
            'status': 0,
            'error_message': err_msg
        }
    return Response(data=json.dumps(response_data), status=status.HTTP_200_OK)

Is this the standard way of handling such things? Is there any better/alternative way we can handle this ?


texts: Program to find the largest odd number among three variables

texts:
def greatest(a,b):
    if a>b:
        return a
    return b
def odd_check(a):
    return not(a%2 == 0)
def go(x,y,z):
    a = odd_check(x)
    b = odd_check(y)
    c = odd_check(z)
    if a and b and not c:
        print greatest(x,y)
    elif a and not b and c:
        print greatest(x,z)
    elif not a and b and c:
        print greatest(y,z)
    elif not a and not b and c:
        print z
    elif not a and b and not c:
        print y
    elif a and not b and not c:
        print x
    elif a and b and c:
        print greatest(x,greatest(y,z))
    else:
        print "None of them are odd"
go(int(input()),int(input()),int(input()))

Doing the problem it felt like I am going over all the eight combinations \$2^3\$ for three variables. Is there any way to avoid this?


texts: A simple program which returns specific value from array

texts:
After researching for an hour regarding SOLID Principles, I tried to do it myself. Please note that most of these codes were from the ideas of others.

I created a simple program which returns specific value from array, depends on what you choose.

public interface IArrayPerformer
{
    int GetAnswer(int[]arr);
}

public class HighestNumber : IArrayPerformer
{
    public int GetAnswer(int[] arr){ //return highest number }
}

public class LowestNumber : IArrayPerformer
{
    public int GetAnswer(int[] arr) {  //return lowest number }
}

public class MiddleNumber : IArrayPerformer
{
    public int GetAnswer(int[]arr) { // return middle number }
}

public class HighestPrimeNumber : IArrayPerformer
{
    public int GetAnswer(int[] arr) { // return highest prime number }
}

public class LowestPrimeNumber : IArrayPerformer
{
    int GetAnswer(int[] arr) { // return lowest prime number }
}

Then, I created a class and enum which only purpose is to choose what action to be done in arrays..

class ActionChooser
{
    public IArrayPerformer imath(MathAction mathAction)
    {
        IArrayPerformer getMath = null;
        switch(mathAction)
        {
            case MathAction.HighestNumber:
                getMath = new HighestNumber();
                break;
            case MathAction.LowestNumber:
                getMath = new LowestNumber();
                break;
            case MathAction.MiddleNumber:
                getMath = new MiddleNumber();
                break;
            case MathAction.LowestPrimeNumber:
                getMath = new LowestPrimeNumber();
                break;
            case MathAction.HighestPrimeNumber:
                getMath = new HighestPrimeNumber();
                break;

        }

        return getMath;
    }
}

public enum MathAction
{
    LowestNumber = 1,
    HighestNumber = 2,
    MiddleNumber = 3,
    LowestPrimeNumber = 4,
    HighestPrimeNumber = 5
}

Lastly, I created a class for making it all possible..

public class Math
{
    private ActionChooser mathChooser = new ActionChooser();
    public int ReturnAnswer(MathAction mathAcs, int[]arr)
    {
        return mathChooser.imath(mathAcs).GetAnswer(arr);
    }
}

Then, I implemented it like this..

    static void Main()
    {
        int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        //This is what I see when I am implementing .NET built-in codes
        //which is I only have to create object, use its method,
        //pass a small count of arguments, and see the output without
        //knowing the logic behind the codes. I think this is what they
        //called abstraction. Am I right? It's awesome.
        Math math = new Math();
        Console.WriteLine(math.ReturnAnswer(MathAction.LowestNumber, arr));
        Console.ReadKey();
    }

Now, my question is, am I doing it right or wrong? If i'm wrong (which is I know most probably), which part of this code is wrong. Could you explain why and suggest a better solution.


texts:
I partially refactored the code so okFields uses the extracted function checkStringLength.

Now I also want problemFields() to use the same refactored function, but there is a difference between how okFields and problemFields use the function: you see that the problemFields has a little ! in front of validator, and I don't know how to have this vary from the same extracted function. How would you avoid the duplicate code?

function stringLengthValidation( mergedModelAndFormFields ) {
    let fieldsToValidate = mergedModelAndFormFields.okFields

    // extracted function
    function checkStringLength() {
        return _.pickBy( fieldsToValidate, ( value ) => {
            return validator.isLength( value[ 'content' ], {
                'min': value[ 'validation' ].minLength,
                'max': value[ 'validation' ].maxLength
            } )
        } )
    }

    let okFields = checkStringLength()

    // I want to replace this with checkStringLength()
    let problemFields = _.pickBy( fieldsToValidate, ( value ) => {
        // see the '!' here that is the variation
        return !validator.isLength( value[ 'content' ], {
            'min': value[ 'validation' ].minLength,
            'max': value[ 'validation' ].maxLength
        } )
    } )

    return {
        'okFields'     : okFields,
        'problemFields': problemFields
    }
}


texts:
I've written an abstract class in C# for the purpose of random number generation from an array of bytes. The .NET class RNGCryptoServiceProvider can be used to generate this array of random bytes, for example.

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

namespace MyLibrary
{
    /// <summary>
    /// Represents the abstract base class for a random number generator.
    /// </summary>
    public abstract class Rng
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Rng"/> class.
        /// </summary>
        public Rng()
        {
            //
        }

        public Int16 GetInt16(Int16 min, Int16 max)
        {
            return (Int16)(min + (Int16)(GetDouble() * (max - min)));
        }

        public Int32 GetInt32(Int32 min, Int32 max)
        {
            return (Int32)(min + (Int32)(GetDouble() * (max - min)));
        }

        public Int64 GetInt64(Int64 min, Int64 max)
        {
            return (Int64)(min + (Int64)(GetDouble() * (max - min)));
        }

        public UInt16 GetUInt16(UInt16 min, UInt16 max)
        {
            return (UInt16)(min + (UInt16)(GetDouble() * (max - min)));
        }

        public UInt32 GetUInt32(UInt32 min, UInt32 max)
        {
            return (UInt32)(min + (UInt32)(GetDouble() * (max - min)));
        }

        public UInt64 GetUInt64(UInt64 min, UInt64 max)
        {
            return (UInt64)(min + (UInt64)(GetDouble() * (max - min)));
        }

        public Single GetSingle()
        {
            return (Single)GetUInt64() / UInt64.MaxValue;
        }

        public Double GetDouble()
        {
            return (Double)GetUInt64() / UInt64.MaxValue;
        }

        public Int16 GetInt16()
        {
            return BitConverter.ToInt16(GetBytes(2), 0);
        }

        public Int32 GetInt32()
        {
            return BitConverter.ToInt32(GetBytes(4), 0);
        }

        public Int64 GetInt64()
        {
            return BitConverter.ToInt64(GetBytes(8), 0);
        }

        public UInt16 GetUInt16()
        {
            return BitConverter.ToUInt16(GetBytes(2), 0);
        }

        public UInt32 GetUInt32()
        {
            return BitConverter.ToUInt32(GetBytes(4), 0);
        }

        public UInt64 GetUInt64()
        {
            return BitConverter.ToUInt64(GetBytes(8), 0);
        }

        /// <summary>
        /// Generates random bytes of the specified length.
        /// </summary>
        /// <param name="count">The number of bytes to generate.</param>
        /// <returns>The randomly generated bytes.</returns>
        public abstract byte[] GetBytes(int count);
    }
}

Any suggestions for improvements would be welcome.


texts:
I have an object like this

initialize : {
    method : function() {
        this.__. //--> do another thing
        ... //--> so many
        this.__.params. //--> do another thing
        ... //--> so many
    }
}

and the method of this object call by another function.  As you can see, we have many lines that refer to this.__ and this.__. params, and for preventing this, I declare local variables T and P like below

initialize : {
    method : function() {
        var T = this.__, P = T.params;
        T. //--> do another thing
        ... //--> so many
        P. //--> do another thing
        ... //--> so many
    }
}

as I mentioned before the method calls by another function called caller.

Is it possible to not declare locale variables in the method function and instead define them in scope of the caller function and pass it to the method ?


texts:
I was playing around with Unity's new Entity Component System and I was trying to implement a rotator system.
This is what I came up with:

Component Data:

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;

[GenerateAuthoringComponent]
public struct RotatorComponent : IComponentData
{
    public float3 radiansPerSecond;
}

System:

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;

public class RotatorSystem : JobComponentSystem
{
    [BurstCompile]
    struct RotateJob : IJobForEach<Rotation, RotatorComponent>
    {
        public float DeltaTime;

        public void Execute(ref Rotation rotation, ref RotatorComponent rotator)
        {
            float3 rotationThisFrame = DeltaTime * rotator.radiansPerSecond;

            quaternion x = quaternion.AxisAngle(new float3(1.0f, 0.0f, 0.0f), rotationThisFrame.x);
            quaternion y = quaternion.AxisAngle(new float3(0.0f, 1.0f, 0.0f), rotationThisFrame.y);
            quaternion z = quaternion.AxisAngle(new float3(0.0f, 0.0f, 1.0f), rotationThisFrame.z);
            rotation.Value = math.mul(x, rotation.Value);
            rotation.Value = math.mul(y, rotation.Value);
            rotation.Value = math.mul(z, rotation.Value);
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        return new RotateJob { DeltaTime = Time.DeltaTime }.Schedule(this, inputDeps);
    }
}

However, I think that the code shown in the system is not verry efficient.
I am verry new to the new ECS stuff and I never did something with the new Unity.Mathematics. It would be nice if someone could show me whether the code shown in the system can be improved and if so how this would be possible.


texts:
I've isolated this function, cons, for hash-consing in C. It is where the bottleneck of my program is. How could its performance be improved?

var32 cons(var32 x, var32 y){
    var32 ptr;
    uid id, hashedId;
    map newMap, currentMap;
    u32 colls;

    #ifdef __DEBUG__
    ++consCount;
    colls = 0;
    #endif

    // Before anything, compute the unique id of that node.
    id = (((uid)(x.ptr))<<32) | (uid)y.ptr;

    // Try to find the node. If it already exists, return its ptr.
    hashedId = id % MAP_HASH_SIZE;
    currentMap = mapByHashedId[hashedId];
    if (currentMap) do {
        if (mapId[currentMap] == id)
            return mapPtr[currentMap];
        #ifdef __DEBUG__
        ++colls;
        #endif
    } while ((currentMap = mapNext[currentMap]));

    #ifdef __DEBUG__
    if (colls<16) ++collisionCount[colls];
    ++allocCount;
    #endif

    // If does not exist, then alloc a new ptr to it.
    ptr = nodeNewPtr[nodeNewPtrIndex--];

    // Add that new ptr to the map.
    newMap = mapNewPtr[mapNewPtrIndex--];
    if (mapByHashedId[hashedId])
        mapNext[newMap] = mapByHashedId[hashedId];
    mapId[newMap] = id;
    mapPtr[newMap] = ptr;
    mapByHashedId[hashedId] = newMap;

    // Fill that new ptr.
    nodeLeft[GETPTR(ptr)] = x;
    nodeRight[GETPTR(ptr)] = y;

    return ptr;
};

Here is a link for complete source with tests!


texts:
So, I needed to make me a register script for my website so pepole can register, and just wanted to know if It's okey.
So, is there any vulns in this script i made?It works perfectly, just that i wanted to have someone to look over it here.
Or if there could be some inprovments that could make it better.

 <?php
        $Username = $_POST['Username'];
        $Password = $_POST['Password'];
        $Email    = $_POST['Email'];
        $IP       = $_SERVER['REMOTE_ADDR'];
        if ($IP != "84.***.***.**") { die(); } // Beta, Restrict users from using it until it's done
        /* Random Activate code generator */
        function GenerateCode() {
            $R1 = rand(1,9);
            $R2 = rand(1,9);
            $R3 = rand(1,9);
            $R4 = rand(1,9);
            $R5 = rand(1,9);
            $R6 = rand(1,9);
            $C1 = "$R1$R2$R3$R4$R5$R6"; // Simple complie method
            return $C1;
        }
        function Encrypt($Pass) {
            $B64 = base64_encode($Pass);
            $MD5 = md5($B64);
            $Hash = base64_encode($MD5);
            return $Hash;
        }
        /* Mysql data */
        $MysqlUsername = "root";
        $MysqlPassword = "**********";
        $MysqlHostname = "localhost";
        $MysqlDatabase = "teamgamersnet";

        $Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);
        if ($Sql->connect_error){ echo $Sql->connect_error; }
        $sUser = $Sql->real_escape_string($Username);
        $sPass = $Sql->real_escape_string($Password);
        $sMail = $Sql->real_escape_string($Email);
        $xPass = $Sql->real_escape_string(Encrypt($Password));
        if (!$Username | !$Password | $Email) { die("Please fill in all the fields"); }
        $CheckUser = $Sql->query("SELECT Username FROM `users` WHERE `Username` = '".$sUser."'");
        $CheckMail = $Sql->query("SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '".$sMail."'");
        if ($CheckUser->num_rows == 1) { die("Username allready exist"); }
        if ($CheckMail->num_rows == 1) { die("E-Mail allready exist"); }
        $xCode = GenerateCode();
        $Insert = "
        INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`)
        VALUES (NULL, '".$sUser."', '".$xPass."', '".$sMail."', '".$IP."', 'false', '".$xCode."');
        ";
        $Create = $Sql->query($Insert);
        if (!$Create) { echo "S**t, a error happened D:";}
        $to = $Email;
        $subject = 'User account activation | Team Gamers Net';
        $message = '

Thank you for registering at Team Gamers Net

Just one more step and that is to activate your account

You registred with username '.$Username.'

And your password you selected (not shown)

To activate and contiune, please click HERE

        ';
        $headers = "From: DoNotReply@TeamGamers.Net \r\n";
        $headers .= "Reply-To: Admin@heisteknikk.com \r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        mail($to, $subject, $message, $headers);
        header("Location: /?register=true");
    ?>


texts:
I made this studying my Java book about concurrency. It's just to test. I feel it works ok but I'm not so sure about my Java. I worry maybe my code style is strange. I really didn't want that exception. It bothers me that I have to catch it.

I'd love to hear your input on the Java style used here. Any suggestion for how to do something better is welcome! Is it ok to make the array of threads like this?

package com.katie;

// Demonstration of a counter that is not thread-safe.
class Counter {
    private int myCounter = 0;
    public void increment() { myCounter++; }
    public int getCounter() { return myCounter; }
}

class BadIdea implements Runnable {
    private Counter myTarget;
    private int myStabs;
    BadIdea(Counter victim, int stabs) {
        myTarget = victim;
        myStabs = stabs;
    }
    public void run() {
        for (int i = 0; i < myStabs; i++) {
            myTarget.increment();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Counter guineaPig = new Counter();
        final int stabCount = 1000;
        final int threadCount = 3;

        // make multiple threads and use them to break the guineaPig
        // because she is not thread safe!

        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(new BadIdea(guineaPig, stabCount));
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                // i dont care!!
            }
        }

        // These will be different sometimes.

        System.out.println(guineaPig.getCounter());
        System.out.println(threadCount * stabCount);
    }
}


texts: Trying to understand appropriate routing in MVC

texts:
I am learning MVC, and trying to understand routing.

I understand that if I want to show an individual blog post for site.com/54, my route would be something like

//index.php
$controller = new Controller();
if ( preg_match("#/(0-9.)#", $uri, $matches) ) {
    $controller->showAction($matches[1]);
}

which would lead to my controller

//controllers.php
class Controller
{
    private function showAction($id) {
        $post = getPostById($id);
        $view = new View('views/show.php');
    }
}

And, on the other hand, a sensible thing to do for different static pages is perhaps

//index.php
...
} elseif ($uri == '/about') {
    $controller->aboutAction();
} elseif ($uri == '/contact') {
    $controller->contactAction();
} elseif ($uri == '/') {
    $controller->indexAction();
} else {
    $controller->missingAction();
}

My question is, what about the in-between? For example, apple.com/ipad/overview/ and apple.com/ipad/features/. They are different pages, so it seems like the latter is sensible (i.e. unique controller method for each page). But then, when you're on /overview, you still need to know you're a sub-page of /ipad (so you can highlight the iPad button in the navigation). If you did the first method (regex parsing), you'd know that (i.e. you could use $matches[1] when constructing your navigation). If you use the second method, it seems like in your view you'd have to do something like $current_product = 'ipad' so your nav would know about it. But this could get cumbersome.

What's the appropriate method?


texts: More elegant way to show | hide in jQuery

texts:
What is the best way to optimize this jQuery code?

$('#hde_test').hide();

$('#shw_test').click(function() {
    $('#shw_test').hide();
    $('#hde_test').show();
    $('.class1').show();
});
$('#hde_test').click(function() {
    $('#shw_test').show();
    $('#hde_test').hide();
    $('.class1').hide();
});


texts:
I just got back from my interview where I had to solve the following problem:

  Write a C++ program that prints the following pattern using nested for loops.

*
***
*****
***
*

Here is my solution:

int inc = 2;
for (int i = 1; i >= 1; i += inc){
    for (int j = 0; j < i; j++ )
        std::cout<<'*';
    std::cout<<endl;
    if ( i == 5 )
        inc = -2;
}

I'm just curious to know if there are better solutions (any criteria for better) or just different approaches.


texts: Writing a for loop to build a String using Streams

texts:
I have the following code which works. Been trying to write it in Java 8 streams to make it more readable but unable to get my head around it. Looking for any feedback to make it more readable.
Thanks.

// Expected output like: 1~CODE1|2~CODE2|3~CODE3|4~EX|5~CODE5
private String getFormattedValue(List<Content> list) {
    final String tilde = "~";
    final String pipe = "|";
    StringBuilder codes = new StringBuilder();

    for (int i = 0; i < list.size(); i++) {
        String code = list.get(i).getCode();
        if (StringUtils.isNotBlank(code) && !"null".equals(code)) {
            code = "example".equals(code) ? "EX" : code.toUpperCase();
            codes.append(i + 1).append(tilde).append(code);
            codes.append(pipe);
        }
    }
    if (codes.toString().endsWith("|")) {
        codes.deleteCharAt(codes.length() - 1);
    }
    return codes.toString();
}


texts: Word splitting / text parsing with consideration for quotes

texts:
Is the MoveNext operation inefficient here?  I really just want to increment an index.  Originally, I had a mutable variable locally in ExtractTokens to accommodate this.  I would have to believe that a mutable variable there would have been pretty efficient, but I'm trying hard not to have them.  I can't help but feel that creating a new Record to increment an integer is bad somehow.  I guess I'm wondering what a real-world F# developer would have chosen to do here.

This starts in ExtractTokens.  It basically iterates each character in a string.  On spaces it yields the previous word, unless in a quote either single or double.

type Quote =
   | Single
   | Double
   | None

type State = {
   Start : int
   Index : int
   Quote : Quote
   }

let InitState : State =
   {Start = 0; Index = 0; Quote = None }

let MoveNext (s : State) : State =
   {s with Index = s.Index + 1}

let FlipQuote (s : State) (text : string) : State =
   match text.[s.Index], s.Quote with
   | '\'', None   -> {s with Quote = Single}
   | '"' , None   -> {s with Quote = Double}
   | '\'', Single -> {s with Quote = None}
   | '"' , Double -> {s with Quote = None}
   | _ -> s

let StartNew (s : State) : State =
   {Start = s.Index; Index = s.Index; Quote = None}

let NotEmpty (s : string) : bool =
   not (System.String.IsNullOrWhiteSpace(s))

let GetToken (s : State) (text : string) : string =
   text.Substring(s.Start, s.Index - s.Start)

let GetChar (s : State) (text : string) : string =
   text.[s.Index].ToString()

let ExtractTokens (text : string) : seq<string> =
   let rec loop state =
      seq {
         if (state.Index < text.Length) then
            match text.[state.Index], state.Quote with
            | '"' , _
            | '\'', _     -> yield! FlipQuote state text |> MoveNext |> loop
            | ' ' , None
            | '(' , None
            | ')' , None  -> yield  GetToken state text
                             yield  GetChar  state text
                             yield! MoveNext state |> StartNew |> loop
            | _   , _     -> yield! MoveNext state |> loop
         else
            yield GetToken state text
      }
   loop InitState |> Seq.where NotEmpty

Refactored

type Quote =
   | Single
   | Double
   | None

type State = {
   Start : int
   Quote : Quote
   }

let InitState : State =
   {Start = 0; Quote = None }

let FlipQuote (state : State) (index : int) (text : string) : State =
   match text.[index], state.Quote with
   | '\'', None   -> {state with Quote = Single}
   | '"' , None   -> {state with Quote = Double}
   | '\'', Single
   | '"' , Double -> {state with Quote = None}
   | _ -> state

let StartNew (state : State) (index : int) : State =
   {Start = index; Quote = None}

let NotEmpty =
   System.String.IsNullOrWhiteSpace >> not

let GetToken (state : State) (index : int) (text : string) : string =
   text.Substring(state.Start, index - state.Start)

let GetChar (index : int) (text : string) : string =
   text.[index].ToString()

let ExtractTokens (text : string) : seq<string> =
   let rec loop index state =
      seq {
         if (index < text.Length) then
            match text.[index], state.Quote with
            | '"' , _
            | '\'', _     -> yield! FlipQuote state index text |> loop (index + 1)
            | ' ' , None
            | '(' , None
            | ')' , None  -> yield  GetToken state index text
                             yield  GetChar  index text
                             yield! StartNew state (index + 1) |> loop  (index + 1)
            | _   , _     -> yield! state |> loop (index + 1)
         else
            yield GetToken state index text
      }
   loop 0 InitState |> Seq.where NotEmpty


texts: Simplifying a packaged task for a threadpool implementation

texts:
I wrote a thread pool where the user can submit jobs through ThreadTask objects. These objects bundle the job priority, the task as a function, and some arbitrary number of function parameters.

After much frustration I ended up with something like this:

struct ThreadTask
{
    template <typename Func, typename... Args>
    ThreadTask(exrFloat priority, Func&& func, Args&&... args)
    {
        // package task function with its arguments
        auto pTask = std::make_shared<std::packaged_task<void()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));

        // convert packaged task to a void std::function
        m_Task = ([pTask]() { (*pTask)(); });
        m_Priority = priority;
    };

    ...
    std::function<void()> m_Task;
};

...

m_Task();

This allows the user to schedule jobs like this:

threadPool.ScheduleTask(priority, [&](int customParam1, int customParam2)
{
    ...
}, param1Val, param2Val);

This was the only way I knew how to package variadic parameters with the function itself. It works, but looks really ugly. Is there some way I could simplify this?


texts: Create a template literal tag to remove whitespace from a string

texts:
I'm just getting into functional programming (as in, just started reading the book) and as practice I'm trying to refactor a past answer I wrote to fit in line with the functional style.

The function is intended to be a template literal tag, like so:

let myString = withoutWhitespace`This is a really long string, that needs to wrap over
    several lines. With a normal template literal you can't do that, but you can
    use a template literal tag to get rid of line breaks and indents.`;

Here's the original:

function withoutWhitespace(strings, ...placeholders) {
  // Build the string as normal, combining all the strings and placeholders:
  let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
  let withoutSpace = withSpace.replace(/\s\s+/g, ' ');
  return withoutSpace;
}

And here's my new version:

function withoutWhitespace(strings, ...placeholders) {
  return trimWhitespace(merge(strings, placeholders).join());
}

function trimWhitespace(input) {
    return input.replace(/\s\s+/g, ' ');
}

function merge(one, two) {
    let result = [];
    for(let i = 0; i < Math.max(one.length, two.length) - 1; i++) {
        pushIfTruthy(result, one[i]);
        pushIfTruthy(result, two[i]);
    }
    return result;
}

function pushIfTruthy(array, item) {
    if(item) {
        array.push(item);
    }
    return array;
}

How does this look so far? What improvements could I make?


texts: Add elements to collection conditionally

texts:
Is there a smarter way to write this code?  I used to add all the elements in the collection constructor, something like this:

new OrderWizardStateCollection([new OrderWizardState(..), new OrderWizardState(..)..])

but now, since I have this one conditional addition, I'm writing it this way:

this.state_collection = new OrderWizardStateCollection();
this.state_collection.add(new OrderWizardState({ state: 'basket', phase: this.phase_collection.findWhere({ phase: 'basket' }) }));
this.state_collection.add(new OrderWizardState({ state: 'account', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
if ( _.has(this.regions, "lp") ) this.state_collection.add(new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
this.state_collection.add(new OrderWizardState({ state: 'delivery', phase: this.phase_collection.findWhere({ phase: 'delivery' }) }));
this.state_collection.add(new OrderWizardState({ state: 'payment', phase: this.phase_collection.findWhere({ phase: 'payment' }) }));
this.state_collection.add(new OrderWizardState({ state: 'placeorder', phase: this.phase_collection.findWhere({ phase: 'placeorder' }) }));


texts: Better practice to find the max/min element in a loop

texts:
Is this the most elegant way to avoid declaring additional variables outside the       following_triggers loop?

      closest_trigger_utc_time = (2**(0.size * 8 -2) -1)
  following_triggers.each do |test|
    closest_trigger_utc_time = test.utc_time if test.utc_time < closest_trigger_utc_time
  end


texts: Find the single smallest IP network with the given IP addresses

texts:
I have a bunch of IP addresses. I want one IP network that has them all. ipaddr.collapse_address_list already exists, but that gives you a list of all the IP networks that identify your IP addresses, no more, no less, whereas I only need one IP network.

I tried at first using XOR, but that fails on some situations (say, 10.0.0.1, 10.0.0.2, 10.0.0.255, 10.0.0.251: bin(1 ^ 2 ^ 255 ^ 251) = 0b111). And'ing has similar problems. This is what I ended up writing.

#http://stackoverflow.com/a/3789000/13992
def _AllSame(items):
  it = iter(items)
  first = next(it, None)
  return all(x == first for x in it)

def _GetOneNetmaskForAllTheseIPs(ips):
  """Get the one IP network that covers all IPs in input.

  ipaddr.collapse_address_list is a little bit TOO smart and gives you the LIST
  of networks that describe a number of IP addreses. Ceph just wants one
  netmask. This function tries to get that one netmask.

  >>> _GetOneNetmaskForAllTheseIPs(("10.0.0.1", "10.0.0.2",
  ...   "10.0.0.251", "10.0.0.255"))
  10.0.0.0/24
  """

  #Turn each IP address in its binary representation, without 0b header
  num_ip_addresses = [int(ipaddr.IPAddress(ip)) for ip in ips]
  lowest_ip = ipaddr.IPAddress(min(num_ip_addresses))
  bin_ip_addresses = [bin(ip)[2:] for ip in num_ip_addresses]

  #"Transpose" the list (abc),(def) → (ad),(be),(cf)
  bit_comparison = zip(*bin_ip_addresses)

  differing_bits = len(bit_comparison)
  #Find the first different bit
  while _AllSame(bit_comparison[-differing_bits]):
    differing_bits -= 1

  #That's the no. of bits that differ. The mask is the number of bits that DON'T
  mask_length = lowest_ip.max_prefixlen - differing_bits

  #Return the network
  network_ip = ipaddr.IPNetwork("%s/%d" % (lowest_ip, mask_length)).network
  network = ipaddr.IPNetwork("%s/%d" % (network_ip, mask_length), strict = True)
  return str(network)

I tried to be as IP-version agnostic as possible here, but chances are I've overlooked a few more-or-less obvious things here — or, even more likely, there's already a better inbuilt solution somewhere in the python libraries or even ipaddr itself.


texts:
I don't know regex. I want to learn regex, but learning regex just for the sake of regex would be quite boring.

So I decided to learn Ruby as well (which so far looks a lot like Python, which I'm familiar with).

My first program attempts to speak with a combination of both Daffy Duck's lisp and Elmer Fudd's verbal apraxia.

It works quite well, but it looks quite messy already. How does one properly combine Ruby and (repeated) regex substitutions?

def lisp(input)
   return input.downcase.gsub(/s/, "th").gsub(/er/, "uh").gsub(/r|l/, "w").capitalize
end

print lisp("What's your input?")
user_input = gets.chomp

puts lisp(user_input)

I downcase everything to make the regex easier and capitalize at the end to turn it back into a proper sentence.

Usage:

What'th youw input? It's rabbit season!

  It'th wabbit theathon!

What'th youw input? My super soaker carries 2 liters of water!

  My thupuh thoakuh cawwieth 2 wituhth of watuh!


texts: Function dependence on iteration variable of another function

texts:
Consider two versions of implementing the same functionality.

Version 1 -
Functions calculateA(),calculateB() and calculateC() dependent on iteration variable of calculateAll().

class Box
{
    void calculateAll()
    {
        for(unsigned i = 0; i < _values.size(); i++)
        {
            calculateA(i);
            calculateB(i);
            calculateC(i);
        }

    }

    A calculateA(unsigned i) const
    {
        //Calcualate A based on _values
    }

    B calculateB(unsigned i) const
    {
        //Calcualate B based on _values
    }

    C calculateC(unsigned i) const
    {
        //Calcualate A based on _values
    }

    std::vector<unsigned>           _values;
};

Version 2 - Functions calculateA(),calculateB() and calculateC() are not dependent on calculateAll()

class Box
{
    void calculateAll()
    {
        calculateA();
        calculateB();
        calculateC();
    }

    A calculateA() const
    {
        for(const auto& value: _values)
        {
            //Calcualate A based on _values
        }
    }

    B calculateB() const
    {
        for(const auto& value: _values)
        {
            //Calcualate B based on _values
        }
    }

    C calculateC() const
    {
        for(const auto& value: _values)
        {
            //Calcualate C based on _values
        }
    }

    std::vector<unsigned>           _values;
};

Which version is more cleaner? Which version is better performance wise? Is there a better implementation that these?


texts: Fastest way to extract n bytes from uint8_t buffer

texts:
I work a lot with byte buffers and have to extract different parts. In this example, it's 4 byte, but it ranges from a single bit to 128 bit. Speed is the most important metric here. See the code for a MWE. I'd like to know if there is a better way.

#include <stdint.h>

static uint32_t get_data(uint8_t *buf, size_t off)
{
    return ((uint32_t)(buf[off + 0]) << 24) +
                  ((uint32_t)(buf[off + 1]) << 16) +
                  ((uint32_t)(buf[off + 2])  <<  8) +
                  ((uint32_t)(buf[off + 3]));
}

int main(int argc, char **argv)
{
    uint8_t buf[128];

    /* get some example data */
    for (uint8_t i = 0; i < 128; ++i)
        buf[i] = i;

    /* we want the data from offset 10 as an uint32_t */
    uint32_t res = get_data(buf, 10);
}


texts: C program to print a vertical english ruler whose length is given by the user

texts:
In this source code, i have writena program, using for loops, to print an english ruler whose length is given by the user.
So what i want to know is that is it possible to modify this program, to print the ruler in a more logical way And if so, how can it be done, without applying reculsions ?
This is the program to print ruler vertically.
#include <stdio.h>
int main()
{

    int q, num, x;
    int y, p, n;
    printf( "Enter height of central dashes \n" );
    scanf( "%d", &n );
    printf( "Enter number of inches \n" );
    scanf( "%d", &num );
    for( x=0; x < num ; x++ )
    {
    for( q=0; q<n; q++ )
    {
    printf( "-" );
    }
    printf( "%d\n", x );
    for( p=0; p < n-3; p++ )
    {
    printf("-");
    }
    printf( "\n" );
    for( p=0; p < n-2; p++ )
    {
    printf( "-" );
    }
    printf( "\n" );
    for( p=0; p < n-3; p++ )
    {
    printf( "-" );
    }
    printf("\n");
    for( p = 0; p < n-1; p++)
    {
    printf( "-" );
    }
    printf( "\n" );
    for( p = 0; p < n-3; p++)
    {
    printf( "-" );
    }
    printf( "\n" );
    for( p = 0; p < n-2; p++)
    {
    printf( "-" );
    }
    printf( "\n" );
    for( p = 0; p < n-3; p++)
    {
    printf( "-" );
    }
    printf( "\n" );
    }
    for( y = 0; y < n; y++ )
    {
        printf( "-" );
    }
    printf( "%d", x );
    printf( "\n" );
    return 0;
 }


texts:
The task is to find the median of two Arrays. I have an O(n) solution.
Can it be written in a better time complexity?

def findMedianSortedArrays(self, A, B):
    combined = []
    while len(A) > 0 and len(B) > 0:
        if (A[0] < B[0]):
            combined.append(A.pop(0))
        else:
            combined.append(B.pop(0))
    combined.extend(A)
    combined.extend(B)

    length = len(combined)
    if length % 2 != 0:
        return combined[length // 2]
    else:
        return (combined[length // 2-1] + combined[length//2]) / 2


texts:
There are 60 submissions from me to the very first beginner-freshman exercise at codeforces.com. Problem: 100985A - MaratonIME helps Pablito

I don't pass the tests because of Time limit exceeded (tle). I'm just thinking about the test can't be passed using java because of performance. But really, I think a crappy error in my algorithm is more likely. Or my approach is completely wrong. So feel free to comment my approach.

Excercise:

  As is well known by any cultured person, rats are the smartest beings
  on earth. Followed directly by dolphins.

  MaratonIME knows about the species hierarchy and uses this knowledge
  in it's regard. Usually, when they need some resource, they know it's
  always useful to have a smart rat available. Unfortunately, rats are
  not very fond of us, primates, and will only help us if they owe us
  some favour.

  With that in mind, MaratonIME decided to help a little rat called
  Pablito. Pablito is studying rat's genealogy, to help with cloning and
  genetic mapping. luckily, the way rats identify themselves make the
  job much easier.

  The rat society is, historically, matriarchal. At first, there were
  little families, each of which had it's own leading matriarch. At that
  time, it was decided that rats would organize themselves according to
  the following rules:

  Each martiarch had an id number greater than one. Each of these ids
  were chosen in a way such that they would have the least amount of
  divisors possible. Each family member had the same id as the
  matriarch. The id of any newborn rat would be the product of its
  parents id's. For instance, the offspring of a rat with id 6 and
  another with id 7 is 42.

  Pablito needs to know if two given rats have a common ancestor, but
  his only tool is the id number of each of the two rats, which is
  always a positive integer greater than 1 with no more than 16 digits.
  Can you help him?

  Create a program that decides if a pair of rats have some common
  ancestor.

  Input The input begins with a positive integer t ≤ 105, the number of
  test cases.

  After that, follows t lines, each with two integers ai e bi
  identifying two rats.

  Every rat's id is a positive integer greater than 1 and with no more
  than 16 digits.

  Output For each test case, print "Sim" if the rats ai and bi share a
  common ancestor and "Nao" otherwise.

My latest approach before using multiple threads. (Yeah, TLE there as well).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class A {
    public static void main(String[] args) throws IOException{
        BufferedReader scan = new BufferedReader (new InputStreamReader(System.in));
        int amountTests = Integer.parseInt(scan.readLine());

        for (int i = 0; i<amountTests; i++){
            String[] tmp = scan.readLine().split(" ");
            long l1 = Long.parseLong(tmp[0]);
            long l2 = Long.parseLong(tmp[1]);
            if (l1 < l2){
                searchPrims(l1,l2);
            }else{
                searchPrims(l2,l1);
            }
        }
    }

    static void searchPrims(long n, long n2){
        int d = 2;
        while (true){
            if(n%d==0){
                if(n2%d==0){
                    System.out.println("Sim");
                    return;
                }
                n/=d;
                d = 2;
            }
            else if(n==1){
                System.out.println("Nao");
                return;
            }
            else{
                if(d==2)
                    d=3;
                else{
                    d+=2;
                }
            }
        }
    }
}


texts:
I tried to solve the N Queens problem in Haskell using backtracking. Here is my approach:

type Solution = [Int]

extend :: Solution -> Int -> Maybe Solution
extend b new = go 0 b
  where
    n = length b
    go _ []  =  Just (b ++ [new])
    go i (x:xs)
      | x == new                      = Nothing
      | abs (i - n) == abs (x - new)  = Nothing
      | otherwise                     = go (i+1) xs

fullExtend :: Int -> Solution -> Maybe Solution
fullExtend n partialSolution
  | length partialSolution == n     = Just partialSolution
  | otherwise                       = foldr propose Nothing [0..(n-1)]
  where
    propose _ (Just xs) = Just xs
    propose x Nothing   = extend partialSolution x >>= fullExtend n

nQueens :: Int -> Maybe Solution
nQueens n = fullExtend n []

Can the propose function be expressed in a more elegant way? I am only happy to get one solution here, and shortcircuiting the evaluation is fine.

I also experimented a bit more to find out all the solutions. Here is how I did so:

extend' :: Solution -> Int -> [Solution]
extend' b new = go 0 b
  where
    n = length b
    go _ []  =   [b ++ [new]]
    go i (x:xs)
      | x == new                      = []
      | abs (i - n) == abs (x - new)  = []
      | otherwise                     = go (i+1) xs

fullExtend' :: Int -> Solution -> [Solution]
fullExtend' n partialSolution
  | length partialSolution == n     = [partialSolution]
  | otherwise                       = [0..(n-1)] >>= (\x -> extend' partialSolution x >>= fullExtend' n)

nQueens' :: Int -> [Solution]
nQueens' n = fullExtend' n []

General comments on coding style would also be helpful.


texts:
I have a hierarchical object structure which needs to be converted to JSON. I have a following basic implementation of how it will be done:

#include <iostream>
using namespace std;

class base
{
    public:
    base():a(1){};
    void serialize()
    {
        cout<<"{"<<endl;
        toString();
        cout<<"}";
    };
    virtual void toString()
    {
        cout<<"\"base-a\": "<<a<<endl;
    };

    private:
    int a;
};

class derived: public base
{
    public:
    derived():b(2){};
    virtual void toString()
    {
        base::toString();
        cout<<"\"derived-b\": "<<b<<endl;
    };

    private:
    int b;
};

int main() {
    derived d;
    base& b = d;
    b.serialize();
    return 0;
}

The only problem I see here is when derived is extended then that class' toString function has to call the toString function of derived and so on.

Is calling a overridden function from overriding function a bad practice?
Is there a better way to write this code?

Note: I cannot use C++11.


texts:
Code reviewers, I request you review the code and suggest all tips for improvement.

public class LRU<K, V> {

    private final Map<K, Entry<K, V>> map;
    private Entry<K, V> eldest;
    private final int lruSize;

    public LRU (int lruSize) {
        if (lruSize <= 0) {
            throw new IllegalArgumentException("size should atleast be one");
        }
        map = new HashMap<K, Entry<K, V>>();
        this.lruSize = lruSize;
    }

    private static class Entry<K, V> {
        Entry<K, V> left;
        K key;
        V value;
        Entry<K, V> right;

        Entry (Entry<K, V> left, K key, V value, Entry<K, V> right) {
            this.left = left;
            this.key = key;
            this.value = value;
            this.right = right;
        }

    };

    /**
     * Head is first node of the linked list.
     * Similar to - convert tree to doubly linkedlist.
     */
    private void addFirst(Entry<K, V> entry) {
        remove(entry);
        if (eldest == null) {
            entry.left = entry.right = entry;
            eldest = entry;
        } else {
            // last node of the list. extra storage just for purpose of simplification
            Entry<K, V> tail = eldest.left;

            tail.right = entry;
            entry.left = tail;

            // now deal with circularing
            eldest.left = entry;
            entry.right = eldest;
        }
    }

    private void remove (Entry<K, V> entry) {
        assert entry != null;

        if (entry.left != null) entry.left.right = entry.right;
        if (entry.right != null) entry.right.left = entry.left;
        if (entry == eldest) eldest = entry.right;
    }

    /**
     * Allowing null. Since, this is behavior of linkedhashmap.
     * Still adding synchronization as interviewer is bound to ask this question
     */
    public synchronized void put(K key, V value) {
        Entry<K, V> entry = new Entry<K, V>(null, key, value, null);
        map.put(key, entry);
        addFirst(entry);

        if (removeEldestEntry()) {
            remove(eldest.key);
        }
    }

    public synchronized V get (K key) {
        Entry<K, V> entry = map.get(key);
        if (entry != null) {
            addFirst(entry);
            return entry.value;
        }
        return null;
    }

    public synchronized void remove (K key) {
       Entry<K, V> entry = map.remove(key);
       if (entry != null) {
           remove(entry);
       }
    }

    private boolean removeEldestEntry() {
        return map.size() > lruSize;
    }
}


texts:
I'm using fabric.js to add images to a canvas from my computer. I'm wondering if there's a cleaner way to do this than what I've been using. My code looks like this:

// Initializing Fabric Canvas

var canvas = new fabric.Canvas("c");
canvas.setHeight(616);
canvas.setWidth(446);

// New Photo to Canvas
document.getElementById('addimg').onchange = function handleImage(e) {
  var reader = new FileReader();
  reader.onload = function(event) {
    var imgObj = new Image();
    imgObj.src = event.target.result;
    imgObj.onload = function() {
      var image = new fabric.Image(imgObj);
      image.set({
        left: 10,
        top: 10,
      }).scale(0.2);
      canvas.add(image);
    };
  };
  reader.readAsDataURL(e.target.files[0]);
};
#addimg {
 position: relative;
 overflow: hidden;
 cursor: pointer;
 }

input {
 position: absolute;
 font-size: 50px;
 opacity: 0;
 right: 0;
 top: 0;
 cursor: pointer;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<div class="file btn btn-sm btn-dark" id="addimg">
  Add Image
  <input type="file" name="file" />
</div>

<canvas id="c"></canvas>


texts: PHP ideal way to check function returns true

texts:
Which of the following way of checking whether a function returns TRUE or FALSE is best, in terms of efficiency and code readability?

I was told by a friend that Method B is a good practice, but I believe Method A is better since it checks whether function returns TRUE then assigns.

Method A: (Checks whether function is TRUE and then assigns.)

if ($result = $db->getResults($id)) {
    echo $result;
} else {
    echo 'fail';
}

Method B: (First assigns the value, then checks—two operations.)

$result = $db->getResults(90);
if ($result) {
    echo $result;
} else {
    echo 'fail';
}

public function getResults($no) {
    if ($no > 85) {
        $result = 'pass';
        return $result;
    } else {
       return FALSE;
    }
}


texts:
I wrote a small program in Python that finds primes (how original) up to some limit. I tried to produce very clean code, so I'd be vary grateful if you could point out any improvement I could do to make it more pythonic and more readable.

I'm also interested in knowing whether or not it can be sped up (with the same method I used here). I tried to use generator, but since I want to read my list of primes multiple times it didn't work... I'm also wondering if a set or some other structure could be better than a list here.

Thank you very much !

from __future__ import print_function
import time

def measure_time(func):
    def wrapper(*args, **kw):
        starting_time = time.clock()
        res = func(*args, **kw)
        ending_time = time.clock()
        print('Duration : %fs' % (ending_time - starting_time))
        return res
    return wrapper

def ask_user_input():
    """Relentlessly ask user to enter an integer >1."""
    while True:
        try:
            lim = int(raw_input('What\'s the limit?   '))
            if lim == int(lim) and lim > 2:
                break
            else:
                print('Must be an integer larger than 1. Try again.')
        except (NameError, ValueError):
            print('Not a number. Try again.')
    return lim

def print_primes(primes):
    for p in primes:
        print(p)

@measure_time
def construct_primes_list(lim):
    """Builds the list of primes smaller than lim."""
    prime_divisors = [2]

    for num in xrange(2, lim):
        for d1 in prime_divisors:
            if num % d1 == 0:
                break
        else:
            prime_divisors.append(num)

    return prime_divisors

def main():
    lim = ask_user_input()
    primes = construct_primes_list(lim)
    # print_primes(primes)

if __name__ == '__main__':
    main()

Here is the benchmarking on my computer:

lim      | time
-----------------------
100      | 0.000143s
1000     | 0.003231s
10000    | 0.071654s
100000   | 2.598098s
1000000  | 169.052574s

EDIT :

As ChatterOne's comment suggested, I tried to compute the square root of num because I know I couldn't find any divisors after that. But it gets way slower. Here is the code :

for num in xrange(3, lim):
    sqrt_num = int(sqrt(num)+1)
    for d1 in [p for p in prime_divisors if p < sqrt_num]:
        if num % d1 == 0:
            break
    else:
        prime_divisors.append(num)

Any thoughts?


texts: 64-bit Mersenne Twister random-number generator; follow-up #1

texts:
This question is a direct follow-up of:

Have a look at this Mersenne Twister random-number generator function

Thanks to Code Review and Stack Overflow, I now realize, that:

unsigned long long int is not guaranteed to be 64-bit
I don't want to re-initialize the random_device on every function call

and a few other things.

So, based on current information, I've re-written it as follows:

#include <iostream>     // std::cout
#include <cstdint>      // std::uint64_t
#include <random>       // std::random_device, etc.

std::uint64_t random_integer(std::uint64_t rand_min, std::uint64_t rand_max)
{
    // use Mersenne Twister as random-number generator engine
    // initialize = seed the random device; static thread_local = only once
    // avoid "most vexing parse" by using "uniform initialization syntax" = { something{}() }
    static thread_local std::mt19937_64 random_number_generator{std::random_device{}()};

    // uniform number distribution, guaranteed unbiased
    std::uniform_int_distribution<std::uint64_t> number_distribution(rand_min, rand_max);

    // return one random number
    return number_distribution(random_number_generator);
}

// this is just to test the output
int main()
{
    for (int i = 1; i <= 10; i++)
    {
        std::cout << random_integer(10000000, 100000000) << std::endl;
    }
    return 0;
}

If you could guide me further on improving it, I would be grateful.


texts:
I've written a small bit of JavaScript which parses some HTML and generate a table of contents based on the various heading tags. The table of contents needs to be nested (E.g. H2 tags appear under H1).

My code is currently working well but I'm not sure the my method of storing all the headings is the best (it's been awhile since I've had to do much JS). The headings are being stored in a series of nested objects. The objects are made up of two properties (#title and #id) to store the heading title and anchor link. It can then contain incrementally numbered sub-heading objects.

A large portion of my code seems to be dealing with finding the last item in the object to append the next heading to. I don't know if there would be an easier way of doing this with nested arrays.

The script runs the parseDOM function passing it the DIV containing the report. Once that's complete the resulting object is passed to a series of functions which turns it into a series of ordered list elements.

I've stripped out the parts for generating the table of contents HTML, I can post it if you want it though.

var heading_selectors = [
 'H1',
 'H2',
 'H3',
 'H4',
 'H5',
 'H6',
];
function parseDOM(report) {
  // Generate selector from heading selectors.
  var selector = heading_selectors.join(',');
  var nav_hierarchy = {};
  var next_heading_id = 0;
  $(selector, report).each(function(index, heading_element) {
    var heading = $(heading_element);
    // Determine heading level.
    var tag_name = heading.get(0).nodeName;
    var level = heading_selectors.indexOf(tag_name);
    var title = heading.text();
    var id = next_heading_id;
    var id_name = id + '-' + level + '-' + title.replace(/\s+/g, '-').toLowerCase();
    heading.attr('id', id_name);

    // Create object to hold heading.
    var new_heading = {
      '#title': title,
      '#id': id_name,
    };

    var parent_item = lastHeadingAtLevel(nav_hierarchy, level);
    parent_item[id] = new_heading;

    // Increment heading id.
    next_heading_id++;
  });

  return nav_hierarchy;
}

/**
 * Returns the last heading at the specified level.
 *
 * @param object heading Heading to retrieve the last element of.
 * @param int level What level of heading to retrieve from.
 *
 * @return object Last heading at specified level.
 */
function lastHeadingAtLevel(heading, level) {
  if (level !== 0) {
    // Recurse through lists until you hit the required level.
    var last_item = getLastHeading(heading);
    last_item = lastHeadingAtLevel(last_item, level-1);
    return last_item;
  }
  // No recursion required.
  return heading;
}

/**
 * Return the last heading in the object (excludes properties beginning with #).
 *
 * @param object heading Heading to retrieve last heading of.
 *
 * @return object Last Heading of object.
 */
function getLastHeading(heading) {
  // Get the keys of the current heading.
  var keys = Object.keys(heading);
  // Default last_element to lowest value
  var last_element = -1;
  for (var i = 0; i < keys.length; i++) {
    if (keys[i].startsWith('#')) {
      continue;
    }
    if (parseInt(keys[i], 10) > last_element) {
      last_element = parseInt(keys[i], 10);
    }
  }

  // Return the last element added.
  return heading[last_element];
}


texts: Print largest two integers from a stream

texts:
I'm writing a program for my intro to comp sci course where I'm supposed to prompt the user to enter a stream of integers, and then return the largest two. We were given the hint to use a scanner and a while loop with the condition .hasnext.

Please review my code:

package Homework;

import java.util.*;

public class Question1 {

public static void main(String[] args) {
    System.out.println("Please type your integers");
    Scanner kbd = new Scanner(System.in);
    int big = 0;
    int big2 = 0;
    while(kbd.hasNext())
    {
       int num = kbd.nextInt();
       if(num > big) { // opens If statement
          big2 = big;
          big = num;
        } else if((num < big) && (num > big2))  {
           big2 = num;
        }
    }
    System.out.print(big);
    System.out.print(big2);
 }
}


texts:
I wrote some program in C language. I have to calculate sum of squares. My book suggested me to use loops but I chose more efficient way by using formula:

$$1^2+2^2+\cdots+n^2=\frac{n\left(n+1\right)\left(2n+1\right)}{6}$$

Original code from listing 5.13:

#include <stdio.h>

int main(void) {
    int licznik, suma;

    licznik = 0;
    suma = 0;
    while (licznik++ < 20)
        suma = suma + licznik;
    printf("suma = %d\n", suma);
    return 0;
}

Finally, this is my code:

#include <stdio.h>

int main(void) {
    int zakres;
    printf("Podaj zakres przeprowadzanych obliczen:\n");
    scanf("%i", &zakres);
    printf("suma kwadratow = %d\n", (((zakres * (zakres + 1)) * (2 * zakres + 1)) / 6));
    return 0;
}

What do you think about this solution? Is it more efficient than loops?


texts:
I have created a fractal tree based on a Lindenmayer System in Python. If you could tell me about any algorithmic or efficiency-based problems in the code, I would be grateful.

import turtle
import time
t = turtle.Pen()

branch = []
code = "1[0]0" # Change this to modify the structure of the tree

t.left(90)
t.up()
t.backward(300)
t.down()
t.speed(10)

for c in code:
    if c == "1":
        t.pencolor("brown")
        t.forward(100) # Change this to modify the size of the tree

    elif c == "0":
        t.pencolor("green")
        t.forward(3) # Change this to modify the size of the leaves

    elif c == "[":
        t.left(45)
        branch.append((t.position(), t.heading()))

    elif c == "]":
        t.up()
        t.goto(branch[len(branch) -1][0], None)
        t.setheading(branch[len(branch) -1][1])
        t.right(90)
        t.down()
        del branch[len(branch) -1]


texts: Fetching data from realm database and searching and viewed in recyclerView

texts:
Attached my data class, datas is not fetched from realm database while performing filtering in performFiltering method:

Worker.kt

package com.oyespace.guards.models

import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.RealmClass

@RealmClass
open class Worker:RealmObject(){
    @PrimaryKey
    var wkWorkID:Int = 0
    var wkfName:String = ""
    var wklName:String = ""
    var wkMobile:String = ""
    var wkEntryImg:String = ""
    var wkWrkType:String = ""
    var wkDesgn:String = ""
    var wkdob:String = ""
    var wkidCrdNo:String =""
    var vnVendorID:Long = 0
    var blBlockID:Long = 0
    var unUnitID:String = ""
    var asAssnID:Long = 0
    var wkIsActive:Boolean = false
    var unUniName:String = ""

}
data class GetWorkersResponse<T>(
    val apiVersion: String,
    val `data`: WorkersList,
    val success: Boolean
)
data class WorkersList(
    val worker: RealmList<Worker>
)

data class GetGuardsListResponse<T>(
    val apiVersion: String,
    val `data`: GuardsList,
    val success: Boolean
)

data class GuardsList(
    val workers: RealmList<Worker>
)

I want to fetch data from realm database and perform searching and view in recyclerview

 override fun performFiltering(charSequence: CharSequence?): FilterResults {

                    val filteredList = ArrayList<Worker>()
                   // Toast.makeText(mcontext,items.get(0).wkfName,Toast.LENGTH_LONG).show()

                    for (row in items) {

                      //  Log.d("Inside for loop",row.wkfName)
                        // if (row.wkfName!!.toLowerCase().contains(charString.toLowerCase()) || row.age!!.contains(charSequence)) {
                        if (row.wkfName.toLowerCase().contains(charString.toLowerCase().trim())) {

                            filteredList.add(row)

                        }
                    }
                    searchList = filteredList
                }
                val filterResults = Filter.FilterResults()
                filterResults.values = searchList

                return filterResults
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {

                searchList = results?.values as? ArrayList<Worker>

                notifyDataSetChanged()
            }

        }

    }


texts:
In the existing system, we need to rebuild the user's authorization.

The database includes Roles and Rights

Roles were previously used but will be skipped in the new version

All authorization will be based on Rights control

I have prepared an attribute that performs such a task

Controller:

[HasRights(Rights.AddPayer, Rights.DeletePayer)]
[HttpPost]
public IActionResult AddPayer([FromBody]PayerModel model)
{
}

Attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public class HasRightsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    HashSet<Rights> userRights;

    public HasRightsAttribute(params Rights[] rights)
    {
        userRights = rights.ToHashSet();
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        Claim claim = context.HttpContext.User.Claims.FirstOrDefault();
        int userId = int.Parse(claim.Value);

        List<int> rights;

        using (var myContext = new myDB())
        {
            rights = (from UR in myContext.TblUserRole
                      join RR in myContext.TblRoleRight on UR.RoleID equals RR.RoleID
                      where UR.UserID == userId
                      select RR.RightID)
                      .ToList();
        }

        var permission = rights.Any(x => userRights.Contains((Rights)Enum.ToObject(typeof(Rights), x)));

        if (!permission)
        {
            //context.Result = new ForbidResult();
            Debug.WriteLine("NO ACCESS");
        }
        else
        {
            Debug.WriteLine("YOU HAVE ACCESS");
        }
    }
}

Is this a good direction?

What can be corrected / changed?


texts: Create a unique four digit code from 35 characters

texts:
I want to generate a four digit code based on the code generated before it, starting at 0000 and going to zzzz.

These are the available characters to be inside the code:

private static final char[] _availableChar = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

The first thing I do is the get the newest code or the code with the highest auto_incremented Id.

I then pass that to this function to generate the next cod:

private String getNewCodeFromOldCode(String oldCode) {
        char[] newCodeChars = oldCode.toCharArray();

        if (oldCode == null || oldCode.isEmpty()) {
            return "0000";
        } else {
            char[] oldCodeChars = oldCode.toCharArray();

            if (oldCodeChars[3] != 'z') {
                newCodeChars[3] = _availableChar[String.valueOf(_availableChar).indexOf(oldCodeChars[3]) + 1];
            } else {

                if (oldCodeChars[2] != 'z') {
                    newCodeChars[3] = '0';
                    newCodeChars[2] = _availableChar[String.valueOf(_availableChar).indexOf(oldCodeChars[2]) + 1];
                } else {

                    if (oldCodeChars[1] != 'z') {
                        newCodeChars[2] = '0';
                        newCodeChars[1] = _availableChar[String.valueOf(_availableChar).indexOf(oldCodeChars[1]) + 1];
                    } else {

                        if (oldCodeChars[0] != 'z') {
                            newCodeChars[1] = '0';
                            newCodeChars[0] = _availableChar[String.valueOf(_availableChar).indexOf(oldCodeChars[0]) + 1];
                        } else {
                            JsfUtil.addErrorMessage("Unable To Generate A Code");
                        }

                    }

                }

            }
        }

        return String.valueOf(newCodeChars);
    }

I'm not exactly sure how to calculate the permutations but I think I have upwards of million different perm. available.


texts:
The problem is to ask the user to guess a number between 1 to 100 and compare it with a random number of that range. If user guessed number is lesser/greater than the random number print "too low" or "too high" accordingly. Take new input asking the user to guess the correct number again. When the guessed number matches with the random number print "you win" and the number of attempts the user required to guess it.
import random
u_num = int(input("guess a number between 1 to 100: "))
w_num = random.randint(1,100)
i = 1
while u_num != w_num:
    if u_num < w_num:
        print("too low")
    else:
        print("too high")
    u_num = int(input("guess again: "))
    i += 1
print(f"you win, and you guessed this number in {i} times!")


texts: Getting JSON with jQuery and creating lists with click events calling more jQuery and JSON

texts:
I have two elements on my page:

I'm calling some JSON with jQuery and loading elements in the divs. I'm curious if there are things I can be doing more efficiently, and better ways to use selectors and JSON.

$().ready(function() {
    //Load sections
    GetCarlineSections(_BucketID);
});

function GetCarlineSections(bucketID) {
    //Get section json list
    $.ajax(
    {
        type: "POST",
        url: _ApplicationRootURL + 'GetChildBucketList', //Call the ActionResult to return the JSON object
        data: 'parentID=' + bucketID,
        success: function (sections) { //'sections' is an array of JSON objects returned by GetChildBucketList
            $(sections).each(function () {
                $('#VerticalMenu') //Append each item to the #VerticalMenu

                    .append(
                        $('
') //Append a new
 element to
 #VerticalMenu
                        .addClass('Section')
                        .html(
                            $('
') //Create a new
 inside of the

                            .addClass(this.BucketName)
                            .html(this.BucketName)
                            .click({ parentID: this.BucketID }, function (event) { //Attach a click event to the
 element
                                $('#AccordionMenu').empty();
                                GetSectionSubSections(event.data.parentID); //Event.data.parentID is the id of the bucket represented by this
 element
                            })
                        )
                    );
            });
        }
    });
}

function GetSectionSubSections(bucketID) {
    $.ajax(
    {
        type: "POST",
        url: _ApplicationRootURL + 'GetChildBucketList',
        data: 'parentID=' + bucketID,
        success: function (SubSections) { //SubSections are the children buckets of Section, local var bucketID
            $(SubSections).each(function () {
                $('#AccordionMenu')
                    .append(
                        $('
')
                        .addClass('SubSection')
                        .html(
                            $('
')
                            .addClass(this.SEOURLName)
                            .html(this.BucketName)
                            .click({ parentID: this.BucketID }, function (event) { //Eventdata parentID passes the SubSectionID to the event object
                                GetSubSectionHeadlines(this, event.data.parentID)
                            })
                        )
                    );
            });
        }
    });
}

function GetSubSectionHeadlines(parentElement, SubSectionID) {
    //Get the Headlines based on the parent SubSection
    $(parentElement).after($('
').addClass(parentElement.className));
    $.ajax({
        type: 'POST',
        url: _ApplicationRootURL + 'GetChildBucketList',
        data: 'parentID=' + SubSectionID,
        success: function (Headlines) {
            $(Headlines).each(function () {
                $('ul.' + parentElement.className).prepend(
                    $('
')
                        .html(this.BucketName)
                )
            })
        }
    });
}


texts: Compare two arrays of objects and get the objects based on ids

texts:
I have two arrays of objects. One has an id property with a list of ids and the second has an object with a unique id property. I want to filter the ids in the second array with the first list and get the data.

const data1 = [{
  name: 'A',
  ids: [1, 2, 3]
}, {
  name: 'B',
  ids: [4, 5, 6]
}, {
  name: 'C',
  ids: [7, 8, 9]
}]

const data2 = [{
    id: 1,
    color: 'red'
  }, {
    id: 2,
    color: 'black'
  }, {
    id: 3,
    color: 'blue'
  }, {
    id: 4,
    color: 'yellow'
  }, {
    id: 5,
    color: 'green'
  }, {
    id: 6,
    color: 'pink'
  },
  {
    id: 7,
    color: 'orange'
  }, {
    id: 8,
    color: 'white'
  }, {
    id: 9,
    color: 'teal'
  }
]

const arrayToObject = (array) =>
  array.reduce((obj, item) => {
    obj[item.id] = item
    return obj
  }, {})

console.log(arrayToObject(data2))

const newData = data1.map(item => {
  return {
    name: item.name,
    data: item.ids.map(i => arrayToObject(data2)[i])
  }
})

console.log(newData)

Expected Output:
[
  {
    "name": "A",
    "data": [
      {
        "id": 1,
        "color": "red"
      },
      {
        "id": 2,
        "color": "black"
      },
      {
        "id": 3,
        "color": "blue"
      }
    ]
  },
  {
    "name": "B",
    "data": [
      {
        "id": 4,
        "color": "yellow"
      },
      {
        "id": 5,
        "color": "green"
      },
      {
        "id": 6,
        "color": "pink"
      }
    ]
  },
  {
    "name": "C",
    "data": [
      {
        "id": 7,
        "color": "orange"
      },
      {
        "id": 8,
        "color": "white"
      },
      {
        "id": 9,
        "color": "teal"
      }
    ]
  }
]

I did manage to achieve this, but I guess there might be a better clean and performant solution. Please advice me on that.
P.S: I am also open to using lodash.


texts: Parse and extract synonym data from a website

texts:
I made a method that finds synonyms to words using thesaurus.com and I'm looking for comments and feedback to it. In what ways can I improve it, both when it comes to speed, security, reliability (regardless of how "reliable" it is to rely on a third-party website for look-ups), etc.

    ///
    /// This method relies heavily on thesaurus.com for synonym lookups. It is not completely reliable, but is deemed reliable enough in instances where you dont have your own thesaurus
    ///
    public static string[] GetSynonyms(string word)
    {
        string url = string.Format("http://thesaurus.com/search?q={0}", word);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK)
        {
            List<string> synonyms = new List<string>();
            StringBuilder data = new StringBuilder();
            string line;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {

                //we know that the synonyms is in the upper-part of the html stream so we do not want to read the entire stream.
                while((line = reader.ReadLine()) != null) {
                    var index = line.IndexOf("");

                    if(index > 0)
                    {
                        index = index + "".Length;
                        synonyms.Add(line.Substring(index).Replace("", ""));
                    }

                    //break when we come to the Antonyms section of the page
                    if (line.Contains("container-info antonyms"))
                    {
                        break;
                    }
                }
            }
            return synonyms.ToArray<string>();
        }
        else
        {
            return null;
        }
    }

Edit: As an example, it now takes about 3.5 seconds to find the synonyms for the word "old".


texts: Any ideas how do I prettify this SQL query?

texts:
This question is abut coding style. I'd like to see how would you improve this code look considering readability as well. Feel free to upvote others solutions you find good.
#1 Initial version:
SELECT greatest(
  0,
  least(
    500,
    (SELECT g.c_daily_limit * (
        SELECT count(*)
        FROM rivals.t_rival_group_auth a
        WHERE a.id_group = g.id) - (
        SELECT count(*)
        FROM rivals.t_order_results rs
        JOIN rivals.t_rivals r ON r.id = rs.id_rival
        WHERE r.id_group = g.id
          AND rs.c_date_order::date = utils.getdate()::date
          AND (rs.c_price IS NOT NULL OR rs.c_failed IS NOT NULL))
      FROM rivals.t_rival_group g
      WHERE g.c_code = _code)
  )
);

#2 An alternative version, should improve readability of nested parameters:
SELECT greatest(
  0,
  least(
    500,
    (
      SELECT g.c_daily_limit * (
        SELECT count(*)
        FROM rivals.t_rival_group_auth a
        WHERE a.id_group = g.id
      ) - (
        SELECT count(*)
        FROM rivals.t_order_results rs
        JOIN rivals.t_rivals r ON r.id = rs.id_rival
        WHERE r.id_group = g.id
          AND rs.c_date_order::date = utils.getDate()::date
          AND (rs.c_price IS NOT NULL OR rs.c_failed IS NOT NULL)
      )
      FROM rivals.t_rival_group g
      WHERE g.c_code = _code
    )
  )
);


texts: Cleaning up code and making better loops for soccer shoot-out game

texts:
I'll start by saying I've just started with programming, and Ruby is my first language. I've made a little soccer shoot-out game. I'm having problems with the end of the code looping back to where I want it.

If there's a tie, I want it to keep the same score and players, but add another round of shooting. Should I do this by creating an array to store the points?

If there's anything else I can simplify, I'd really appreciate your input.

class Shoot
def initialize
    shoot
end

def shoot
    @kick = 1 + rand(6)
end

def kick
    @kick
end
end

response = ''
until response == 'N'
play = "Have another shoot-out? Put Y or N."

puts "Player 1's name is:"
player_1_name = gets.chomp

puts "Player 2's name is?"
player_2_name = gets.chomp

puts "#{player_1_name} and #{player_2_name}, are you ready to play sudden death   (ENTER)?!"
gets.chomp

p1_score = 0
p2_score = 0
result_1 = 0
result_2 = 0

until result_1 >= 1 || result_2 >= 1
  puts "#{player_1_name}, please take your kick (ENTER)."
  gets.chomp!
  shot_1 = Shoot.new.kick
  result_1 = shot_1*0.2
  puts "#{player_1_name} takes the shot, and it's looking good..."
  puts "(ENTER)"
  gets.chomp

  if result_1 >= 1
      puts "...And it's a goal!!!"
      p1_score += 1
  else
      puts "...Oh! So close, but it's no good!!!"
  end

  puts "#{player_2_name}, please take your kick (ENTER)."
  gets.chomp!

  shot_2 = Shoot.new.kick
  result_2 = shot_2*0.2
      puts "#{player_2_name} takes the shot, and it's looking good..."
  puts "(ENTER)"
  gets.chomp

  if result_2 >= 1
      puts "...And it's a goal!!!"
      p2_score += 1
  else
      puts "...Oh! So close, but it's no good!!!"
  end

puts "#{player_1_name}: #{p1_score}"
puts "#{player_2_name}: #{p2_score}"

if p1_score > p2_score
    puts "#{player_1_name}, you're the winner! Congratulations!"
elsif p1_score < p2_score
    puts "#{player_2_name}, you're the winner! Congratulations!"
else
    puts "Looks like we've gotta go another round!"
    return
end
end

puts play
response = gets.chomp
end


texts: I need help optimizing a function that returns all divisors

texts:
This is my code:
export function all_divisors(num: number): number[] {
    return range(1, num+1).filter(i => num % i === 0).toArray();
}

the range function(docs) is part of the IterPlus library and is a pretty self-explanatory inclusive-exclusive range function, again, what I'm doing using the filter function is pretty self-explanatory, .toArray() converts IterPlus<number> to an array number[].
Anyway, I'd like some help optimizing this, as it is pretty slow when working with larger numbers(it took ~190ms for 3,000,000 and ~3ms for 30,000).
I don't care about code-golfing, or meant to code-golf in the first place, it was just convienient at the time.


texts: Optimize parsing of number for currency conversion

texts:
I have written this working block, but is it optimized? I am getting currency in this format: 1.234,25.

public static String convertCurrency(String value, String exchangeCurrencyId)
{
    java.text.NumberFormat format = null;
    value = value.replaceAll("\\.", ",");
    char[] chars = value.toCharArray();
    chars[value.lastIndexOf(',')] = '.';
    value = new String(chars);
    value = value.replaceAll(",", "");
    Double price = Double.valueOf(value);
    price = price * (50); //exchange rate

    return price.toString();
}


texts:
I'm trying to write clean code, but I'm not so good with exception handling.
How can I improve this method? Or is it good enough already?

This method gets a hash from a file.

public String getLatestHash() {
    String hash = "none";

    URL packURL = null;
    try {
        packURL = new URL(ConfigManager.get("play_url") + "/" + HTMLParser.getPackName());
    } catch (MalformedURLException e) {
        logger.severe("invalid URL!");
        logger.severe(e.getMessage());
    }

    try (InputStream inputStream = packURL.openConnection().getInputStream()) {
        hash = DigestUtils.md5Hex(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return hash;
}


texts:
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

How can i improve the below solution?

    package com.alpha;

    import java.util.HashMap;
    import java.util.Map;

    public class DailyCodingProblem1 {
        public static void main(String args[]) {
            int[] arr = { 10, 15, 3, 7 };
            int k = 17;

            Boolean ans = solution(arr, k);
            System.out.println(ans);
        }

        private static Boolean solution(int[] arr, int k) {
            final Map<Integer, Boolean> map = new HashMap<>();
            for (int x : arr) {
                map.put(k - x, true);
            }
            for (int x : arr) {
                if (Boolean.TRUE.equals(map.get(Integer.valueOf(x)))) {
                    return true;
                }
            }
            return false;
        }
    }


texts: Preparing form data for a POST request with fetch

texts:
Acquiring a form’s data for asynchronous POST requests has been a long-standing problem. There is the FormData API, but there are still some obstacles when the form’s data is encoded as x-www-form-urlencoded (the default).

My current use case deals with arbitrary forms which might encode data either way; hence, I tried to generalize the way I construct the request’s body. Note that it’s intentional the form is submitted as an asynchronous request as the response is going to be rendered inside the current document.

Can this generalization be simplified further?

document.querySelector('form').addEventListener('submit', performPostRequest);

/**
 * Handles submit events that are about to perform a POST request.
 *
 * @param {Event} event
 */
function performPostRequest(event) {
  // Prevent the default action of sending a regular POST request.
  event.preventDefault();

  const form = event.target;

  fetch(form.action, {
    method: 'post',
    headers: {
      'Content-Type': `${form.enctype}; charset=UTF-8`
    },
    body: constructRequestBody(form)
  })
    .then(console.log)
    .catch(console.error);
}

/**
 * Encodes a form’s data for a POST request’s body.
 *
 * Supported encoding types:
 *
 * - `application/x-www-form-urlencoded`
 * - `multipart/form-data`
 *
 * @param {HTMLFormElement} form
 * @returns {FormData|URLSearchParams}
 */
function constructRequestBody(form) {
  const formData = new FormData(form);

  if (form.enctype === 'multipart/form-data') {
    return formData;
  }

  const requestBody = new URLSearchParams();

  for (const [name, value] of formData) {
    requestBody.append(name, value);
  }

  return requestBody;
}