texts:
I'm currently learning C# so I can make real games with Unity. This is the first C# program I've built in Unity. Essentially what is does is control the thrust, and rotation of a GameObject shaped like a rocket. It may not necessarily be "real physics" but for my first program, it's good enough.

using UnityEngine;
using System.Collections;

public class RocketController : MonoBehaviour
{
    public float thrustMultiplier;
    public float rotationSpeed;
    private bool applyThrust = false;

    void Start () { transform.forward = transform.up; }

    // Check for misc keypresses
    void CheckMiscKeys ()
    {
        // Start applying thrust
        if (Input.GetKey (KeyCode.Space))
        {
            applyThrust = true;
        }

        // Stop applying thrust
        if (Input.GetKey (KeyCode.LeftShift))
        {
            applyThrust = false;
        }
    }

    // Check for rotation keypresses
    void CheckRotationKeys ()
    {
        // Rotate forward
        if (Input.GetKey (KeyCode.W))
        {
            transform.Rotate (rotationSpeed * new Vector3 (1, 0, 0));
        }

        // Rotate backwards
        if (Input.GetKey (KeyCode.S))
        {
            transform.Rotate (rotationSpeed * new Vector3 (-1, 0, 0));
        }

        // Rotate left
        if (Input.GetKey (KeyCode.A))
        {
            transform.Rotate (rotationSpeed * new Vector3 (0, -1, 0));
        }

        // Rotate right
        if (Input.GetKey (KeyCode.D))
        {
            transform.Rotate (rotationSpeed * new Vector3 (0, 1, 0));
        }
    }

    // Apply thrust to the rocket's rigidbody
    void ApplyRocketThrust ()
    {
        if (applyThrust)
        {
            Vector3 force = transform.forward * thrustMultiplier;
            rigidbody.AddForce(force);
        }
    }

    // Run physics calculations and misc events
    void FixedUpdate ()
    {
        CheckMiscKeys ();
        CheckRotationKeys ();
        ApplyRocketThrust ();
    }
}

What can be improved? Is there anything I'm doing wrong here?


texts:
I'm currently reviewing some standard pieces of code I use a lot in projects.

Currently I'm using the following functions for password hashing.

function generate_salt($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789``-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[rand(0, $max)];

  return $str;
}

function hash_password($password, $salt, $iter=5) {
  $hash = sha1(sha1($password.$salt).sha1(strrev($password).strrev($salt)));

  for($i=0;$i<=$iter;++$i) {
     $hash = sha1(sha1($hash).sha1(strrev($hash)));
  }

  return $hash;
}

I will replace sha1() with hash('sha512', ).

Any other suggestions to make this more secure / to improve it?


texts:
Which one of these are better for the memory?

protected static List<Line> CreateBolt(Vector2 source, Vector2 dest, float thickness)
{
    //...

    for (int i = 1; i < positions.Count; i++)
    {
        float pos = positions[i];
        float scale = (length * Jaggedness) * (pos - positions[i - 1]);
        float envelope = pos > 0.95f ? 20 * (1 - pos) : 1;
        float displacement = Rand(-Sway, Sway);
        displacement -= (displacement - prevDisplacement) * (1 - scale);

        // ,,,
    }
    //...
}

protected static List<Line> CreateBolt(Vector2 source, Vector2 dest, float thickness)
{
    //...
    float pos;
    float scale;
    float envelope;
    float displacement;

    for (int i = 1; i < positions.Count; i++)
    {
        pos = positions[i];
        scale = (length * Jaggedness) * (pos - positions[i - 1]);
        envelope = pos > 0.95f ? 20 * (1 - pos) : 1;
        displacement = Rand(-Sway, Sway);
        displacement -= (displacement - prevDisplacement) * (1 - scale);

        // ,,,
    }
    //...
}

Should I declare variables before or inside a for loop? Does it even make a difference at all?


texts:
The full code is located here: https://gist.github.com/4521540

It's a dummy List in C++. My concern is with freeing up memory.
It doesn't crash when I run my code. It looks like my if/else covers everything.

It starts by deleting the second item if there is. That's what the while loop does.
If there is only one present (or left with one), delete startNode.

startNode is a pointer points to the first item in the list.
endNode always points to the last item in the list.

Am I deleting the pointer or the underlying object?

I do mostly Python. Last time I wrote a serious C++ homework was about 2 years ago in my algorithm class so I really can't remember everything off my head.

~List()
{
    // there is at least one item
    if(startNode != 0)
    {
        // release memory starting from the second item
        ListNode *current, *soon;
        current = this->startNode->next;
        while(current != 0)  // if there are at least two items
        {
            /* When there is no more items after current,
             * delete current and leave.
             * Otherwise, free up current and move on to
             * the next item.
             */
            if(current->next != 0)
            {
                soon = current->next;
                delete current;
                current = soon;
            }
            else
            {
                delete current;
                break;
            }

        }
    }

    delete this->startNode;
    delete this->endNode;
}

Also, do I need to delete the myList in my main program? I think when I exit the program, the destructor is automatically called.


texts: Determining whether a task is active based on many conditions

texts:
I wrote a Rails model instance method that checks many separate conditions, and returns a single boolean. It does not employ any nesting of branching structures. Each check has its own comments describing its reasoning. Every check is necessary for the method to return an accurate value, and none of the checks are likely to be reused independently of the other checks. The function is 34 lines long including comments. A colleague reviewing the code suggested that the method may be too long, and therefore would be more readable if broken out into multiple helper methods for greater readability.

def active?
  #Check columns on self first, so if those dont pass,
  #no other records will need to be loaded.
  return false if self[:active] == false && !ignore_column
  return false if self.suspended # here for thoroughness. tasks should never be marked active and suspended.
  return false if self.completed_at # here for thoroughness. tasks should never be marked active and completed.
  if failed_attempts >= MAX_FAILED_ATTEMPTS # here for thoroughness. tasks should never be marked active after the max failed attempts.
    if !suppress_error_emails
      SystemMailer.error message:"Too many failed attempts for task execution. #{failed_attempts}/#{MAX_FAILED_ATTEMPTS} failed attempts for Task #{id}."
    end
    return false
  end
  #If the origin is inactive and not because it is a withdrawn status, then the task should be inactive.
  return false if !evergreen && origin && !origin.active && origin.is_a?(Crm::Status) && !origin.indicates_closed # Status or Subscription

  return false if sequenceable.is_a?(Crm::Case) && sequenceable.sales_stage_id.to_i>Crm::SalesStage.id('Placed') #placed policies shouldn't fire tasks

  #Recruits are always marked inactive because they are users that can't log in.
  #If the person is inactive but not a recruit, the task should be inactive.
  is_a_recruit=person.try(:is_a?,Usage::User) && person.try(:role)==Usage::Role['recruit']
  return false if !person.try(:active) && !is_a_recruit

  if self.template
    template_purpose_id=self.template.template_purpose_id
    purposes=Marketing::Template::TEMPLATE_PURPOSE
    status_opted_out=self.person.status_unsubscribe && template_purpose_id==purposes["Status"][:id]
    con_mktg_opted_out=self.person.is_a?(Crm::Connection) && self.person.marketing_unsubscribe && template_purpose_id==purposes["Consumer Marketing"][:id]
    user_mktg_opted_out=self.person.is_a?(Usage::User) && self.person.marketing_unsubscribe && template_purpose_id==purposes["Agent Marketing"][:id]
    if status_opted_out || con_mktg_opted_out || user_mktg_opted_out
      return false
    end
  end

  return true
end

Is there a magic number of lines where a function or method becomes too long and should be broken out into multiple functions? If so, what is the magic number? Does it depend on the type of code (model/view/controller), or some other circumstance?


texts:
I'm a beginner in OOP and PHP frameworks.  I used slim skeleton to create a project and designed the project in this way.

Project structure is given by the slim skeleton. Object Mappers are added by my self. I want to know whether this is a good practice. What I'm doing wrong here. Is there any better way to do this?

src
   Controllers
      PostController.php
      CommentController.php
   Models
      Post.php
      Comment.php
   ObjectMappers
      PostMapper.php
      CommentMapper.php
   Dependencies.php
   Middleware.php
   Routes.php
   Settings.php

Model files are used to include queries for relevant class.
Mappers are the real classes that used to map query results to necessary class.
Controllers are for necessary operations before sending it to the user.

Post.php

namespace App\Models;

class Post {

   public function getPostById($id){

      $sql = "SELECT `post_id`, `post` FROM `posts` WHERE `post_id` = :id";

      try {
         $stmt = $this->db->prepare($sql);
         $stmt->execute(['id' => $id]);
         $post = $stmt->fetchObject('\App\ObjectMappers\PostMapper');
         if($post){
            return $post;
         }
         return false;
      } catch (\PDOException $e){
         return false;
      }
   }

   // Other queries
}

PostMapper.php

namespace App\ObjectMappers;

class PostObject {

    public $post_id;
    public $post;

    public function __construct(){}

    public function getPost_id()
    {
        return $this->post_id;
    }

    public function setPost_id($post_id)
    {
        $this->post_id= $post_id;
        return $this;
    }

    public function getPost()
    {
        return $this->post;
    }

    public function setPost($post)
    {
        $this->post= $post;
        return $this;
    }
}

PostController.php

namespace App\Controllers;

class PostController {

   public function ($request, $response, $args){

      $postId = $request->getAttribute("post_id");

      if(!$postId){
         return $response->withJSON("post id not found");
      }
      $post = $this->Post->getPostById($postId);

      if(!$post ){
         return $response->withJSON("post not found");
      }

      return $response->withJSON($post);
   }
}

I'll be glad if you can help me. I'm trying to avoid using existing ORMs here.


texts: Project Euler #1 Sum of multiples of 3 and 5

texts:
Given:

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

Solution:

class Main {
  public static int sumMupltiple(int num, int limit) {
      int numOfMulitples = (limit - 1) / num;
      return num * (numOfMulitples * (numOfMulitples + 1) / 2);
  }

  public static void main(String[] args) {
    System.out.println(
        sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));

  }
}

Is there a clearer approach for Java?


texts:
Here is my method that I use to get one entity in an ASP.NET Web API application.

[EnableQuery]
public virtual HttpResponseMessage GetById([FromODataUri]int id)
{
    // get concrete entity from repository
    var entity = repository.GetById(id);
   // check entity
    if (entity == null)
    {
        var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
        return ErrorMsg(HttpStatusCode.NotFound, message);
    }

    // problem
    return Request.CreateResponse(HttpStatusCode.OK, SingleResult.Create(repository.Table.Where(t => t.ID == id)));
}

I'm using SingleResult for OData request (because $expand for single entity does not work if I do not create SingleResult). But in this case I repeatedly do almost the same action repository.GetById(id); and repository.Table.Where(t => t.ID == id).

How can I improve it?


texts: Calculating luma of a rect in an image of .yuv format

texts:
I'm trying to get the average luma of an area in an YUV image in the Android camera. I have come up with the following code which I think is correct and produces consistent results.

private static final int AVERAGE_LUMA_SAMPLE_SIZE = 2;

// sample the average luma
// yuvImage is the byte data return from a camera's previewFrame
public static int getAverageLuma(byte[] yuvImage, int imageWidth, int imageHeight, RectF sampleArea) {
    int totalLuma = 0;
    int totalSampled = 0;

    int top = (int)Math.max(sampleArea.top, 0);
    int left = (int)Math.max(sampleArea.left, 0);
    int right = (int)Math.min(sampleArea.right, imageWidth);
    int bottom = (int)Math.min(sampleArea.bottom, imageHeight);

    for(int i = top; i < bottom; i += AVERAGE_LUMA_SAMPLE_SIZE) {
        int rowStartPosition = (i * imageWidth) + left;

        for (int j = 0; j < right; j += AVERAGE_LUMA_SAMPLE_SIZE) {
            int bytePostion = rowStartPosition + j;
            int y = (0xff & ((int) yuvImage[bytePostion])) - 16;

            totalLuma += Math.max(y, 0);
            totalSampled++;
        }
    }

    return Math.round((float)totalLuma / totalSampled);
}


texts: Find kth smallest element in binary search tree

texts:
I was faced with below interview question today and I came up with below solution but somehow interviewer was not happy. I am not sure why..

  Given a binary search tree, find the kth smallest element in it.

Is there any better or more efficient way to do this problem?

  /*****************************************************
   *
   * Kth Smallest Iterative
   *
   ******************************************************/

  public int kthSmallestIterative(TreeNode root, int k) {
    Stack<TreeNode> st = new Stack<>();

    while (root != null) {
      st.push(root);
      root = root.left;
    }

    while (k != 0) {
      TreeNode n = st.pop();
      k--;
      if (k == 0)
        return n.data;
      TreeNode right = n.right;
      while (right != null) {
        st.push(right);
        right = right.left;
      }
    }

    return -1;
  }

I mentioned time and space complexity as O(n). My iterative version takes extra space. Is there any way to do it without any extra space?


texts: Search for the longest sequence of toggled consecutive bits in an integer

texts:
I have to do a function called findsaw. This function searches for the longest sequence of toggled consecutive bits in an integer and returns the index of the first bit of the sequence, the sequence must start from the least significant bit.

In the case there are multiple answers(sequences with same size) choose the one with lowest start index.

Function signature:

unsigned int findsaw(int value)

Some test cases:

findsaw(0x0) returns 0
findsaw(0xAA) returns 0
findsaw(0xA0F) returns 8
findsaw(0xF0A) returns 0
findsaw(0xFA0) returns 4
findsaw(0xEAEA476BL) returns 23

My code:

#include <stdio.h>
#define YES 1 /* inside a sequence */
#define NO 0 /* outside a sequence */

unsigned int findsaw(int value){
    unsigned int sequence = value;
    unsigned char idx = 0;
    unsigned char sequenceIdx = 0;
    unsigned char currentIdx = 0;
    unsigned char size = 0;
    unsigned char sequenceSize = 0;
    unsigned char bit = value & 1;
    unsigned char nextBit;
    unsigned char insideSequence = NO;

    while (sequence){
        sequence>>= 1;
        nextBit = sequence & 1;
        if(bit ^ nextBit){
            if(insideSequence){
                sequenceSize++;
            }
            else{
                sequenceSize = 2;
                sequenceIdx = currentIdx;
                insideSequence = YES;
            }
        }
        else{
            if(size < sequenceSize){
                size = sequenceSize;
                idx = sequenceIdx;
            }
            insideSequence = NO;
            sequenceSize = 0;
        }
        currentIdx++;
        bit = nextBit;
    }
    if(size < sequenceSize){
        idx = sequenceIdx;
    }
    return idx;
}

What would be the correct output for all 1's like findsaw(0xF), my function returns the index of the last bit, in this case 3?


texts: How can I speed up my RSS feed Android App?

texts:
I have a problem with parsing RSS from a PHP page because the app is too slow.

This is my parsing code:

public void getdataparse(String url) {

    Log.d("Do in Background","Start Call Void");

    String dbtitle = "";
    String dbDesc = "";
    String dbimgicon = "";
    String dbimg = "";
    String dblink = "";
    String dbpubdate = "";
    String dborderStg = "";
    String dbsourcename = "";
    String dbimagecheck = "";
    int dbfff = 0;

        try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new URL(url).openStream());

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("item");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                dbtitle = "";
                dbDesc = "";
                dbimgicon = "";
                dbimg = "";
                dblink = "";
                dbpubdate = "";
                dborderStg = "";
                dbsourcename = "";
                dbimagecheck = "";
                dbfff = 0;
                Datemx = 0;
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    dbtitle = getTagValue("title", eElement);

                    dbDesc = getTagValue("description", eElement);

                    String[] timeformated = new String[2];

                    timeformated = gettime(getTagValue("pubdate", eElement));

                    dbpubdate = timeformated[0];

                    dborderStg = timeformated[1];

                    Log.d("pubDate = ", "" + dbpubdate + "OrderStg = " + dborderStg);

                    dblink = getTagValue("link", eElement);

                    dbimgicon = getTagValue("sicon", eElement);

                    dbimg = "http://s14.postimg.org/cs10sq11d/whitemega.png";

                    dbsourcename = getTagValue("sname", eElement);

                    dbimagecheck = "";

                    dbfff = Datemx;

                    handler = new DataHandler(getBaseContext());
                    handler.open();
                    long id = handler.insertrssfeedData(dbtitle, dbDesc, dbimg, dbimgicon, dblink, dbpubdate, dbfff, dbsourcename , dbimagecheck);
                    handler.close();

                    Log.d("Add New Recorde","Record = " + temp + "/n Title = " + dbtitle);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The PHP page URL

The PHP code


texts:
Write a method mirror that accepts a stack of integers as a
  parameter and replaces the stack contents with itself plus a mirrored
  version of itself (the same elements in the opposite order). For
  example, suppose a variable s stores the following elements:

  bottom [10, 50, 19, 54, 30, 67] top

  After a call of mirror(s);, the stack would store the following
  elements (underlined for emphasis):

  bottom [10, 50, 19, 54, 30, 67, 67, 30, 54, 19, 50, 10] top

  Note that the mirrored version is added on to the top of what was
  originally in the stack. The bottom half of the stack contains the
  original numbers in the same order. If your method is passed an empty
  stack, the result should be an empty stack. If your method is passed a
  null stack, your method should throw an IllegalArgumentException.

  You may use one stack or one queue (but not both) as auxiliary storage
  to solve this problem. You may not use any other auxiliary data
  structures to solve this problem, although you can have as many simple
  variables as you like. You may not use recursion to solve this
  problem. For full credit your code must run in O(n) time where n is
  the number of elements of the original stack. Use the Queue interface
  and Stack/LinkedList classes from lecture.

I'm looking for ways to improve my future programming. Is this a good way to solve this problem? Currently, I'm surprised with the amount of work I'm doing with these Stacks and Queues data structures.

Yes, I know I'm being asked to use these data structures to solve the problem. But maybe there are ways that I need to think outside of the box to accomplish the same task?

I'm also looking for any bugs my code might have, so definitely let me know if you find any!

public static void mirror (Stack<Integer> s) {

    if (s == null) {
        throw new IllegalArgumentException();
    }

    Queue<Integer> q = new LinkedList<Integer>();

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    int size = q.size();
    for (int i = 0; i < size; i++) {
        int valq = q.poll();
        s.push(valq);
        q.offer(valq);
    }

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }
}


texts:
I'm writing a method that generates a random integer array that are sorted. It takes the arguments of min value, max value and the length of desired array. So for example the arguments with min val = 1 max val = 10 length = 5 could give [1,1,2,3,5,6,9,9,9,10] or [2,4,5,6,6,6,6,6,6,8]. Let me know if the specifications are unclear and I'll elaborate.

Here is my code; it works but is a bit messy:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Random;

public class test {
    public static void main(String[] args)
    {
        System.out.println(Arrays.toString(generateSorted(10, 0, 100)));
    }

    public static int[] generateSorted(final int length, final int minVal, final int maxVal)
    {
        ArrayList<Integer> data = new ArrayList<>(length);
        data.add(getRandomVal(minVal, maxVal));

        boolean added;
        for(int i = 0; i < length; i++)
        {
            added = false;
            ListIterator<Integer> itr = data.listIterator();
            int rndNum = getRandomVal(minVal, maxVal);
            while(itr.hasNext() && !added)
            {
                Integer currentNum = itr.next();
                if(currentNum >= rndNum)
                {
                    itr.previous();
                    itr.add(rndNum);
                    added = true;
                }
            }

            if(!added)//add to end of arrayList
            {
                data.add(rndNum);
            }
            //printArrList(data);
        }

        return data.stream().mapToInt(i -> {
            return i;
        }).toArray();
    }

    /*prints contents of arraylist all on 1 line*/
    public static void printArrList(ArrayList<Integer> al)
    {
        System.out.print("[");
        /*this could be replaced with a for (each) loop*/
        al.stream().forEach((i) -> {
            System.out.print(i+", ");
        });
        System.out.println("]");
    }

    /*returns random int between [min, max]*/
    private static int getRandomVal(int min, int max)
    {
        int n = max - min + 1;
        int i = rand.nextInt(n);//nextInt(n) returns random int in [0, n)
        return min + i;
    }
    final static private Random rand = new Random();
}


texts:
In a project I decided to parse a file and create functions during compilation to speed up rendering of a payroll template. I had (or still have?) a hard time grasping macros in Elixir so I started experimenting in a smaller scale. This was the winner and it also worked out in the project:

defmodule Swapper do
  defmodule Helper do
    defmacro make_custom_swapper(name, left, right) do
      quote bind_quoted: [n: name, l: left, r: right] do
        def unquote(:"#{n}_swapper")(unquote(l)), do: unquote(r)
        def unquote(:"#{n}_swapper")(unquote(r)), do: unquote(l)
      end
    end
  end

  defmodule Maker do
    require Helper
    defmacro generate_multiple_custom_swappers(pairs) do
      quote do
        for {n,l,r} <- unquote(pairs) do
          Helper.make_custom_swapper(n,l,r)
        end
      end
    end
  end
end

defmodule TestingGrounds do
  require Swapper.Maker
  require Swapper.Helper

  # testing Helper
  Swapper.Helper.make_custom_swapper(:lofa,:a,27)

  letters = String.split("abcdefghijklmnopqrstuvwxyz", "", trim: true)
  letter_swapper_list =
    for l <- letters do
      {:letter, l, String.upcase(l)}
    end

  things_to_swap = [{:eclipse, "moon", "sun"}|letter_swapper_list]

  # the big guns
  Swapper.Maker.generate_multiple_custom_swappers(things_to_swap)
end

I'm glad that it works but getting to this solution involved adding more stuff where I got lucky. It feels exactly like this when I first discovered &/1 that seemed like the solution to everything:

defmodule A do
  def massage(string) do
    string
    |> (&splitter/1).() # == splitter
  end

  defp splitter(str) do
    str
    |> String.split("")
  end
end


texts:
So I solved Fractional Knapsack problem:

  There are n items in a store. For i =1,2, . . . , n, item i has weight wi > 0 and worth vi > 0. Thief can carry a maximum weight of W pounds in a knapsack. In this version of a problem the items can be broken into smaller piece, so the thief may decide to carry only a fraction xi of object i, where 0 ≤ xi ≤ 1. Item i contributes xiwi to the total weight in the knapsack, and xivi to the value of the load.
  In Symbol, the fraction knapsack problem can be stated as follows.
  maximize nSi=1 xivi subject to constraint nSi=1 xiwi ≤ W
  It is clear that an optimal solution must fill the knapsack exactly, for otherwise we could add a fraction of one of the remaining objects and increase the value of the load. Thus in an optimal solution nSi=1 xiwi = W

import java.util.Scanner;

public class FractionalKnapsack{

 static int[] value;
 static int[] weight;
 static float[] ratio;
 static int knapSackWeight;

 static void getMaximumBenefit() {

     int currentWeight = 0;
     float benefit = 0;

     while(currentWeight < knapSackWeight) {

        int item = getMaxRatioItem();

        //No items left
        if(item == -1) {

            break;
       }

       for(int i=0;i<weight[item];i++) {

           if(currentWeight+ratio[item]<=knapSackWeight) {
               currentWeight++;
               benefit = benefit + ratio[item];
            }
       }

        //Removing the item from array
        ratio[item] = 0;
     }

    System.out.println("Weight: " + currentWeight + " Benefit: " + benefit);

 }

static int getMaxRatioItem() {

    float maxRatio = 0;
    int ratioIndex = -1;

    //Getting max ratio
    for(int i=0;i < ratio.length;i++) {

        System.out.println(ratio[i]);

        if(ratio[i] > maxRatio) {

            maxRatio = ratio[i];
            ratioIndex = i;
        }
    }

    return ratioIndex;
}

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    value = new int[n];
    weight = new int[n];
    ratio = new float[n];

    for (int i = 0; i < n; i++) {
        weight[i] = in.nextInt();
        value[i] = in.nextInt();
        ratio[i] = (float)value[i] / weight[i];
    }

   knapSackWeight = in.nextInt();

    getMaximumBenefit();

}
}

Is there any better solution? The running time will be n^2?


texts: Implementation of Graham Scan algorithm in Haskell

texts:
Here is an implementation of Graham Scan algorithm for computing the convex hull of a finite set of points:

data Point = Point {
  xcoord :: Double,
  ycoord :: Double
} deriving (Show)

data Direction = ToRight | Straight | ToLeft  deriving (Show, Eq)

distance :: Point -> Point -> Double
distance a b = sqrt (((xcoord a) - (xcoord b))^2 + ((ycoord a) - (ycoord b))^2)

-- The direction function can be simplified after some algebraic analysis:
direction :: Point -> Point -> Point -> Direction
direction a b c
  | s < 0 = ToRight
  | s == 0 = Straight
  | s > 0 = ToLeft
  where
    s = ((xcoord c) - (xcoord a)) * ((ycoord a) - (ycoord b)) + ((ycoord c) - (ycoord a)) * ((xcoord b) - (xcoord a))

directions_ :: [Point] -> [Direction]
directions_ [] = []
directions_ [_] = []
directions_ [_, _] = []
directions_ (a:b:c:xs) = (direction a b c) : (directions_ (b:c:xs))

directions :: [Point] -> [Direction]
directions xs = ToLeft : ToLeft : (directions_ xs)

lowestYPoint :: [Point] -> Point
lowestYPoint [x] = x
lowestYPoint (x:xs)
  | (ycoord x) <= (ycoord lowestRest) = x
  | otherwise = lowestRest
  where
    lowestRest = lowestYPoint xs

cosineAB :: Point -> Point -> Double
cosineAB a b = ((xcoord b) - (xcoord a)) / (distance a b)

sortByAngle :: Point -> [Point] -> [Point]
sortByAngle x xs = sortBy comparePoints xs where
  comparePoints :: Point -> Point -> Ordering
  comparePoints a b
    | cA > cB = LT
    | cA < cB = GT
    | otherwise = case () of
      _ | xA < xB  -> LT
        | xA > xB  -> GT
        | xA == xB -> case () of
          _ | yA < yB   -> LT
            | yA > yB   -> GT
            | yA == yB  -> EQ
    where
      yA = (ycoord a)
      yB = (ycoord b)
      xA = (xcoord a)
      xB = (xcoord b)
      cA = (cosineAB x a)
      cB = (cosineAB x b)

grahamScanDirections :: [Direction] -> [Bool]
grahamScanDirections [] = []
grahamScanDirections [_] = [True]
grahamScanDirections (ToLeft:ToRight:xs) = False : (grahamScanDirections (ToLeft:xs))
grahamScanDirections (ToLeft:ToLeft:xs)  = True  : (grahamScanDirections (ToLeft:xs))
grahamScanDirections (ToLeft:Straight:xs) = False : (grahamScanDirections (ToLeft:xs))
grahamScanDirections _ = error "Impossible scenario"

filterByList :: [Bool] -> [a] -> [a]
filterByList [] _ = []
filterByList _ [] = []
filterByList (x:xs) (y:ys)
  | x = y : (filterByList xs ys)
  | otherwise = (filterByList xs ys)

grahamScan :: [Point] -> [Point]
grahamScan ps = filterByList bool_list ps1 where
  -- sort ps by their angles (or cosine values) formed with the lowest point
  ps1 = sortByAngle (lowestYPoint ps) ps
  bool_list = grahamScanDirections $ directions ps1

Test:

*Main> let ps = [(Point 1 0), (Point 1 2), (Point 0 3), (Point 2 3), (Point 2 2), (Point 3 2), (Point 2 1)]
*Main> grahamScan ps
[Point {xcoord = 1.0, ycoord = 0.0},Point {xcoord = 3.0, ycoord = 2.0},Point {xcoord = 2.0, ycoord = 3.0},Point {xcoord = 0.0, ycoord = 3.0}]

Any suggestion about correctness/performance or any other possible improvement is appreciated.


texts:
I wrote this code over the last few days and I learned a lot, and it works as I expect. However I suspect it's woefully inefficient:

import requests, bs4, os

os.chdir('../../Desktop')
wallpaperFolder = os.makedirs('Wallpapers', exist_ok=True)

pageCount = 1
GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)

linkList = []
while not GalleryUrl.endswith('page=3'):
    # Download the page
    GalleryUrl = 'https://wall.alphacoders.com/search.php?search=Game+Of+Thrones&page=%s' % (pageCount)
    print('Opening gallary... %s' % (GalleryUrl))
    res = requests.get(GalleryUrl)
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # find urls to image page
    section = soup.find_all('div', attrs={'class': 'boxgrid'})

    for images in section:
        imageLink = images.find_all('a')
        for a in imageLink:
            imageUrl = a.get('href')
            linkList.append(imageUrl)
            print('Image found at... ' + imageUrl)
    linkCount = 0
# Follow links and download images on page.
    while linkCount != len(linkList):
        print('Downloading image at... %s' % (str(linkList[linkCount])))
        imagePageUrl = ('https://wall.alphacoders.com/' + str(linkList[linkCount]))
        res = requests.get(imagePageUrl)

        wallpaperSoup = bs4.BeautifulSoup(res.text, 'html.parser')

        link = wallpaperSoup.find(id='main_wallpaper')
        imageSrc = link['src']

        # Save image to folder

        res = requests.get(imageSrc)
        imageFile = open(os.path.join(os.getcwd(), 'Wallpapers', os.path.basename(imageSrc)), 'wb')
        for chunk in res.iter_content(12000):
            imageFile.write(chunk)
        imageFile.close()
        linkCount += 1

    # Move to next page and empty link list
    pageCount += 1
    del linkList[:]

print('Done')

Aside from cutting the print statements and simply letting the program do its thing, how could I optimize this code to run more efficiently?


texts:
Given a binary tree, determine if it is a valid binary search tree
  (BST).

  Assume a BST is defined as follows:

  The left subtree of a node contains only nodes with keys less than the
  node's key. The right subtree of a node contains only nodes with keys
  greater than the node's key. Both the left and right subtrees must
  also be binary search trees.

Example 1:

  2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

 5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

My solution

Do inorder traversal and keep it in stack.
Iterate through stack to see if any of the value on top is less than equal to second top.

Definition for a binary tree node.

 public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode(int x) { val = x; }
  }

class Solution {

    public void doInOrderTraversal(TreeNode root, Stack s) {
        if(root == null) {
            return;
        }
        doInOrderTraversal(root.left, s);
        s.push(root.val);
        doInOrderTraversal(root.right, s);

    }

    public boolean isValidBST(TreeNode root) {

        if(root == null) {
            return true;
        }

        Stack<Integer> stack = new Stack<>();

        doInOrderTraversal(root, stack);

        while(!stack.isEmpty()) {
            int top = stack.pop();
            if(stack.isEmpty()) {
                return true;
            }
            int secondTop = stack.peek();
            if(top <= secondTop) {
                return false;
            }
        }
        return true;
    }
}

I was thinking to not use stack, but two values current and previous. And keep check if current is less than previous then only break. I am not sure, how to do this. Please suggest.


texts:
I am trying to make a router in Rust using Rocket.rs. I'd like to devise a way to use a default router for my more simple db tables that don't require different logic, to prevent rewriting the same functions over and over and only replacing just the type of output and input it takes.

struct Router<T> {
    router_type: T,
}

trait DefaultRouter<T> {
    #[get("/")]
    pub fn get_list(&self, connection: DbConn) -> Result<Json<Vec<T>>, Failure>;

    #[get("/<id>")]
    pub fn get(&self, id: String, connection: DbConn) -> Result<Json<T>, Failure>;

    #[post("/", format = "application/json", data = "<data>")]
    pub fn insert(&self, data: T, connection: DbConn) -> Result<status::Created<Json<T>>, Failure>;

    #[put("/<id>", format = "application/json", data = "<data>")]
    pub fn update(&self, id: String, data: Json<T>, connection: DbConn) ->
        Result<status::Created<Json<T>>, Failure>;

    #[delete("/<id>")]
    pub fn delete(&self, id: String, connection: DbConn) -> Result<status::NoContent, Failure>;

    fn created(&self, data: T) -> status::Created<Json<T>>;
    fn error_status(error: Error) -> Failure;
    fn host() -> String;
    fn port() -> String;
}

impl <T> DefaultRouter<T> for Router<T> {
    #[get("/")]
    pub fn get_list(&self, connection: DbConn) -> Result<Json<Vec<T>>, Failure> {
        //...
    }
}

What this code attempts to do is to apply the functionality defined in the trait to a given router_type. I want to be able to return data of a specific schema type without needing to define this functionality for each individual schema I have defined. Does this approach align with the intentions of rust? Or is there something better? I am still definitely a beginner, so any constructive criticism is welcome.


texts: CultureInfo with fallback routing to another language

texts:
Our company needs a localization/translation behavior which allows incomplete (ResX) resources.
If a String

isn't available in italian
fall back to the next roman language, like french
fall back to our invariant (in this case: german)

The easiest approach was a custom CultureInfo.

/// <summary>
/// A <see cref="CultureInfo" /> which switches to another language instead of  <see cref="CultureInfo.InvariantCulture" />.
/// </summary>
public class FallbackCultureInfo : CultureInfo
{
    private static readonly List<FallbackCultureInfo> CultureInfos = new List<FallbackCultureInfo>();
    private readonly CultureInfo fallback;
    private CultureInfo determinedParent;

    public override CultureInfo Parent
    {
        get
        {
            if (this.determinedParent != null)
            {
                return this.determinedParent;
            }

            var originalParent = base.Parent;
            if (Object.Equals(originalParent, CultureInfo.InvariantCulture) && (this.fallback != null))
            {
                return this.determinedParent = this.fallback;
            }

            if (this.fallback == null)
            {
                return this.determinedParent = originalParent;
            }

            this.determinedParent = FallbackCultureInfo.Build(originalParent.Name, this.fallback.Name);
            return this.determinedParent;
        }
    }

    private FallbackCultureInfo(String name, CultureInfo fallback = null) : base(name)
    {
        this.fallback = fallback;
    }

    /// <summary>
    /// Builds a <see cref="CultureInfo"/> with a custom fallback behavior, which switsches to
    /// another language before it gets <see cref="CultureInfo.InvariantCulture"/>.
    /// </summary>
    /// <example>
    /// CultureInfo.CurrentUICulture = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
    /// </example>
    /// <remarks>
    /// Due to a missing <see cref="CultureInfo" />.operator== we have to ensure a unique instance per name on our own.
    /// </remarks>
    /// <param name="name">Name of our culture, like "en-US"</param>
    /// <param name="fallbacks">Fallback stack, like "en-GB", "fr-FR"</param>
    /// <returns>The build <see cref="CultureInfo"/>.</returns>
    public static FallbackCultureInfo Build(String name, params String[] fallbacks)
    {
        lock (FallbackCultureInfo.CultureInfos)
        {
            return FallbackCultureInfo.QueuedBuild(new[] { name }.Concat(fallbacks).Reverse());
        }
    }

    private static FallbackCultureInfo QueuedBuild(IEnumerable<String> names)
    {
        FallbackCultureInfo result = null;
        FallbackCultureInfo lastFallback = null;
        foreach (var name in names)
        {
            result = FallbackCultureInfo.CultureInfos.FirstOrDefault(ci => String.Equals(ci.Name, name));
            if (result != null)
            {
                lastFallback = result;
                continue;
            }

            result = lastFallback = new FallbackCultureInfo(name, lastFallback);
            FallbackCultureInfo.CultureInfos.Add(result);
        }

        return result;
    }
}

CultureInfo.CurrentUICulture = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");

Works like a charm at a first glance.

But because it is located at a general .Net position, I would like to ask for other opinions about this way to solve the problem. Has anyone done a similiar approach which failed somehow - or even if you havent - do so see any issues with it?


texts:
I wrote the following code to generate a series of barcodes given a CSV with a list of ISBNs in the first column and titles in the second, using the python-barcode library (which itself requires pillow to generate PNGs and JPGs). I am fairly new with Python and have had little formal training, and so would be interested in any and all feedback regarding functionality, formatting, and anything else I might be missing.

import os
import csv
import barcode
from barcode.writer import ImageWriter

def create_code_png(isbn,title):
    """Creates barcode, gives ISBN and title"""
    isbn13 = barcode.get_barcode_class('ean13')
    return isbn13(isbn, writer = ImageWriter())

def remove_forbidden(string_in):
    """Removes characters forbidden from windows file names from a string"""
    forbidden_chars = ":;<>\"\\/?*|."
    return "".join([char for char in string_in if char not in forbidden_chars])

def codes_from_csv(list_location,destination_folder):
    """Creates PNG Barcodes from a csv, placing them in a given folder"""
    with open(list_location, newline='') as csvfile:
        os.chdir(destination_folder)
        for row in csv.reader(csvfile, dialect='excel'):
            code = create_code_png(isbn:=row[0],title:=remove_forbidden(row[1]))
            code.save(isbn + " " + title)

if __name__ == "__main__":
    codes_from_csv("P:\\barcodes.csv","E:\\Barcodes")


texts: ActiveRecord SQL search with a filter based on parameters

texts:
For work, my colleague and I sketched this method up as a brain dump of how we want this method to work. What I am trying to figure out is how can we break this method into smaller components so that it is easier to test to write tests for this. I am trying to avoid putting this into methods where they are coupled by parameters.

def self.for_venue(venue, options = {})
  filter = options[:filter]

  date_conditions = case options[:date]
  when 'upcoming' then  'e.datetime > :datetime'
  when 'past'     then  'e.datetime < :datetime'
  end

  sql_query = [
    "SELECT #{search_fields}",
    "FROM events e #{search_joins}",
    "WHERE " +  [date_conditions, "e.venue_id = #{venue.id}", "e.deleted = 0"].reject(&:nil?).join(" AND ")
  ]
  if options[:limit].present?
    sql_query << "LIMIT #{options[:limit]}"
    sql_query << "OFFSET #{options[:offset]}" if options[:offset].present?
  end
  sql_query << "ORDER BY #{options[:order]}" if options[:order].present?

  sql = ActiveRecord::Base.prepare_sql([sql_query.join(" "), { :datetime => Time.now.beginning_of_day }])
  results = SlaveDB.connection.select_all(sql)

  filter ? filter.select(results) : results
end


texts: removing the properties based on another object - better way

texts:
Based on userAccessData Object i need to filter the properties so what ever properties inside the fields are there they will be exist in the updatedValue, i am able to do it.

also one more thing if the ouput is an empty object then there is no need to have that object want to remove that also

i have tried the below code. its working but is there any better way and how should i remove the empty object

const userAccessData = {
  forms: {
    student: [
      {
        studentDetails: ['read', 'create', 'update'],
      },
    ],
    class: [
      {
        classDetails: ['read', 'create', 'update'],
      },
      {
        classSecondaryDetails: ['read', 'create', 'update'],
      },
    ],
    school: [
      {
        schoolContact: ['read', 'create', 'update'],
      },
      {
        schoolAddress: ['read'],
      },
      {
        schoolBasicDetails: ['read', 'create'],
      },
      {
        schoolLocationDetails: ['read', 'create', 'update'],
      },
    ],
  },
  fields: {
    school: {
      schoolAddress: [
        {
          isAddress: ['read', 'update'],
        },
      ],
      schoolLocationDetails: [
        {
          status: ['read'],
        },
      ],
      schoolContact: [
        {
          contactAddress: ['read'],
        },
        {
          contactStatus: ['read', 'create'],
        },
      ],
    },
    student: {
      studentDetails: [
        {
          isAvailable: ['read'],
        },
      ],
    },
    class: {
      classDetails: [
        {
          classId: ['read', 'create', 'update'],
        },
      ],
    },
  },
};

let updatedValue = {
  values: {
    schoolContact: {},
    schoolLocationDetails: {
      status: '123',
    },
    schoolAddress: {
      isAddress: 'yes',
      status: 'no'
    },
  }
};

const updateDetailsWithAccess = (updatedData, accessListData, selectedSection) => {
  const accessForms = Object.keys(accessListData[selectedSection]);
  Object.keys(updatedData.values).forEach((o) => {
    if (accessForms.indexOf(o) === -1) {
      delete updatedData.values[o];
    }
  });

  Object.keys(updatedData.values).forEach((o) => {
    const accessFormsForFields = accessListData[selectedSection][o].map(field => Object.keys(field)[0])
    Object.keys(updatedData.values[o]).forEach((field) => {
      if (accessFormsForFields.indexOf(field) === -1) {
        delete updatedData.values[o][field];
      }
    });
  });
  return updatedData;

};

console.log(updateDetailsWithAccess(updatedValue, userAccessData.fields, 'school'))

expected output

{
  "values": {
    "schoolLocationDetails": {
      "status": "123"
    },
    "schoolAddress": {
      "isAddress": "yes"
    }
  }
}


texts: Error handling in controller (MVC structure)

texts:
Lately, I'm using domain model pattern, and my controllers methods often looks like (yii2 example, verify user in loyalty system with Ajax response).

if (LoyaltyDomModel::loyaltyVerification($post_data)) {

    if (LoyaltyDomModel::setVerify(Yii::$app->user->identity, $post_data)) {

        return  ['body'=>'successfull','status' => true];
    }
    else {
        return  ['body'=>'unable update user','status' => 'error'];
    }
}
else {
    return  ['body'=>'errorcardno','status' => 'error'];
}

If logic is more complex I have a lot of if statement with model methods which return bool values, for example (I'm trying to decouple models logic in atomic methods), and it looks like not healthy. Should I encapsulate logic of return errors in models? What is best practices?


texts: Scheme function to duplicate every element of a list a specified number of times

texts:
This code takes a list and a integer and duplicates every element in the list the specified number of times.

(define (super-duper source count)
        (define (next-super source left)
                (if (zero? left)
                        (super-duper (cdr source) count)
                        (cons (super-duper (car source) count) (next-super source (- left 1)))))

        (if (pair? source)
                (cons (super-duper (car source) count) (next-super source (- count 1)))
                source))

(display(super-duper '((x y) t) 3))


texts: Can my responsive-tables JS code be made more performant?

texts:
I was using dataTables.net's responsive plugin before this, and am happy to say that my (much simpler) code runs about 5 times quicker than that did.  On my machine the fiddle averages about 50ms versus 250ms if I use DT responsive.

Is there anything I should do to improve performance of my code? Can it be made better?  I'm FAR from a JS expert, as I'm sure it shows.  I'm very happy to drop jQuery if it can be done better without!

Here's a working JS fiddle.

function initResponsiveTables() {
    //does this enhance performance at all?
    'use strict';

    //get an array of <th> elements
    var th = $('th');

    //initialise in top scope
    var priorities = [];

    //iterate over the <th>s, extracting their column priorities
    th.each(function (index) {
        var priority = th[index].getAttribute('data-priority');

        //TODO: this seems very messy, I feel there must be a cleaner way?
        if (priorities[priority] === undefined) {
            priorities[priority] = index;
        } else {
            priorities[priority] += ',' + index;
        }
    });

    //clean up the array so we have consecutive indices
    priorities = priorities.filter(function (x) {
        return x !== undefined && x !== null;
    });

    //initialise all of these outside of the loop
    var sCols = '';
    var aCols = [];
    var aSelectors = [];
    var sSelectors = '';
    var i;

    //while the table is wider than the window, and there's still columns to remove
    while ($('#table').width() > $(window).width() - 40 && priorities.length > 0) {
        //get the lowest priority
        sCols = (priorities.pop() + '');

        //split it, in case we have more than one column on the same priority
        //in this case we prefer to remove them as a group, rather than one at a time
        aCols = sCols.split(',');

        //clear the array from previous iteration
        aSelectors = [];
        for (i = 0; i < aCols.length; i++) {
            //build up the jQuery selectors
            aSelectors.push('td:nth-child(' + aCols[i] + '), th:nth-child(' + aCols[i] + ')');
        }

        //make jQuery selector string
        sSelectors = aSelectors.join(', ');

        //hide relevant columns
        $(sSelectors).css('display', 'none');
    }
}

var start = performance.now();;

initResponsiveTables();

alert(performance.now() - start);


texts: Text cleaning script, producing lowercase words with minimal punctuation

texts:
I created following script to clean text that I scraped. The clean text would ideally be lowercase words, without numbers and at maybe only commas and a dot at the end of a sentence. It should only have white-space between words and remove all "\n" elements from the text.

Particularly, I'm interested in feedback to the following code:

def cleaning(text):

    import string
    exclude = set(string.punctuation)

    import re
    # remove new line and digits with regular expression
    text = re.sub(r'\n', '', text)
    text = re.sub(r'\d', '', text)
    # remove patterns matching url format
    url_pattern = r'((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?'
    text = re.sub(url_pattern, ' ', text)
    # remove non-ascii characters
    text = ''.join(character for character in text if ord(character) < 128)
    # remove punctuations
    text = ''.join(character for character in text if character not in exclude)
    # standardize white space
    text = re.sub(r'\s+', ' ', text)
    # drop capitalization
    text = text.lower()
    #remove white space
    text = text.strip()

    return text

The script is cleaned via

cleaner = lambda x: cleaning(x)
df['text_clean'] = df['text'].apply(cleaner)
# Replace and remove empty rows
df['text_clean'] = df['text_clean'].replace('', np.nan)
df = df.dropna(how='any')

So far, the script does the job, which is great. However, how could the script above be improved, or be written cleaner?

Unclear seems the difference between

text = re.sub(r'\n', '', text)
text = re.sub('\n', '', text)

and whether

text = re.sub(r'\s+', ' ', text)
...
text = text.strip()

makes sense.


texts:
I got this question from the interviewbit site test.

There are n horses and you are the kth person in the line to ride on the horse. All the persons in the queue will go with the lowest numbered horse available i.e if horse no.1 and horse no.2 are present , the person will choose horse no.1 .All the horses have their own riding time and after their riding time ends they are free for next round. If there are no horses available the person will wait for the horse to come and will go on with it. We have to find that on which horse number we will be riding.

Input:- T - no. of test cases, n - no. of horses, k - your number in queue,ride time(M) - n numbers which will denote the riding time of the horses

constraints:- 1 <= T <= 100, 1 <= N <= 1000, 1 <= K <= 10^9, 1 <= M(i) <= 100000

output :- you have to tell the horse number which you will get.

Ex. 1

3 8

4 2 1

output:-
1

Here there are 3 horses with running time 4, 2, 1 and i am 8th in the queue.
so first three persons will go with horse#1 , horse#2 and horse#3. After this
there will be no horse so the fourth person will have to wait. horse#3 will
come first so he will go with it. fifth will go with horse#2 and sixth with
horse#3, seventh will go with horse#3 and eight will go with horse #1. so the
output is 1.
Below is my code :-

Its time complexity is O(N*K). Is there a better way to solve it.

#include<iostream>
using namespace std;

int main(){

    int t;
    cin>>t;
    while(t--){
        int n,k;
        cin>>n>>k;
        int hrs[n], ans;
        for(int i = 0;i < n;i++)
        cin>>hrs[i];

        if(n >= k){
            cout<<k<<endl;
        }else{
            int tt = 0,p = n;
            int B[n];
            for(int j = 0;j < n;j++)
            B[j] = hrs[j];

            while(p != k){
                tt++;
                for(int m = 0;m < n;m++){
                    if(tt == hrs[m]){
                        p++;
                        hrs[m] += B[m];
                        if(p == k){
                         ans = m;
                         break;
                        }
                    }
                }

            }
            cout<<ans+1<<endl;
        }

      }

    return 0;
}


texts: Catch-style unit testing in JavaScript (phase 1)

texts:
I decided to port my favorite unit testing framework, Catch, to JavaScript. So far I'm focusing on test cases and sections. I'll add assertions in phase 2, and output in phase 3.

The goal for this phase was to get all the assertions in the following test code to pass:

function assert(value, message) {
    console.log(value ? 'pass' : 'FAIL', message || '')
}

TEST_CASE('See if this works right', '[stuff]', function(){
    var x = 2, y = 4;

    console.log('============');
    SECTION('halving a good time', function(){
        x /= 2;
        y /= 2;
        assert(x == 1 && y == 2, 'halved values');
    });
    SECTION('double the fun', function(){
        x *= 2;
        y *= 2;
        assert(x == 4 && y == 8, 'doubled values');
        SECTION('up high', function(){
            x += 5;
            y += 5;
            assert(x == 9 && y == 13, 'high five');
        });
        SECTION('down low', function(){
            x -= 5;
            y -= 5;
            assert(x == -1 && y == 3, 'low five');
        });
    });
});

Notice that the entire test case should be run from the beginning, once for each "leaf" section, just like Catch (follow the second link in this question for a more complete explanation).

Here's what I've written so far. The documentation is very minimal right now; I'll be annotating and commenting properly later.

( /** @type function(Window) **/ function(global) {
    'use strict';

    var context = [],
        testCases = [],
        currentTestCase,
        nextTask;

    /** Section.
    */
    function Section(name, body, tags) {
        this.name = name;
        this.tags = tags;
        this.body = body;
        this.subsections = [];
        this.subsectionIndex = 0;
        this.subsectionsEncountered = 0;
    }

    /** Run section.
    */
    Section.prototype.run = function() {
        context.unshift(this);
        this.subsectionsEncountered = 0;
        this.body();
        context.shift();
    }

    /** Update subsection.
    */
    Section.prototype.updateSubsection = function(name, body) {
        var index = this.subsectionIndex,
            subsection = this.subsections[index];

        if (!subsection) {
            subsection = new Section(name, body);
            this.subsections[index] = subsection;
        } else {
            subsection.body = body;
        }

        return subsection;
    }

    /** Test case.
    */
    global['TEST_CASE'] = function(name, tags, body) {
        var next;

        currentTestCase = new Section(name, body, tags);
        testCases.push(currentTestCase);
        currentTestCase.run();
        while (nextTask) {
            next = nextTask;
            nextTask = null;
            next();
        }
    };

    /** Test case section.
    */
    global['SECTION'] = function(name, body) {
        var outer = context[0],
            oldNext = nextTask;

        if (outer.subsectionIndex == outer.subsectionsEncountered++) {
            nextTask = function() {
                if (++outer.subsectionIndex < outer.subsectionsEncountered) {
                    currentTestCase.run();
                } else if (oldNext) {
                    oldNext();
                }
            };
            outer.updateSubsection(name, body).run();
        }
    };

}(this));

I've kept the macro-style naming conventions from Catch, and dumped a bunch of things in the global scope. This may or may not change, but this is one thing I'm probably not interested in having reviewed, since it's easier for me to keep the names exactly the same while porting. The rest is fair game.

  Update: phase 2 is mostly complete.


texts:
I created this program some time ago. It shows you how to solve tower of hanoi for n disks, step by step.

Here's the code:

from os import system
from colorama import Fore, Style

clear = lambda: system('cls')

class TowerOfHanoi:
    def __init__(self, n, r1, r2, r3):
        self.n = n

        self.r1 = r1
        self.r2 = r2
        self.r3 = r3

        clear()
        print('Initial: ')
        self.parser(a, b, c)

        input('\nEnter To Continue...')

        self.solve()

    def parser(self, a1, b1, c1):
        x, y, z = [], [], []

        a1, b1, c1 = [0] * (self.n - len(a1)) + a1, \
                     [0] * (self.n - len(b1)) + b1, \
                     [0] * (self.n - len(c1)) + c1

        m = self.n

        for i in a1:
            s = ' ' * (m - i + 1)
            h = Fore.RED + s + '██' * i + s + Style.RESET_ALL

            x.append(h)

        for i in b1:
            s = ' ' * (m - i + 1)
            h = Fore.RED + s + '██' * i + s + Style.RESET_ALL

            y.append(h)

        for i in c1:
            s = ' ' * (m - i + 1)
            h = Fore.RED + s + '██' * i + s + Style.RESET_ALL

            z.append(h)

        print(' ' * self.n + str(self.r1)
              + ' ' * (self.n * 2 + 1) + str(self.r2)
              + ' ' * (self.n * 2 + 1) + str(self.r3))

        print()

        print('\n'.join(i + ' ' * (self.n - len(i))
                + j + ' ' * (self.n - len(j))
                + k for i, j, k in zip(x, y, z)))
        print()

    def solve(self, n = None, r1 = None, r2 = None, r3 = None, x = 0, y = 1, z = 2):
        if n is None:
            n = self.n

        if r1 is None:
            r1 = self.r1
        if r2 is None:
            r2 = self.r2
        if r3 is None:
            r3 = self.r3

        if n == 1:
            clear()
            print("Move disk 1 from rod", r1, "to rod", r2)
            print()
            [a, b, c][y].insert\
                (0, [a, b, c][x].pop(0))
            self.parser(a, b, c)
            return

        self.solve(n - 1, r1, r3, r2, x, z, y)
        input('\nEnter To Continue...')

        clear()

        print("Move disk", n, "From Rod", r1, "To Rod", r2)
        print()

        [a, b, c][y].insert\
            (0, [a, b, c][x].pop(0))

        self.parser(a, b, c)

        input('\nEnter To Continue...')
        print()
        self.solve(n - 1, r3, r2, r1, z, y, x)

print('Welcome to Tower of Hanoi!')
print('You have some number of rings of increasing length')
print('Like this:')
print()
print(Fore.RED + '  ██  ' + Style.RESET_ALL)
print(Fore.RED + ' ████ ' + Style.RESET_ALL)
print(Fore.RED + '██████' + Style.RESET_ALL)
print()
print('The rules are simple: ')
print('  * You can move a disk from a rod to another rod')
print('      if the current disk is smaller than the topmost disk in the rod you are moving')
print()
print('  * The goal is to move all disks from rod 1 to rod 2')
print()
print('This program shows you how to move the disks from rod 1 to rod 2')
print()

while True:
    input('Press enter to start!')
    print()

    n1 = int(input('Enter number of rings: '))

    a = [i for i in range(1, n1 + 1)]
    b = []
    c = []

    toh = TowerOfHanoi(n1, 1, 2, 3)

    print()
    play_again = input('Do you want to play again? <Y>es or <N>o').lower()

    while play_again != 'y' or play_again != 'n':
        play_again = input('Do you want to play again? <Y>es or <N>o').lower()

    if play_again == 'n':
        print('Bye!')
        break

This code seems a bit lengthy, as well as ugly. How do I improve it?

Any tips are welcome!


texts: Make palindrome finder-builder function faster

texts:
I built a small JavaScript function to see if a series of characters are a palindrome or not. The functions works well and does everything it has to do, but I'm wondering if something can be tweaked to make it faster.

This is the actual code:

var words = ['anita lava la tina',' a ', 'civvic', 'ddaa', 'aa', 'dca', '332', null,     'toyota','racecar'];
function getPalindrome(word){
    if(!word || (word = word.replace(/ /g,'')).length<2)
        return "-1";

    var charsCount = {};
    word = word.toLowerCase();
    var chars = word.split("");

    //ahorra un poco de tiempo cuando las palabras son grandes
    if(chars.reverse().join('')===word)
        return word;

    for(var i=0;i<chars.length;i++){
        if(charsCount[chars[i]])
            charsCount[chars[i]] += 1;
        else
            charsCount[chars[i]] = 1;
    }

    //si hay mas de un impar, ya no puede ser palindromo
    var oddCounter = 0;
    var palindromo = [];
    var oddChar = '';
    for(var letter in charsCount){
        if(charsCount[letter] % 2 !== 0)
            oddCounter++;

        if(oddCounter>1)
            return "-1";

        var times = charsCount[letter];
        if(times===1){
            oddChar = letter;
        }
        else{
            for(var i=0;i<times;i++){
                if(i%2==0)
                    palindromo.push(letter);
                else
                    palindromo.unshift(letter);
            }
        }
    }
    //agrego el impar a la mitad, si es que hay
    palindromo.splice(palindromo.length/2,0,oddChar);

    return palindromo.join('');
}

for(var i in words){
    console.log(words[i],":",getPalindrome(words[i]));
}

What I do here is this:

If word is null or the length of word after eliminating spaces is lower than 2, then it's not a palindrome, so return -1.
If the reverse of word equals word, then it is a palindrome, so return the word.
Make a map with all the chars, adding the occurrence of each char.
Loop the map of the chars: if the count of more than one char is an odd number, then it's not a palindrome, so return -1.
Simply put one char at the beginning of an array and one at the end and loop n times if the char was found.
Store the odd char in a variable for later use.
When loop (4) ends, insert the odd char in the middle of the array.
Return the built palindrome.

The function works, but how can I make it faster?


texts:
I had to write a program to calculate the Lagrange polynomial of the maddening degree of function: \$\log(x+1)+\cos(x-1)\$

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

#define GRADE 6

/* Funzione per costruire la successione dei nodi (xi,yi) dei punti di valutazione*/
void nodeSuccession(double* xNode, double* yNode, double* xVal){
    int i;

    printf("xNode [");
    for(i = 0; i < GRADE + 1; i++){
        xNode[i] = i; /* Array contenete le ascisse dei nodi */
        printf("%.4f, ", xNode[i]);
        yNode[i] = 0; /* Array contenete le ordinate dei nodi */
    }
    printf("\b\b]\n");

    printf("yNode [");
    for(i = 0; i < GRADE + 1; i++){
        yNode[i] = (log(xNode[i] + 1)) + cos(xNode[i] - 1);
        printf("%.4f, ", yNode[i]);
    }
    printf("\b\b]\n");

    printf("xVal  [");
    for(i = 0; i < GRADE; i++){
        xVal[i] = (xNode[i] + xNode[i+1]) / 2;
        printf("%.4f, ", xVal[i]);
    }
    printf("\b\b]\n");

}
/* Funzione per costruire il polinomio di lagrange e lo valuto nei punti */
double* polynomial(double *xVal, double *xNode, double *yNode){
    int i, j, k;
    double pr, *sum = malloc(GRADE * sizeof(double));

    for(j = 0; j < GRADE; j++){
        sum[j] = 0;
        for(k = 0; k < GRADE + 1; k++){
            pr = 1;
            for(i = 0; i < GRADE + 1; i++){
                if(k != i)
                    pr = pr * ((xVal[j] - xNode[i])/(xNode[k] - xNode[i]));
            }
            sum[j] = sum[j] + yNode[k] * pr;
        }
    }

    return sum;
}

/* Funzione per la valutazione dell'errore di interpolazione */
double* error(double *xVal, double *sum){

    int i;
    double *err = malloc(GRADE * sizeof(double));

    for(i = 0; i < GRADE; i++)
        err[i] = fabs(((log(xVal[i] + 1)) + cos(xVal[i] - 1)) - sum[i]);

    return err;
}

int main(void){
    int i;
    double xNode[GRADE + 1], xVal[GRADE], yNode[GRADE + 1];
    double *poly = malloc(GRADE * sizeof(double)), *err = malloc(GRADE * sizeof(double));

    system("clear");
    printf("\n===== PROGRAMMA PER IL CALCOLO DEL POLINOMIO DI LAGRANGE =====\n\n");

    nodeSuccession(xNode, yNode, xVal);
    poly = polynomial(xVal, xNode, yNode);

    printf("\npoly  [");
    for(i = 0; i < GRADE; i++)
        printf("%.4f, ", poly[i]);
    printf("\b\b]\n");

    err = error(xVal, poly);
    printf("err   [");
    for(i = 0; i < GRADE; i++)
        printf("%.4f, ", err[i]);
    printf("\b\b]\n");

    free(poly);
    free(err);

    return 0;
}


texts:
I was trying to do a very common interview problem "Finding the max repeated word in a string " and could not find much resources in net for c/c++ implementation. So I coded it myself here. I have tried to do most of the coding from scratch for better understanding. Could you review my code and provide comments on my algorithm. Some people have suggested using hashtables for storing the count, but am not using hashtables here.

#include<stdafx.h>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<iostream>

using namespace std;
string word[10];

//splitting string into words
int parsestr(string str)
{
    int index = 0;
    int i = 0;
    int maxlength = str.length();
    int wordcnt = 0;
    while(i < maxlength)
    {
        if(str[i] != ' ')
        {
            word[index] = word[index] + str[i];
        }
        else
        {
            index++; //new word
            wordcnt = index;
        }
        i++;
    }
    return wordcnt;
}

//find the max word count out of the array and return the word corresponding to that index.
string maxrepeatedWord(int wordcntArr[],int count)
{
    int max = 0;
    int index = 0;
    for(int i = 0; i <= count; i++)
    {
        if(wordcntArr[i] > max)
        {
            max = wordcntArr[i];
            index = i;
        }
    }

    return word[index];
}

void countwords(int count)
{
    int wordcnt = 0;
    int wordcntArr[10];
    string maxrepeatedword;
    for(int i = 0; i <= count; i++)
    {
        for(int j = 0; j <= count; j++)
        {
            if(word[i] == word[j])
            {
                wordcnt++;
                //word[j] = "";
            }
            else
            {}
        }
        cout << " word " << word[i] << " occurs " << wordcnt << " times " << endl;
        wordcntArr[i] = wordcnt;
        wordcnt = 0;
    }

    maxrepeatedword = maxrepeatedWord(wordcntArr,count);
    cout << " Max Repeated Word is " << maxrepeatedword;
}

int main()
{
    string str = "I am am am good good";
    int wordcount = 0;
    wordcount = parsestr(str);
    countwords(wordcount);
}


texts:
Mostly due to readability, I am using the following code to

find a specific csv file on a drive
read that CSV file using a streamReader
parse it into a List<string[]> to be able to use LINQ and/or PLINQ later on

However, the process takes about 4-5 seconds, which is simply put too long. Any suggestions on how to improve the following (or maybe even replace it)?

var query = (from x in Directory.GetFiles(_path, "*.csv").AsParallel()
                     where x.Contains(dateTime)
                     select x).First();

        #region Read CSV File
        List<string[]> _tempList = new List<string[]>();

        FileStream stream = new FileStream(query, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        using (StreamReader reader = new StreamReader(stream, Encoding.Default, true, 1024))
        {
            string currentLine;
            while ((currentLine = reader.ReadLine()) != null)
            {
                string[] temp = currentLine.Split(new char[] { ',' }, StringSplitOptions.None);
                _tempList.Add(temp);
            }
        }
        #endregion

The order inside the CSV file is important - the file will contain between (2000-7000) x 25 entries.

The CSV file has several fields which I am not interested in - and I don't necessarily need them in my List<string[]> (or string[][]).  I have tried to filter them with a LINQ statement similar to the following pseudo code:

var query = from x in MyListOfStringArray
            select new {Col1 = x[1] , Col2 = c[4]}.ToArray();

This approach results in a strange type for query - and for that matter was pretty slow (I would have an array with about 9-11 properties).  Any ideas on that second issue?


texts: Finding the closest value and matching it with the correct item in the list

texts:
I have list values with their IDs like this:

ID   Value
A    1.2
B    4.2
C    7.2
D    10.2

In C#, I want to find the ID with the closest value to a given value say 3.9. In this example, B will be the answer as it has the value(4.2) closest to the given value.

My solution to this problem involved following steps:

Put the values in an list of objects (where each object has a property ID and a value) or a dictionary with string ID and decimal value
Loop through the list or dictionary and find the minimum value
If the value is found or their difference is minimum, print the item ID (in this case B)

I want to know if there is better solution in terms of time complexity as here it seems to be \$O(n)\$.

public class SampleClass {
        public string ID { get; set; }
        public double Value { get; set; }
        public SampleClass(string _id, double _value){
        this.ID = _id;
        this.Value = _value;
        }
        public static void Main(string[] args){
            SampleClass input1 = new SampleClass("A",1.20);
            SampleClass input2 = new SampleClass("B", 4.20);
            SampleClass input3 = new SampleClass("C", 7.20);
            SampleClass input4 = new SampleClass("D", 10.20);
            double givenValue = 9.9;
            List<SampleClass> sampleClassList = new List<SampleClass>();
            sampleClassList.Add(input1);
            sampleClassList.Add(input2);
            sampleClassList.Add(input3);
            sampleClassList.Add(input4);
            double cVal = double.MaxValue;
            string cID = string.Empty;
            double diff = 0;
            foreach (SampleClass item in sampleClassList){
              if (item.Value == givenValue){
                  Console.WriteLine(item.ID);
                  return;
              }
             diff = Math.Abs(item.Value - givenValue);
             if (diff < cVal) {
                 cVal = diff;
                 cID = item.ID;
             }
           }
            Console.WriteLine(cID);
        }
    }

I am aware if there are list of values which is sorted, then you can find the closest value through binary search on this sorted list and it will give you a more efficient time complexity.

But in my case, after finding the closest value, I have to match this value to its ID. Also, these values can be duplicate, so I cannot use them as key in dictionary.

Is there more efficient way of doing this, or am I missing something?


texts:
I'm using this nice C++ wrapper to work with SQLite3 in my project. I wanted to handle errors gracefully and automatically rollback if piece of code fails, so wrote this simple helper class:

class SqlTransaction { // RAII class to rollback on error
    public:
        SqlTransaction(std::shared_ptr<sqlite::database> db_): db(db_) { *db << "begin;"; };
        ~SqlTransaction() { if (!finished) rollback(); };
        void commit() { if (!finished) { *db << "commit;"; finished = true; } };
        void rollback() { if (!finished) { *db << "rollback;"; finished = true; } };

        // Disable both copying and moving
        SqlTransaction(const SqlTransaction&) = delete;
        SqlTransaction& operator=(const SqlTransaction&) = delete;
        SqlTransaction(SqlTransaction&&) = delete;

    private:
        std::shared_ptr<sqlite::database> db;
        bool finished = false;
    };

It's to be used like this:

SqlTransaction trans(db);
// work with db here, may throw if something goes wrong
trans.commit();


texts:
I wrote a smooth function that returns a list of all smooth numbers below a certain limit from a list of prime:

repeatMul init limit = takeWhile (<=limit) . scanl (*) init . repeat

smooth limit = (`inner` 1)
    where inner [] init = [init]
          inner (x:xs) init = repeatMul init limit x >>= inner xs

For instance:

main = print . sort . smooth 20 $ [2, 3, 5]
-- [1,2,3,4,5,6,8,9,10,12,15,16,18,20]

It works fine, but I wonder if the inner function could be written in a different way. I've been trying to find a high order function to achieve the same purpose, but I can't wrap my head around it.

Also I'm new to haskell, so any general comment is welcome.

Extra question: I have another version of smooth that returns a set instead of a list:

import Data.Set (singleton, unions)

repeatMul limit x = takeWhile (<=limit) . iterate (*x)

smooth limit xs = foldr f singleton xs $ 1
    where f x c = unions . map c . repeatMul limit x

Is it possible to simplify this as well even though the Set type does not instantiate the Monad type class?


texts:
I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.

One thing is sure is to divide the code up in several files maybe but outside of that.

The code:

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

#define ROWS 3
#define BOARD_SIZE ROWS * ROWS

typedef enum { false, true } bool;

bool enter_entry(char *board, char character, int x, int y);
void print_board(const char *board);
void *init_board();
bool is_solved(char *board, char item);
bool is_draw(char *board);
bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
void player_selection(char *board, char item);
void game_loop(char *board);

int main()
{
    char *board = init_board();
    game_loop(board);
    return 0;
}

void *init_board()
{
    char *board = malloc(sizeof(char) * BOARD_SIZE);
    for(int i = 0; i < BOARD_SIZE; i++)
    {
        board[i] = ' ';
    }
    return board;
}

void print_board(const char *board)
{
    for(int i = 1; i < BOARD_SIZE+1; i++)
    {
        printf("| %c ", board[i-1]);
        if(i % 3 == 0)
        {
            printf("|\n");
        }
    }
    printf("\n");
}

bool is_solved(char *board, char item)
{
    if(is_equal(board, 0, 1, 2, item)) { return true; }
    if(is_equal(board, 3, 4, 5, item)) { return true; }
    if(is_equal(board, 6, 7, 8, item)) { return true; }

    if(is_equal(board, 0, 3, 6, item)) { return true; }
    if(is_equal(board, 1, 4, 7, item)) { return true; }
    if(is_equal(board, 2, 5, 8, item)) { return true; }

    if(is_equal(board, 0, 4, 8, item)) { return true; }
    if(is_equal(board, 2, 4, 6, item)) { return true; }
    return false;
}

bool is_draw(char *board)
{
    for(int i = 0; i < BOARD_SIZE; i++)
    {
        if(board[i] == ' ')
        {
            return false;
        }
    }
    return true;
}

bool is_equal(char *board, int indexA, int indexB, int indexC, char item)
{
    if(board[indexA] == item && board[indexB] == item && board[indexC] == item)
    {
        return true;
    }
    return false;
}

bool enter_entry(char *board, char character, int x, int y)
{
    int index = x + ROWS * y;

    if(board[index] != ' ')
    {
        return false;
    }

    board[index] = character;
    return true;
}

void player_selection(char *board, char item)
{
    int x, y;
    printf("enter coords (x, y): \n");

    while(1)
    {
        scanf(" %d %d", &x, &y);
        bool succes = enter_entry(board, item, x-1, y-1);
        if(succes)
        {
            break;
        }
        printf("This coord is already used or not valid enter new ones:\n");
    }
    print_board(board);
}

void game_loop(char *board)
{
    char playerOneChar = 'o';
    char playerTwoChar = 'x';

    printf("Welcome to tic tac toe!\n");
    printf("Press enter to continue\n");
    char enter = 0;
    while (enter != '\r' && enter != '\n') { enter = getchar(); }

    printf("Let's start the game!\n");
    print_board(board);

    while(1)
    {
        printf("Player one: \n");
        player_selection(board, playerOneChar);
        if(is_solved(board, playerOneChar))
        {
            printf("Player one won!\n");
            break;
        }

        if(is_draw(board))
        {
            printf("No winners!\n");
            break;
        }

        printf("Player two: \n");
        player_selection(board, playerTwoChar);
        if(is_solved(board, playerTwoChar))
        {
            printf("Player two won!");
            break;
        }
        if(is_draw(board))
        {
            printf("No winners!\n");
            break;
        }
    }
}

Thank you in advance!


texts: Find target in sorted array pivoted at some unknown point in O(log n)

texts:
You are given an array sorted in ascending order which is rotated at
  some pivot unknown to you beforehand. Find your target in \$O(log n)\$
  which means it should be a binary search. If the value does not exist
  return -1.

The approach I took was to narrow the subset of solutions by using an upper bound infinity and a lower bound infinity. I would cut the array in half. If the mid was less than the target, the right of the mid would become the new lower bound and if the high was less than the current target the mid would be the new upper bound.

function findTarget(array, target) {
  let lo = 0,
    hi = array.length,
    limit;
  while (lo < hi) {
  let mid=Math.floor((hi+lo)/2);
    if ((array[mid] < array[0]) === (target < array[0])) {
      limit = array[mid]
    } else if (target < array[0]) {
      limit = Number.NEGATIVE_INFINITY
    } else {
      limit = Number.POSITIVE_INFINITY
    }
    if (limit < target) {
      lo = mid + 1
    } else if (limit > target) {
      hi = mid
    } else {
      return mid
    }
  }
  return -1
}

console.log(findTarget([4, 5, 6, 7, 0, 1, 2], 3))


texts: Determine if a string only contains repetitions of a substring

texts:
This is my first Python program in years, it's just a simple string manipulation program. Given a string, determine if it contains repetitions of any substring. For example, testtest contains two substring test and nothing else.

def onlySubstrings(stringOrig):
    stringCopy = (stringOrig+'.')[:-1] # copy string contents
    for i in range(1, len(stringCopy)): # for each character
        stringCopy = stringCopy[1:]+stringCopy[0] # shift first char to end
        if stringCopy == stringOrig: # if equivalent to original input
            return True # it consists of substrings only
    else: # otherwise the only substring is the string itself
        return False

if __name__ == '__main__':
    wordList = ['testtest','testteste','test','tetestst'] # some test words
    print('The below words only contain substring repetitions:')
    for word in wordList: # for each word
print(onlySubstrings(word), '\t', word)

If you imagine the string as circular unto itself, the string can only contain equal substring(s) if you can move the characters to the left or right and get the same original string in less than len shifts:

testtest - 0 shifts, original string
esttestt - 1 shift, not original
sttestte - 2 shifts, not original
ttesttes - 3 shifts, not original
testtest - 4 shifts, original again

Since 4 < len, it contains only substring repetitions.

testteste - 0 shifts, original string
esttestet - 1 shift, not original
...
etesttest - (len-1) shifts, not original
testteste - len shifts, original again

Since we couldn't find the original string again in under len shifts, it does not only contain repetitions of a substring.


texts: Passing an entity to use it's fields to update method is ok to do?

texts:
I have two different ideas on how to handle this Update method in my MVC Model class "DataAccess" And I'm wondering if in the first, I'm handling my class incorrectly or ambiguously, because I'm using members from the same object for two different purposes.

The man Class has 2 relevant members.  ID, which is the primary key of the entity, and Name, which is the description

    public DbResult Update(Man man)
    {
        DbResult dbResult;

        var query =
            from person in _MyDBEntities.Men
            where person.ManID == man.ManID // Man with ManID is what we're looking for.
            select person;

        try
        {
            foreach (Man m in myQuery)
            {
                m.Name = man.Name; // man.Name is the new name
            }
            dbResult = DbResult.Success("Record updated");
        }
        catch (Exception e)
        {
            dbResult = DbResult.Failed(e.ToString());
        }
        return dbResult;
    }

And this version of the method, which uses the variables passed in differently.

    public DbResult Update(int idToLookFor, string newName)
    {
        DbResult myResult;

        var query =
            from person in _MyDBEntities.Men
            where person.ManID == idToLookFor
            select person;

        try
        {
            foreach (Man m in myQuery)
            {
                m.Name = newName;
            }
            dbResult = DbResult.Success("Record updated");
        }
        catch (Exception e)
        {
            dbResult = DbResult.Failed(e.ToString());
        }
        return dbResult;
    }

is my first method a better or ok approach to the problem?  Because what if I have an update method later on that uses 8 members, and need to create more versions of this function for updating other entities?

## UPDATED ##

Including a new class here:

public class InputValidation//<T> where T: class
{
    /// <summary>
    /// Delegate that matches the signature of TryParse, method defined for all primitives.
    /// </summary>
    /// <typeparam name="T">Output type of This Delegate</typeparam>
    /// <param name="input">input for this Delegate to translate to type T</param>
    /// <param name="output">The translated variable to return via out parameter</param>
    /// <returns>Whether the Parse was successful or not, and output as output</returns>
    public delegate bool TryParse<T>(string input, out T output);
    public bool ValidateInputType<T>(string input, TryParse<T> TypeValidator, out T result)
    {
        return TypeValidator(input, out result);
    }
    public bool ValidateInputRange<T>(ref T result, int lower, int upper)
    {
        // How can I use relational operators like > < = on T? without forcing T result to an int?
        return isValidRange(int.Parse(result.ToString()), lower, upper);
    }
    public bool isValidRange(int item, int lower, int upper)
    {
        return (lower <= item && item <= upper);
    }
}


texts: Laravel Pagination with haversine formula in it

texts:
I'm using the haversine formula to count distance from selected post-code to desired destination.

I have the following scope in App\Models\Business.php:

public function scopeDistance($query, $latitude, $longitude, $radius)
{
    $query->getQuery()->orders = [];
    return $query->select('*')
                 ->selectRaw("( 3959 * acos( cos( radians($latitude) ) * cos( radians( latitude ) )  * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin(radians(latitude)) ) ) AS distance")
                 ->having('distance', '<=', $radius)
                 ->orderBy('distance');
}

Everything seems pretty ok, except the case when I use the paginate() method instead of get() in builder.

There are solutions out there, but I couldn't get these to work or were too complicated. I came up with this solution and I would like to hear feedback in terms of performance or memory usage.

This is the query at the end:

"select count(*) as count from (select ( 3959 * acos( cos( radians(51.5872718) ) * cos( radians( latitude ) )  * cos( radians( longitude ) - radians(-0.549759) ) + sin( radians(51.5872718) ) * sin(radians(latitude)) ) ) AS distance from `businesses` having `distance` <= ?) as harversine"

and custom_pagination function:

function custom_paginator($builder, $per_page)
{
    $path = current_route();
    $current_page = \Illuminate\Pagination\Paginator::resolveCurrentPage();

    if ( ! isset($builder->getQuery()->columns[1])) $count = $builder->count();
    else
    {
        $query = clone $builder->getQuery();
        $query->columns = [ $query->columns[1] ];
        $query->orders = null;
        $count = array_get(\DB::select("select count(*) as count from ({$query->toSql()}) as haversine", $query->getBindings()), 0)->count;
    }

    return new \Illuminate\Pagination\LengthAwarePaginator(
        $builder->forPage($current_page, $per_page)->get(),
        $count, $per_page, null, compact('path')
    );
}

Is there anything I should change or improve?


texts:
I'm learning algorithm and this is my implementation of quick sort, please guide how can i improve it further and what are other more optimal ways to implement quick sort?

def quick_sort(arr):
    length = len(arr)
    if length <= 1:
        return arr

    else:
        pivot = arr.pop()

    items_greater = []
    items_lower = []

    for item in arr:
        if item > pivot:
            items_greater.append(item)
        else:
            items_lower.append(item)

    return quick_sort(items_lower)+[pivot]+quick_sort(items_greater)


texts: Removing random repeated guesses from brute force program

texts:
I came here to ask if there is a way to prevent already guessed guesses from being guessed again in my brute-force Java program. Basically I used a rand.nextInt in my program but the program will guess already guessed passwords again even if they were incorrect. How could I prevent this as it wastes time and processing power to guess already guessed numbers?

import java.util.*;
import java.io.*;
class pwcracker
{
public static void main (String[] args)
{
    Scanner scan = new Scanner( System.in );
    Random rand = new Random();

  String pw, choices, guess;
    long tries;
    int j, length;

    System.out.println("Enter a password that is up to 5 chars and contains no numbers: ");
    pw = "" + scan.nextLine();
    length = pw.length();

    choices = "abcdefghijklmnopqrstuvwxyz";
    tries = 0;
    guess = "";

    System.out.println("Your pw is: " + pw);
    System.out.println("The length of your pw is: " + length);

  System.out.println("for TEST- Guess: " + guess + "pw :"+pw);

  if (!guess.equals(pw)){

  while  (!guess.equals(pw))
    {
        j = 0;
        guess = "";

        while ( j < length )
        {
            guess = guess + choices.charAt( rand.nextInt( choices.length() ) );
        j = j + 1;

        if (guess .equals(pw))
     {
       System.out.println("Match found, ending loop..");
       break;
     }

        }
                System.out.println("Guess: " + guess + " pw :"+pw);
        tries = tries + 1;
    }
  }
    System.out.println("Here is your password: " + guess);
    System.out.println("It took " + tries + " tries to guess it.");
   }
}


texts:
So I made this calculator in c# console, I'm pretty nooby-ish in programming. I want to know if I can make it better, because my coding skills suck. Pretty sure my logic sucks too.

Any advice and tips?

   public static void Main() {
        bool returnToStart;

        do {
            returnToStart = Calc();

        } while(returnToStart == true);

        Console.ReadLine();

    }
    public static bool Calc() {
        ExitProgram();
        Console.Clear();

        float firstNumber; float secondNumber; float result;
        string operation;

        Console.Write("First number: ");
        firstNumber = float.Parse(Console.ReadLine());

        Console.Write("Choose your operator: addition(+), subtraction(-), " +
                     "multiplication(*) or division(/): ");
        operation = Console.ReadLine();

        Console.Write("Second number: ");
        secondNumber = float.Parse(Console.ReadLine());

        Console.Clear();

        switch(operation) {
            case "+":
                result = (firstNumber + secondNumber);
                Console.WriteLine("Calculation: {0}", result);
                break;
            case "-":
                result = (firstNumber - secondNumber);
                Console.WriteLine("Calculation: {0}", result);
                break;
            case "*":
                result = (firstNumber * secondNumber);
                Console.WriteLine("Calculation: {0}", result);
                break;
            case "/":
                if(firstNumber == 0) {
                    Console.WriteLine("Cant divide by zero!");
                } else {
                    result = (firstNumber / secondNumber);
                    Console.WriteLine(result);
                }
                break;

            default:
                Console.WriteLine("Error! Try again.");
                break;

        }
        return true;

    }
    public static bool ExitProgram() {
        string exit = "Exit";

        Console.WriteLine("If you're done with your calculations,\nthen you can exit this program by simply typing in 'Exit' ");
        Console.Write("Want to quit the program?: ");
        exit = Console.ReadLine();

        if(exit == "Exit") {
           Environment.Exit(0);

        }return true;

    }

}

}


texts: Find all subsets of an int array whose sums equal a given target

texts:
I am trying to implement a function below:

  Given a target sum, populate all subsets, whose sum is equal to the target sum, from an int array.

For example:

Target sum is 15.

An int array is { 1, 3, 4, 5, 6, 15 }.

Then all satisfied subsets whose sum is 15 are as follows:

15 = 1+3+5+6
15 = 4+5+6
15 = 15

I am using java.util.Stack class to implement this function, along with recursion.

GetAllSubsetByStack class

import java.util.Stack;

public class GetAllSubsetByStack {

    /** Set a value for target sum */
    public static final int TARGET_SUM = 15;

    private Stack<Integer> stack = new Stack<Integer>();

    /** Store the sum of current elements stored in stack */
    private int sumInStack = 0;

    public void populateSubset(int[] data, int fromIndex, int endIndex) {

        /*
        * Check if sum of elements stored in Stack is equal to the expected
        * target sum.
        *
        * If so, call print method to print the candidate satisfied result.
        */
        if (sumInStack == TARGET_SUM) {
            print(stack);
        }

        for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {

            if (sumInStack + data[currentIndex] <= TARGET_SUM) {
                stack.push(data[currentIndex]);
                sumInStack += data[currentIndex];

                /*
                * Make the currentIndex +1, and then use recursion to proceed
                * further.
                */
                populateSubset(data, currentIndex + 1, endIndex);
                sumInStack -= (Integer) stack.pop();
            }
        }
    }

    /**
    * Print satisfied result. i.e. 15 = 4+6+5
    */

    private void print(Stack<Integer> stack) {
        StringBuilder sb = new StringBuilder();
        sb.append(TARGET_SUM).append(" = ");
        for (Integer i : stack) {
            sb.append(i).append("+");
        }
        System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
    }
}

Main class

public class Main {

    private static final int[] DATA = { 1, 3, 4, 5, 6, 2, 7, 8, 9, 10, 11, 13,
        14, 15 };

    public static void main(String[] args) {
        GetAllSubsetByStack get = new GetAllSubsetByStack();
        get.populateSubset(DATA, 0, DATA.length);
    }
}

Output in Console is as follows:

15 = 1+3+4+5+2
15 = 1+3+4+7
15 = 1+3+5+6
15 = 1+3+2+9
15 = 1+3+11
15 = 1+4+2+8
15 = 1+4+10
15 = 1+5+2+7
15 = 1+5+9
15 = 1+6+8
15 = 1+14
15 = 3+4+6+2
15 = 3+4+8
15 = 3+5+7
15 = 3+2+10
15 = 4+5+6
15 = 4+2+9
15 = 4+11
15 = 5+2+8
15 = 5+10
15 = 6+2+7
15 = 6+9
15 = 2+13
15 = 7+8
15 = 15

Please help me with the following 2 things:

How can I improve this code to reduce the times for recursion? Is sorting the int array (from high to low) before recursion a better way?
Is there a way to improve the code without using recursion?


texts: Searching all object property values inside Array.prototype.filter callback

texts:
Based on input from the UI (most likely a string) I would like to search a list of object and return all object that has one or more matching property values which match the given input.

Do you have any thoughts regarding performance or overall design?

The only requirement is that I need to keep the outer Array.prototype.filter. My question is how/if I should modify anything inside its callback.

var items = [{ x: 1, y: 2 }, { x:1, y: 3, z: 'blah' }];

function findObjectByPropertyValue(value, ignoreCase){

    var result = items.filter(function(item){

       var keys = Object.keys(item);
       for(var i = 0, len = keys.length; i < len; i++){

           var match,
               propertyValue = item[keys[i]];

           if(ignoreCase && typeof propertyValue === 'string' && typeof value === 'string')
               match = propertyValue.toLowerCase() === value.toLowerCase();
           else
               match = propertyValue === value;

           if(match)
               return true;
        }
    });

    return result;
}

console.assert(findObjectByPropertyValue(1).length === 2);
console.assert(findObjectByPropertyValue(2).length === 1);
console.assert(findObjectByPropertyValue(4).length === 0);
console.assert(findObjectByPropertyValue('blah').length === 1);
console.assert(findObjectByPropertyValue('Blah', true).length === 1);
console.assert(findObjectByPropertyValue('Blah').length === 0);

http://jsfiddle.net/Lg6rwnwh/1/


texts: Prime number checker in Python 3 - follow-up

texts:
I have updated my code from the last time it got reviewed. If anyone has some more suggestions on how I can improve this and/or make it faster it would be appreciated!

def is_prime(num):
    '''Calculates whether num is a prime number,
    if it is return True otherwise return False'''

    # SPECIALCASE: These are special cases that are not primes
    if num % 2 == 0 and num != 2 or num <= 1:
        return False

    # Look for a factor
    for i in range(3, int(num ** (0.5)) + 1, 2):
        # If there is a factor
        if num % i == 0:
            # Its not a prime number
            return False

    # If there is no factors and its not a special case
    return True


texts: Amending code to make it list some files in a directory, rather than all

texts:
The method list_all() is the code I am starting with. It just lists all files in "c:\windows".

I want to adjust it to list only the first 10 files (if there are as many files as that there).

I can see that Directory.GetFiles(sDir) returns an array of string.  The original method list_all(), takes all of them.  I want mine to just take the first 10, or if there's less than 10 then all of them.  But i've added four lines of code and used a list, to do it. My amended method is list_some()

It's far from a disaster, but I'm sure there's a better way though I'm not sure.

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            static void list_all()
            {
                string sDir = "c:\\windows";

                foreach (string f in Directory.GetFiles(sDir))
                {
                     Console.WriteLine(f);
                }

            }

            static void list_some()
            {
                string sDir="c:\\windows";

                List<string> lstsomefiles = new List<string>();
                int count = Directory.GetFiles(sDir).Length;
                string[] strs_fileslst = Directory.GetFiles(sDir);

                for (int i = 0; i < count && i < 10; i++) lstsomefiles.Add(strs_fileslst[i]);

                foreach (string f in lstsomefiles)
                {

                    Console.WriteLine(f);
                }

            }

        }
    }
}


texts: Extracting the first two components of a version number

texts:
What's the most pythonic way to extract a substring by delimiter position?

i.e. something like slicing a string, but where the index is based on the delimiter position, rather than the character position in the string.

I have a version string "1.2.3.dev0" and I want to extract the first two components "1.2".

Currently I'm using:

>>> delimiter = "."
>>> version = "1.2.3.dev0"
>>> short_version = delimiter.join((version.split(delimiter)[0:2]))
>>> print(short_version)
1.2

Is this the simplest way to achieve this?


texts: Function to scan input to string buffer in C

texts:
I have written a function that reads standard input, ignores initial whitespace and fills the buffer with that data.
I think that it is a bit large and cumbersome, can you please tell me what can be improved?

int dscan(char *where, int size) {
    int found = 0;
    int i = 0;
    int j = 0;
    for (i = 0; i < size - 1; i++) {
        char c;
        scanf("%c", &c);
        if (c == '\n') {
            where[j] = '\n';
            where[j + 1] = '\0';
            return j;
        }
        if (isspace(c)) {
            if (!found) {
                continue;
            }
        } else {
            found = 1;
        }
        where[j] = c;
        j++;
    }
    return j;
}