texts: router system like laravel, how to manage routes creation and router handler?

texts:
i'm trying to create a url router system, for educational purposes, that has a similar usage like Laravel has, but i'm curious about how i can register the routes like laravel does (with single calls to static methods), here's my "conceptual" code that i made using a TDD approach:

        $Route = new Route;
        $Route
        ->setUri('users/[i:id]')
        ->setMethod('GET')
        ->setCallback(function () {
            return 'get user';
        })
        ->setMiddleware([
            App\Http\Middlewares\Auth::class,
            App\Http\Middlewares\Permission::class
        ])
        ->setName('users.show');

        $Route2 = new Route;
        $Route2
        ->setUri('orders')
        ->setMethod('POST')
        ->setCallback('OrdersController@create')
        ->setMiddleware([
            App\Http\Middlewares\Auth::class
        ])
        ->setName('orders.post');

        $Router = new Router;
        $Router->addRoute($Route);
        $Router->addRoute($Route2);
        // if the route is matched this methods are called
        // $Router->handleMiddlewares();
        // $Router->handleCallback();
        $Router->run();

1 - there's a better approach about how to encapsulate the route object creation to a simple/shorter way?
eg:
in Laravel we can map routes like this:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback)->name('foo');

2 - should the router class be responsible for filtering routes (regex rules etc), handling callbacks and middlewares?


texts: How would you refactor this case statement?

texts:
I've got this code in my ApplicationHelper file:

def new_button
  case controller_name
  when 'cars'
    "
New Car
".html_safe
  when 'trucks'
    "
New Truck
".html_safe
  when 'mopeds'
    "
New Moped
".html_safe
  else
    nil
  end
end

So I can just put <%= new_button %> in the view, to display the appropriate button based on the controller_name being accessed.

I have about 10 different controllers to select from (and I'm sure that collection will grow), so the code is getting a bit lengthy.

Is there a better way to accomplish this?


texts: Ruby BST code for insertion implementation

texts:
After some help in understanding difference why direct assignment with setter methods don't work, here is my code for a simple BST in ruby. Would appreciate your reviews and suggestions to refactor the code.

class Node
  attr_accessor :value, :left_child, :right_child

  def initialize (value)
    @value = value
    @left_child = nil
    @right_child = nil
  end
end

class BST
  attr_accessor :root

  def initialize
    @root = nil
  end

  def insert(value, node)

    if self.root == nil
      self.root = Node.new(value)
      return self.root
    end

    return self.root if self.root.value == value

    if node.value > value
      p node
      if node.left_child == nil
        node.left_child = Node.new(value)
        return node
      else
        insert(value, node.left_child)
      end

    else

      if node.right_child == nil
        node.right_child = Node.new(value)
        return node
      else
        insert(value, node.right_child)
      end
    end
  end

end


texts: Scaling and cropping an image adaptively based on the window dimensions

texts:
I've tried my best (I'm new to JS) to write a script that make an image fit to its parent div with respect of the ratio and overflowing when needed.

For example, if the height of the image is smaller than the window's height, I set the height equal to the window's height and the width overflow the window's width. I then horizontally center the image.

If the width is smaller than the window's width, I do the way around.

An example can be seen here: JSFiddle

Note that the example doesn't work as I'm seeing it on my browser (Chrome). Refresh simulation might not work properly.

The fact is that everything is working as expected when I refresh the page. If I try to resize the page, the ratio is not respected at all. But then again, If I refresh the page (after it's been resized), the image fits perfectly.

function imageFitToScreen() {
  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
  var postThumbnailWidth = $('#postThumbnail').width();
  var postThumbnailHeight = $('#postThumbnail').height();
  var imageWidth = $('#postThumbnail').find('img').width();
  var imageHeight = $('#postThumbnail').find('img').height();
  if ((windowHeight < windowWidth) && (imageHeight < imageWidth)) {
    $('#postThumbnail').find('img').css('width', 'auto');
    $('#postThumbnail').find('img').css('height', '100%');
  }
  var imageWidth = $('#postThumbnail').find('img').width(); /* imageWidth value has changed with the if before */
  if ((windowHeight < windowWidth) && (imageWidth < postThumbnailWidth)) {
    $('#postThumbnail').find('img').css('min-width', '100%');
    $('#postThumbnail').find('img').css('height', 'auto');
  }
  if ((windowWidth < windowHeight) && (imageWidth < imageHeight)) {
    $('#postThumbnail').find('img').css('width', '100%');
    $('#postThumbnail').find('img').css('height', 'auto');
  }
  var imageHeight = $('#postThumbnail').find('img').height(); /* imageHeight value has changed with the if before */
  if ((windowWidth < windowHeight) && (imageHeight < postThumbnailHeight)) {
    $('#postThumbnail').find('img').css('width', 'auto%');
    $('#postThumbnail').find('img').css('min-height', '100%');
  }
}

$(window).on("load", imageFitToScreen);
$(window).on("resize", imageFitToScreen);

I double the var imageHeight and var imageWidth before they are called again because they change within the first and third IF.

I don't know if it's important for you to know that I'm changing the #postThumbnail width/height before I run this script.

function refreshDynamicSize() {
  $('#content').find('#postThumbnail').css('min-height', $(window).height() - $('header').height());
  $('#content').find('#postThumbnail').height($(window).height() - $('header').height());
  $('#content').find('#postThumbnailTitle').css('line-height', $(window).height() + 'px');
  $('#content').find('#extend').css('min-height', $('#postThumbnail').height());
}

$(window).on("load", refreshDynamicSize);
$(window).on("resize", refreshDynamicSize);

What I'm looking for is an optimisation of the code as it works on refresh but not on resize.

It might surely be really simple (like change in execution order, or an "on.load" something...).


texts:
I have found a password hashing article and an implementation.

Is this code secure if I increase the salt to 64 bytes, hash key size to 128 bytes and the iterations to 10000? Are there vulnerabilities or incorrectly implemented sections in this code?

I know that Rfc2898DeriveBytes is making use of HMAC-SHA1, but with a high salt bit count, the SHA1 risk is lowered (if my googling can be trusted).

Any advice or words of caution or ways to secure or correct this code would be welcome.

// The following constants may be changed without breaking existing hashes.
public const int SALT_BYTE_SIZE = 24;
public const int HASH_BYTE_SIZE = 24;
public const int PBKDF2_ITERATIONS = 1000;

public const int ITERATION_INDEX = 0;
public const int SALT_INDEX = 1;
public const int PBKDF2_INDEX = 2;

/// <summary>
/// Creates a salted PBKDF2 hash of the password.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <returns>The hash of the password.</returns>
public static string CreateHash(string password)
{
    // Generate a random salt
    RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
    byte[] salt = new byte[SALT_BYTE_SIZE];
    csprng.GetBytes(salt);

    // Hash the password and encode the parameters
    byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
    return PBKDF2_ITERATIONS + ":" +
        Convert.ToBase64String(salt) + ":" +
        Convert.ToBase64String(hash);
}

/// <summary>
/// Validates a password given a hash of the correct one.
/// </summary>
/// <param name="password">The password to check.</param>
/// <param name="correctHash">A hash of the correct password.</param>
/// <returns>True if the password is correct. False otherwise.</returns>
public static bool ValidatePassword(string password, string correctHash)
{
    // Extract the parameters from the hash
    char[] delimiter = { ':' };
    string[] split = correctHash.Split(delimiter);
    int iterations = Int32.Parse(split[ITERATION_INDEX]);
    byte[] salt = Convert.FromBase64String(split[SALT_INDEX]);
    byte[] hash = Convert.FromBase64String(split[PBKDF2_INDEX]);

    byte[] testHash = PBKDF2(password, salt, iterations, hash.Length);
    return SlowEquals(hash, testHash);
}

/// <summary>
/// Compares two byte arrays in length-constant time. This comparison
/// method is used so that password hashes cannot be extracted from
/// on-line systems using a timing attack and then attacked off-line.
/// </summary>
/// <param name="a">The first byte array.</param>
/// <param name="b">The second byte array.</param>
/// <returns>True if both byte arrays are equal. False otherwise.</returns>
private static bool SlowEquals(byte[] a, byte[] b)
{
    uint diff = (uint)a.Length ^ (uint)b.Length;
    for (int i = 0; i < a.Length && i < b.Length; i++)
        diff |= (uint)(a[i] ^ b[i]);
    return diff == 0;
}

/// <summary>
/// Computes the PBKDF2-SHA1 hash of a password.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">The salt.</param>
/// <param name="iterations">The PBKDF2 iteration count.</param>
/// <param name="outputBytes">The length of the hash to generate, in bytes.</param>
/// <returns>A hash of the password.</returns>
private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
{
    Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
    pbkdf2.IterationCount = iterations;
    return pbkdf2.GetBytes(outputBytes);
}


texts: Synchronizing scrollbars, scrollTop and scroll event loops

texts:
I've been playing around synchronizing two scrollbars on a web application using JavaScript and jQuery (1.11.3). So far what I've been doing is any time a scroll event happens on one div, I use scrollTop to adjust the position on the other div:

$left = $("#left")
$right = $("#right")

$left.scroll(function () {
    $right.scrollTop($left.scrollTop());
});

$right.scroll(function () {
    $left.scrollTop($right.scrollTop());
});

(jsFiddle)

The problem comes from scrollTop triggering a scroll event on the element it's called from, creating a loop and making it misbehave on some browsers.

JavaScript events are queued, so toggling a flag before and after a call to scrollTop is not working (and could possibly backfire). So I came up with this solution:

$left = $( "#left" )
scrollLeft = []

$right = $( "#right" )
scrollRight = []

$left.scroll( function () {
    if ( !scrollRight.pop() ) {
        scrollLeft.push( true );
        $right.scrollTop( $left.scrollTop() );
    }
} );

$right.scroll( function () {
    if ( !scrollLeft.pop() ) {
        scrollRight.push( true );
        $left.scrollTop( $right.scrollTop() );
    }
} );

(jsFiddle)

This actually works, even though the scroll event is triggered on the other div the code is not executed and the loop is broken. I'm using a queue with push and pop in case some browser calls event handlers in some weird way; possibly using a single boolean variable could suffice to guard scrollTop.

My question is, is there a better way of doing this?


texts:
I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes).

Am I over-thinking this? Can you help me minimize the code? I am just not seeing it. ALSO, is there any way to simplify the input of so many variables such as in this situation?

def lindexsplit(List,*lindex):

    index = list(lindex)

    index.sort()

    templist1 = []
    templist2 = []
    templist3 = []

    breakcounter = 0
    itemcounter = 0
    finalcounter = 0

    numberofbreaks = len(index)
    totalitems = len(List)

    lastindexval = index[(len(index)-1)]
    finalcounttrigger = (totalitems-(lastindexval+1))

    for item in List:

        itemcounter += 1

        indexofitem = itemcounter - 1

        nextbreakindex = index[breakcounter]

        #Less than the last cut
        if breakcounter <= numberofbreaks:

            if indexofitem < nextbreakindex:

                templist1.append(item)

            elif breakcounter < (numberofbreaks - 1):

                templist1.append(item)

                templist2.append(templist1)

                templist1 = []

                breakcounter +=1

            else:

                if indexofitem <= lastindexval and indexofitem <= totalitems:

                    templist1.append(item)

                    templist2.append(templist1)

                    templist1 = []

                else:

                    if indexofitem >= lastindexval and indexofitem < totalitems + 1:

                        finalcounter += 1

                        templist3.append(item)

                        if finalcounter == finalcounttrigger:

                            templist2.append(templist3)

    return templist2

Example:

mylist = [1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15]
lindexsplit(mylist,3,5,8)
return [[1, 2, 3, 4], [5, 6], [7, 8, 9], [0, 10, 11, 12, 13, 14, 15]]


texts: Python Multi Choice Quiz with a score to count

texts:
I am trying to make a multi choice quiz with a score to count. This is the first time I've used Python and I'm finding it difficult to make the code work properly. How can I make the code shorter and work better? It tells me my code has an infinite loop, how is that so?

#Convert the 0 into a number so we can add scores
score = 0
score = int(score)

#Ask user for their name
name = input("What is your name?")
name = name.title()
print("""Hello {}, welcome to Quiz night!
You will be presented with 5 questions.
Enter the appropriate number to answer the question
Good luck!""".format(name))

#Question1
print("""What is the term for ‘Maori’ language?
1. Te Rex
2. Hangi
3. Hongu
4. Te Reo""")

answer1 = "4"
response1 = input("Your answer is:")

if (response1 != answer1):
    print("Sorry, that is incorrect!")
else:
    print("Well done! " + response1 + " is correct!")
    score = score + 1

print("Your current score is " + str(score) + " out of 5")

#Question2
print("""What is the Maori term for ‘tribe’ or ‘mob’?
1. Mihi
2. Iwi
3. Awi
4. Hapu""")

answer2 = "2"
response2 = input("Your answer is:")

if (response2 != answer2):
    print("Sorry, that is incorrect!")
else:
    print("Well done! " + response2 + " is correct!")
    score = score + 1

print("Your current score is " + str(score) + " out of 5")

#Question3
print("""What is the term for the formal welcome, where two individuals press their nose together?
1. Hongi
2. Haka
3. Hangi
4. Huka""")

answer3 = "1"
response3 = input("Your answer is:")

if (response3 != answer3):
    print("Sorry, that is incorrect!")
else:
    print("Well done! " + response3 + " is correct!")
    score = score + 1

print("Your current score is " + str(score) + " out of 5")

#Question4
print("""Who is the ‘demi-god’ or the ‘great creator’ who fished NZ out from the sea?
1. Zeus
2. Hercules
3. Maui
4. Maori""")

answer4 = "3"
response4 = input("Your answer is:")

if (response4 != answer4):
    print("Sorry, that is incorrect!")
else:
    print("Well done! " + response4 + " is correct!")
    score = score + 1

print("Your current score is " + str(score) + " out of 5")

#Question5
print("""What is the name for the traditional Maori method of cooking?
1. Roast
2. Hangi
3. Hongi
4. Bake""")

answer5 = "2"
response5 = input("Your answer is:")

if (response5 != answer5):
    print("Sorry, that is incorrect!")
else:
    print("Well done! " + response5 + " is correct!")
    score = score + 1

print("Your total score is " + str(score) + " out of 5")
print("Thank you for playing {}, goodbye!".format(name))


texts:
I just recently finished the following problem on Leetcode problem. I know it's not the cleanest or fastest solution. I would appreciate if I can get some feedback on how to optimize the code.

The idea is too add all possible prefixes into an array and return the longest possible prefix. I believe this is probably why the algorithm doesn't run as fast as it should.

Also, I would appreciate if someone can assist in determining what the space and time complexity would be for the algorithm below?

var longestCommonPrefix = function(strs) {
const firstWord = strs[0];
const arrResults = [];
let index = 1;
let arrWithoutFirstElement = strs.slice(1, strs.length);
if(strs.length===0)return '';
if(strs.length===1)return strs[0];

while(index <= firstWord.length) {
   if(arrWithoutFirstElement.every(element =>
       element.substring(0,index)===firstWord.substring(0,index))){
       arrResults.push(firstWord.substring(0,index));
   }
   index++;
}

return arrResults.length > 0  ? arrResults[arrResults.length-1] : '';
}

console.log(longestCommonPrefix(["flower","flow","flight"]));


texts:
I have written this code as a college assignment fot the famous job sequencing problem. Please tell me any improvements if possible. Oh, for algorithms.h header file, refer my github repo

The code:

#include "algorithms.h"

struct Job {
    int index = 0;
    int time_slot = 0;
    int profit = 0;
public:
    Job() = delete;
    explicit Job(int i, int time, int pr) {
        index = i;
        time_slot = time;
        profit = pr;
    }
    bool operator>=(Job j) {
        if ((this->time_slot == j.time_slot && this->profit >= j.profit) || (this->time_slot > j.time_slot)) {
            return true;
        }
        return false;
    }
    bool operator<=(Job j) {
        if ((this->time_slot == j.time_slot && this->profit <= j.profit) || (this->time_slot < j.time_slot)) {
            return true;
        }
        return false;
    }
    bool operator<(Job j) {
        if ((this->time_slot == j.time_slot && this->profit < j.profit) || (this->time_slot < j.time_slot)) {
            return true;
        }
        return false;
    }
    bool operator>(Job j) {
        if ((this->time_slot == j.time_slot && this->profit > j.profit) || (this->time_slot < j.time_slot)) {
            return true;
        }
        return false;
    }
    bool operator==(Job j) {
        if (this->time_slot == j.time_slot) {
            return true;
        }
        return false;
    }
    friend std::ostream& operator<<(std::ostream& out, Job job) {
        out << job.index;
        return out;
    }
};

int main() {
    Job j1(1, 1, 3);
    Job j2(2, 3, 5);
    Job j3(3, 4, 20);
    Job j4(4, 3, 18);
    Job j5(5, 2, 1);
    Job j6(6, 1, 6);
    Job j7(7, 2, 30);
    std::vector<Job> vect = { j1,j2,j3,j4,j5,j6,j7 };
    vect = Sorter<Job>::mergeSort(vect);
    auto order = [&]() {
        auto it = vect.begin();
        while (it + 1 != vect.end()) {
            if (*it == *(it + 1)) {
                it = vect.erase(it);
                continue;
            }
            it++;
        }
    };
    order();
    std::for_each(vect.begin(), vect.end(), [](Job i) {std::cout << i << " "; });
    return 0;
}


texts: consecutive_find function for returning a consecutive range of elements

texts:
consecutive_find() is a function that returns the beginning of a range that contains strictly N consecutive elements. It was part of a SO question that I answered.

Currently this function runs in \$O(n)\$ time. I wanted to know if there are any pitfalls with this function and if it can be improved at all. For example, are there any standard algorithms that can be used here that have not been? Here is a demo.

Explanation of code:

It sets two variables to the start of the range: marker and lead. lead is always going to be 1 position greater than marker (in order to see if there are more consecutive elements).

Then we loop through a count how many elements equal *lead using a variable count.

It checks count to see if it equals n (the element count we're looking for) and if either lead is the iterator to the end, or if lead points to an element that is different than marker, then we know that there are no more matching elements that we haven't checked, and we return marker, which is n places behind lead.

If that condition fails, then we know *lead == *marker. This goes against the strict condition that we want because there are greater than N consecutive elements. So we set marker to the next position that doesn't equal *lead to prevent unneeded extra loops. marker is set to lead and count is reset to 1.

template <class Iter>
Iter consecutive_find(Iter first, Iter last, std::size_t n)
{
    Iter marker(first), lead(first);
    std::size_t count(1);

    using value_type = typename std::iterator_traits<Iter>::value_type;

    while (lead != last)
    {
        lead = std::next(marker);
        while ((lead != last) && (*marker == *lead)) { ++count; ++lead; }
        if (count == n)
        {
            if ((lead == last) || !(*lead == *marker))
                return marker;
        }
        marker = std::find_if_not(lead, last,
                                  [&lead] (value_type const& x) { return x == *lead; });
        count = 1;
    }
    return last;
}

I can change the nested while() loop to lead = std::find_if_not(lead, last, \[&lead\] (value_type const& x) { return x == *lead; }); but then that violates the DRY rule.


texts:
I have limited experience with both making REST APIs and implementing security features, so I figured it'd be worth running this code through some other people's eyes before making it live.

My main questions are around the use of REST - e.g. are there better ways to implement my methods that return bools?

(Assume the "drivers" are keyed in the DB by Name)

public class Driver
{
    public string Name { get; set; }
    public string Pass { get; set; }
}

[HttpPost]
[RequireHttps]
[ActionName( "GetPasswordExists" )]
public HttpResponseMessage GetPasswordExists([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        bool passExists = false;
        // db operations
        response = Request.CreateResponse(HttpStatusCode.OK, passExists);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}

[HttpPost]
[RequireHttps]
[ActionName("SetPassword")]
public HttpResponseMessage SetPassword([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        string hash = System.Web.Helpers.Crypto.HashPassword(driver.Pass);
            // db operations
            response = Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}

[HttpPost]
[RequireHttps]
[ActionName("VerifyPassword")]
public HttpResponseMessage VerifyPassword([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        bool valid = false;
        string hash = null;
        // db operations
        valid = System.Web.Helpers.Crypto.VerifyHashedPassword(hash, driver.Pass);
        response = Request.CreateResponse(HttpStatusCode.OK, valid);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}


texts: Checking for existence of object by id, name, display name, or web id

texts:
I have the following code:
public final boolean doesExistById(Long id) {
    return dataAccessObject.findById(id) != null;
}

public final boolean doesExistByName(String name) {
    return dataAccessObject.findByName(name) != null;
}

public final boolean doesExistByDisplayName(String displayName) {
    return dataAccessObject.findByDisplayName(displayName) != null;
}

public final boolean doesExistByWebId(String webId) {
    return dataAccessObject.findByWebId(webId) != null;
}

My Product class has properties id, name, displayName, wedId.
dataAccessObject.findBy____() returns an object of type Product, if it can be found in the data store, or null if it cannot.
I would like to reduce this chunk of code, if possible, because I have many objects that require the doesExist() pattern as above. The client code will only know one of these properties.

A possible solution I thought of would be to do this:
public final boolean doesExist(Long id, String name, String displayName, String webId) {..}

and then call it with null for unknown fields while using if statements to determine which field has a value. But is there another way that is more elegant?

One of the answers I got over was this, from user StriplingWarrior:

You are recognizing that the "does exist" part of all of these methods is exactly the same, and that makes you want to avoid repeating it, but the "ByXxx" part of these methods is completely different.
What you've got is far better than what you're thinking of doing. Please don't change your method signature to require callers to provide null values for all but one argument. That is highly error-prone, as it provides no compile-time errors for a variety of different ways that people might use the method signature incorrectly.
One thing you might want to consider doing is separating the "does exist" piece of this into its own mechanism:
public final Optional<MyObj> byId(Long id) {
    return Optional.ofNullable(dataAccessObject.findById(id));
}

So instead of saying service.doesExistById(123), you'd say service.byId(123).isPresent(). This represents the same meaning semantically, but it's broken into separate parts, which means you can reuse byId(), byName(), etc., for other purposes where you need the actual object, and not just to know whether it exists.

My ultimate question is, aside from the current solution, is there another way to refactor this code block so I don't have so much repeated similar code?


texts: Tag Cloud using 2 queries (one nested), and a foreach loop: Is there a better way?

texts:
I have a database that, among other things, stores publications and publication tags.  There is a many-to-many relationship between publications and publication tags.  Simply put, I query the database for all the publication tags and the corresponding id.  While looping through that query, I have a nested query to count the number of times each tag is used.  Once I have all the information, I then loop through all results to display the tags.  That seems inefficient, but I can't think of a better way.  Thoughts?

//get the tag id and tag names
try {
  $stmt = $pdo->prepare('SELECT publicationTagId, tagName FROM publicationTags WHERE EXISTS (SELECT publicationTags_publicationTagId FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = publicationTagId)ORDER BY tagName');
  $stmt->execute();
} catch(PDOException $e) {
    echo "
Oops!
";
}
$tags = $stmt->fetchAll();

$tagCount = array();
//iterate through the tags and get usage counts
foreach($tags as $tag) {
  try {
    $stmt = $pdo->prepare('SELECT count(publicationTags_publicationTagId) FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = :pubId');
    $stmt->execute(array(':pubId'=>$tag[0]));
    while($tagCounter = $stmt->fetch()) {
      $tagCount[] = $tagCounter[0];

    }
  } catch(PDOException $e) {
    echo "
Oops!
";
  }
}

//get the min and max usages
$minUse = min($tagCount);
$maxUse = max($tagCount);

//max and min font size
$maxPercent = 150;
$minPercent = 100;

//prevent divide by zero
$divisor = ($maxUse == $minUse) ? 1 : $maxUse - $minUse;

//multiplier
$multiplier = ($maxPercent - $minPercent) / $divisor;

//set up list
echo "
";

$counter = 0;
//loop through tags
foreach($tags as $tag) {
    $size = $minPercent + ($tagCount[$counter][0]-$minUse)*$multiplier;
    echo "
$tag[1]
";
    $counter++;
}

//reset link
echo "
View All
";

//close the list
echo "
";


texts: Doubly linked list implementation in Python

texts:
Here's my implementation of doubly linked list in Python:

 class DList:

    def __init__(self):
        self.head = None
        self.size = 0

    def insert(self, data):
        self.size += 1
        if self.head is None:
            self.head = Node(data)
        else:
            p = Node(data)
            p.next = self.head
            self.head.previous = p
            self.head = p

    def remove(self, index):
        if self.head is None:
            raise ValueError('Removing off an empty list')
        if index < 0 or index >= self.size:
            raise IndexError("Index is either negative or greater than the list size.")
        current = self.head
        if index == 0:
            self.head = self.head.next
            self.head.previous = None
        else:
            for _ in range(index -1):
                current = current.next
            p = current.next.next
            if p is None:
                current.next = None
            else:
                current.next = p
                p.previous = current

    def __sizeof__(self):
        return self.size

    def __repr__(self):
        res = '[ '
        current = self.head
        while current is not None:
            res += str(current.data)
            res += ' '
            current = current.next
        res += ']'
        return res

class Node:
    def __init__(self, data):
        if data is None:
            raise ValueError('Node value cannot be None')
        self.data = data
        self.previous = None
        self.next = None


texts:
I have a table of groups, and a table of members. Each member belongs to one group. This is how it looks (more groups then 2 are possible):

Groups

id | name | year |
------------------
1  | Nice | 1966 |
2  | Hard | 2012 |

Member

id | name  | idGroup |
----------------------
1  | Bernd | 1       |
2  | Max   | 1       |
3  | Tom   | 2       |
4  | Bob   | 1       |
5  | Alice | 2       |

I want to compute a table, where each group is listed once, together with all its members, like this:

name | year | members         |
-------------------------------
Nice | 1966 | Bernd, Max, Bob |
Hard | 2012 | Tom, Alice      |

At the moment, I use two queries to get this table:

    Groupname
    Year
    Members

<?php
$db           = new mysqli("localhost","user","pass","database");
$sql          = "SELECT id, name, year FROM groups";
$groupsResult = $db->query($sql);

while($group = $groupsResult->fetch_assoc())
{
  $groupName = htmlspecialchars($group['name']);
  $groupYear = htmlspecialchars($group['year']);
  $members   = "";

  $stmt         = $db->prepare('SELECT name FROM member WHERE idGroup = ?');
  $stmt->bind_param('i',$group['id']);
  $stmt->execute();
  $memberResult =   $stmt->get_result();

  while($member =   $ergebnis->fetch_assoc())
  {
    if(!empty($members)) $members .= ", ";
    $members .= htmlspecialchars($member["name"]);
  }

  ?>

    <?php echo $groupName; ?>
    <?php echo $groupYear; ?>
    <?php echo $members; ?>

<?php
}
?>

But I have the feeling that this is not a good approach.

I know that I can get with an INNER JOIN the result.

id | name  | groupName | year
------------------------------
1  | Bernd | Nice      | 1966
2  | Max   | Nice      | 1966
3  | Tom   | Hard      | 2012
4  | Bob   | Nice      | 1966
5  | Alice | Hard      | 2012

but this does not seem to help me. Is it possible to get with one SQL directly the result:

name | year | members         |
-------------------------------
Nice | 1966 | Bernd, Max, Bob |
Hard | 2012 | Tom, Alice      |

or is there another way how I can optimize this code?


texts: Binding touch events and moving an element

texts:
I have the following jQuery plugin that binds touch events and moves an element.

In the functions moveMe and snap, there is duplicate code doing the same thing because I couldn't figure out how to refactor the scope of the functions to only do this once.

$.fn.draggable = function(limit) {

  var offset = null;
  var start = function(e) {
    var orig = e.originalEvent;
    var pos = $(this).position();
    offset = {
      x: orig.changedTouches[0].pageX - pos.left,
      //y: orig.changedTouches[0].pageX - pos.top
    };
    $(this).stop(true,false);
  };

  var moveMe = function(e) {
    e.preventDefault();
    $('body').css('overflow-x','hidden');

    var orig    = e.originalEvent;
    var touchX  = orig.changedTouches[0].pageX;
    var difference = touchX - offset.x;
    var move;

    if (difference >= limit) {
        move = limit;
    } else if (difference <= 0) {
        move = 0;
    } else {
        move = difference;
    }

    $(this).css({
      left: move,
      //left: orig.changedTouches[0].pageX - offset.x
    });

  };

  var snap = function(e) {

    var orig    = e.originalEvent;
    var touchX  = orig.changedTouches[0].pageX;
    var difference = touchX - offset.x;
    var threshold = limit*0.75;

    if (difference >= limit) {
        move = limit;
    } else if (difference <= 0) {
        move = 0;
    } else {
        move = difference;
    }

    if (threshold > (limit-move)) {
        $(this).animate({
            left : limit
        });
    } else {
        $(this).animate({
            left : 0
        });
    }

    };

  this.bind("touchstart", start);
  this.bind("touchmove", moveMe);
  this.bind("touchend", snap);

};

$("#container").draggable(200);


texts:
this is my implementation of std::forward

template<typename T, typename U>
constexpr decltype(auto) forward(U && u) noexcept
{
    return static_cast<T &&>(u);
}

compared to the standards

template<typename T>
constexpr T && forward(typename std::remove_reference<T>::type & __t) noexcept
{
    return static_cast<T &&>(__t);
}

template<typename T>
constexpr T && forward(typename std::remove_reference<T>::type && __t) noexcept
{
    return static_cast<T &&>(__t);
}

the standard uses the remove_reference to ensure usage of:

forward<T>(value)

which then requires them to overload each rvalue / lvalue instance of forward. Whereas I am using a second template parameter to ensure the correct usage, which allows me not need an overload.

can anyone point out any downfalls in my implementation?

Note: decltype(auto) can be replaced with T && for the same results.


texts:
For work I had to implement the DBSCAN algorithm in the 3D space for clusters finding. It works, now I wonder how is the quality of the code. I'm especially concerned about incrementing the size of the vector during the for loop in the expandCluster lambda. I followed the Wikipedia article

struct ivec3
{
    int x;
    int y;
    int z;
};

std::vector<std::vector<ivec3>> dbscan3D(std::vector<ivec3> &dataset, int eps, int min_pts)
{
    // https://en.wikipedia.org/wiki/DBSCAN

    std::vector<std::vector<ivec3>> clusters;
    int idx_current_cluster = 0;

    struct info_point
    {
        ivec3 position;
        int cluster;
    };

    std::unordered_map<int, info_point> map_info_dataset;

    auto getKey = [](ivec3 P)
    {
        return ((int64_t)P.z << 42) + ((int64_t)P.y << 21) + (int64_t)P.x;
    };

    for (auto&& P : dataset)
    {
        map_info_dataset[getKey(P)] = info_point{ P, -1 };
    }

    auto regionQuery = [&eps, &map_info_dataset, &getKey](const int key)
    {
        const auto& pos_P = map_info_dataset.at(key).position;

        std::vector<int> keys_neighborPts;

        for (int x = pos_P.x - eps; x <= pos_P.x + eps; ++x)
        {
            for (int y = pos_P.y - eps; y <= pos_P.y + eps; ++y)
            {
                for (int z = pos_P.z - eps; z <= pos_P.z + eps; ++z)
                {
                    int key = getKey({ x, y, z });

                    if (map_info_dataset.count(key))
                    {
                        keys_neighborPts.push_back(key);
                    }
                }
            }
        }
        return keys_neighborPts;
    };

    auto expandCluster = [&eps, &min_pts, &map_info_dataset, &clusters, &regionQuery]
    (const int key, std::vector<int> &keys_neighborPts, int idx_current_cluster)
    {
        clusters.at(idx_current_cluster).push_back(map_info_dataset.at(key).position);
        map_info_dataset.at(key).cluster = idx_current_cluster;

        for (int i = 0; i < keys_neighborPts.size(); ++i)
        {
            auto &local_key = keys_neighborPts[i];
            auto &local_point = map_info_dataset.at(local_key);

            if (local_point.cluster == -1)
            {
                auto keys_neighborPts_local_point = regionQuery(local_key);

                if (keys_neighborPts_local_point.size() >= min_pts)
                {
                    keys_neighborPts.insert(keys_neighborPts.end(), keys_neighborPts_local_point.begin(), keys_neighborPts_local_point.end());
                }

                clusters.at(idx_current_cluster).push_back(local_point.position);
                local_point.cluster = idx_current_cluster;
            }
        }
    };

    for (auto&& P : map_info_dataset)
    {
        const int& key_P = P.first;
        info_point& info_P = P.second;

        if (info_P.cluster != -1)
        {
            continue;
        }

        auto keys_neighborPts = regionQuery(key_P);

        if (keys_neighborPts.size() >= min_pts)
        {
            clusters.emplace_back();
            expandCluster(key_P, keys_neighborPts, idx_current_cluster);
            ++idx_current_cluster;
        }
    }

    return clusters;
}


texts: How is my Java code for stack implementation?

texts:
The following example shows how to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.

public class MyStack {
  private int maxSize;
  private long[] stackArray;
  private int top;

  public MyStack(int s) {
    maxSize = s;
    stackArray = new long[maxSize];
    top = -1;
  }

  public void push(long j) {
    stackArray[++top] = j;
  }

  public long pop() {
    return stackArray[top--];
  }

  public long peek() {
    return stackArray[top];
  }

  public boolean isEmpty() {
    return (top == -1);
  }

  public boolean isFull() {
    return (top == maxSize - 1);
  }

  public static void main(String[] args) {
    MyStack theStack = new MyStack(10);
    theStack.push(10);
    theStack.push(20);
    theStack.push(30);
    theStack.push(40);
    theStack.push(50);

    while (!theStack.isEmpty()) {
      long value = theStack.pop();
      System.out.print(value);
      System.out.print(" ");
    }

    System.out.println("");
  }
}


texts:
So here we have a little game of Tic Tac Toe I've made. It runs well on TI-83/84 calculators and it doesn't seem to have any problems. However, I'd like to eliminate some of the code that seems bulky and repetitive as well as possibly add some checks so you can't overwrite a square that's already been played and to finish the game when a row of 3 has been made. If anyone could help me I'd appreciate it!

:ClrHome
:ClrDraw
:1->X
:0->I
:0->O
:Horizontal 9
:Horizontal 3
:Horizontal -3
:Horizontal -9
:Vertical 9
:Vertical 3
:Vertical -3
:Vertical -9
:Disp "WHO FIRST X OR O"
:Input F
:Disp "USE 1 THROUGH 9"
:Lbl 1
:Input M
:fPart(M/3)3-2->H
:If H=-2
:1->H
:H*6->H
:-6->V
:If M>3
:0->V
:If M>6
:6->V
:If F
:Then
:Line(H-2,V-2,H+2,V+2)
:Line(H-2,V+2,H+2,V-2)
:Else
:Circle(H,V,2)
:End
:I+1->I
:abs(F-1)->F
:If I=9
:Goto 2
:Pause
:Goto 1
:Lbl 2


texts:
https://leetcode.com/problems/burst-balloons/

  Given n balloons, indexed from 0 to n-1, each balloon is painted with
  a number on it represented by array nums. You are asked to burst all
  the balloons. If you burst balloon i, the number of coins you will get is calculated as:
  $$ nums[left] * nums[i] * nums[right] $$Here, left and right are adjacent indices of i. After the burst, left and right then becomes adjacent.

  Find the maximum coins you can collect by bursting the balloons
  wisely.

  Note:

  You may imagine $$ nums[-1] = nums[n] = 1 $$They are not real therefore
  you can not burst them. 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
             coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RecurssionQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/burst-balloons/
    /// </summary>
    [TestClass]
    public class BurstBalloonsTest
    {
        [TestMethod]
        public void TestExample()
        {
            int[] nums = {3, 1, 5, 8};
            BurstBalloonsClass burst = new BurstBalloonsClass();
            Assert.AreEqual(167, burst.MaxCoins(nums));
        }
    }

    public class BurstBalloonsClass
    {

        public int MaxCoins(int[] nums)
        {
            int[] numbers = new int[nums.Length +2];  // we add 2 because of the question
            // nums[-1] = nums[n] = 1
            int n = 1;
            foreach (var x in nums)
            {
                if (x > 0) // we care only about positive values for profit
                {
                    numbers[n++] = x;
                }
            }
            numbers[0] = numbers[n++] = 1;
            int[][] memo = new int[n][];
            for (var index = 0; index < memo.Length; index++)
            {
                memo[index]= new int[n];
            }
            // we allocate NxN matrix for memoization

            return Burst(memo, numbers, 0, n - 1);
        }

        private int Burst(int[][] memo, int[] numbers, int left, int right)
        {
            if (left + 1 == right)
            {
                return 0;
            }

            if (memo[left][right] > 0)
            {
                return memo[left][right];
            }

            int ans = 0;
            // we try all the options between left and right
            // we compare the answers of all of the options and the maxmial one
            // if poped all of the ballons from left to u and from i to right we have only an option to pop
            // numbers[left] * numbers[i] * numbers[right]
            for (int i = left + 1; i < right; ++i)
            {
                ans = Math.Max(ans, numbers[left] * numbers[i] * numbers[right]
                                    + Burst(memo, numbers, left, i)
                                    + Burst(memo, numbers, i, right));
            }

            memo[left][right] = ans;
            return ans;
        }
    }
}


texts:
I am modeling a capacitor which has its capacitance varying according to the DC Bias. The DC Bias is computed by taking the mean of the voltage across the capacitance.

class CAP:
    """
    Represents the Capacitor.
    """
    def __init__(self, nominal_capacitance):
        # Theoretical capacitance without DC Bias (i.e. voltage mean at 0)
        self.nominal_capacitance = nominal_capacitance # uF
        # Actual capacitance, initialized at the nominal value
        self.capacitance = nominal_capacitance # uF

        # Voltage control loop settings
        self.set_voltage_value = None # Value set in mV
        self.set_lower_voltage_window_bound = None # Window upper bound in mV
        self.set_upper_voltage_window_bound = None # Window lower bound in mV
        self.voltage = 0 # Voltage across the capacitor
        self.being_charge = False # Is it being charged/discharged by the control loop?

        # Measurements
        self.charge_counter = 0
        self.discharge_counter = 0

        self.voltage_charged = 0
        self.voltage_discharged = 0

        # List of the voltage across the capacitance
        self.timeline = [] # mV

    def update_capacitance(self):
        """
        Value according to the DC Bias characterstic approximation.
        """
        global timelines_resolution # time step between 2 voltages measurements in the list self.timeline

        DC_bias = np.mean(self.timeline) / 1000
        change_perc = (-0.0008*(DC_bias**4)+0.0474*(DC_bias**3)-0.7953*(DC_bias**2)-0.5447*DC_bias-0.4847)/100
        self.capacitance = self.nominal_capacitance * (1+change_perc)

The voltage across the capacitance is controlled via a control loop which will recharge or discharge the capacitor. The goal is to keep its voltage within boundaries (window).

The attribute self.timeline will have one measure point (voltage) added every timelines_resolution. I can get between 200 000 points to a few millions.

The conversion to a numpy array and the mean computation become quite long. On the otherhand, it is handy to work with a list and its append method since I do not know beforehand the number of point that will be measured.

Do you see any other way to compute this DC Bias or to make this faster?
At the moment, I call the function update_capacitance every 25000 points. I would like to increase this resolution.


texts:
I have a Cache Helper Class.

using System;
using System.Web;

public static class CacheHelper
{
    /// <summary>
    /// Insert value into the cache using
    /// appropriate name/value pairs
    /// </summary>
    /// <typeparam name="T">Type of cached item</typeparam>
    /// <param name="o">Item to be cached</param>
    /// <param name="key">Name of item</param>
    public static void Add<T>(T o, string key)
    {
        // NOTE: Apply expiration parameters as you see fit.
        // I typically pull from configuration file.

        // In this example, I want an absolute
        // timeout so changes will always be reflected
        // at that time. Hence, the NoSlidingExpiration.
        HttpContext.Current.Cache.Insert(
            key,
            o,
            null,
            DateTime.Now.AddMinutes(1440),
            System.Web.Caching.Cache.NoSlidingExpiration);
    }

    /// <summary>
    /// Remove item from cache
    /// </summary>
    /// <param name="key">Name of cached item</param>
    public static void Clear(string key)
    {
        HttpContext.Current.Cache.Remove(key);
    }

    /// <summary>
    /// Check for item in cache
    /// </summary>
    /// <param name="key">Name of cached item</param>
    /// <returns></returns>
    public static bool Exists(string key)
    {
        return HttpContext.Current.Cache[key] != null;
    }

    /// <summary>
    /// Retrieve cached item
    /// </summary>
    /// <typeparam name="T">Type of cached item</typeparam>
    /// <param name="key">Name of cached item</param>
    /// <param name="value">Cached value. Default(T) if
    /// item doesn't exist.</param>
    /// <returns>Cached item as type</returns>
    public static bool Get<T>(string key, out T value)
    {
        try
        {
            if (!Exists(key))
            {
                value = default(T);
                return false;
            }

            value =  (T) HttpContext.Current.Cache[key];
        }
        catch
        {
            value = default(T);
            return false;
        }

        return true;
    }
}

and usage:

string key = "EmployeeList";
List<Employee> employees;

if (!CacheHelper.Get(key, out employees))
{
    employees = DataAccess.GetEmployeeList();
    CacheHelper.Add(employees, key);
    Message.Text =
        "Employees not found but retrieved and added to cache for next lookup.";
}
else
{
    Message.Text = "Employees pulled from cache.";
}

Do you see any improvement / issue?


texts: Filtering users by criteria in Ruby on Rails

texts:
I am a fairly new (RubyonRails) developer. I desire to improve my coding skills so I used climate to do some review on my code. It gave me a flag for this method that its complex. Is it characterised as complex because of having several "actions/tasks" in a single method?

Will it be better if I extract some code segments to a different method?

Is there something else I am not seeing?

  def search
    filter_mapping = {"cost" => "rcost", "quality" => "rquality", "time" => "rtime", "experience" => "rexperience", "communication" => "rcommunication"}
    @filters = params[:filter].split(",") rescue []
    @sort = params[:sort]

    @user_type = params[:s_user_type]
    @skills = params[:s_skills]
    @location = params[:location]
    @max_rate = params[:max_rate]
    @availability = params[:availability]

    @users = User.scoped.joins(:user_skills)
    @users = @users.where('user_type = ?', @user_type) if @user_type.present?
    @users = @users.where('user_skills.skill_id in (?)', @skills.map(&:to_i)) if @skills.present? && @skills.size > 0
    @users = @users.where('availability = ?', @availability) if @availability.present?
    @users = @users.where('location_country = ?', @location) if @location.present?
    @users = @users.where('rate < ?', @max_rate.to_i) if @max_rate.present?
    @users = @users.page(params[:page]).per(PER_PAGE)

    @filters.each do |f|
      if filter_mapping.keys.include?(f)
        @users = @users.order("#{filter_mapping[f]} desc")
      end
    end

    @users = @users.order('id asc') if @filters.empty?
    @advanced_link = @location.blank? && @max_rate.blank? && @availability.blank?
    render :index
  end

Update

I figured out that I can extract the scopes into a method like that:

  def get_users_where_scopes
    @users = User.scoped.joins(:user_skills)
    @users = @users.where('user_type = ?', @user_type) if @user_type.present?
    @users = @users.where('user_skills.skill_id in (?)', @skills.map(&:to_i)) if @skills.present? && @skills.size > 0
    @users = @users.where('availability = ?', @availability) if @availability.present?
    @users = @users.where('location_country = ?', @location) if @location.present?
    @users = @users.where('rate < ?', @max_rate.to_i) if @max_rate.present?
    @users = @users.page(params[:page]).per(PER_PAGE)
  end

and then call it with @users = get_users_where_scopes(). But now the complexity of this method seems wrong to me.


texts: Best Practices concerning Includes and SQL Connect Strings

texts:
I'm just starting to learn PHP. I have three random questions about PHP and one question about Code Review. None of them are technical questions ("will this work?"); they're best practices questions ("is this the best way to do this?"). Can you offer advice?

I put commonly used data in separate files and use include to insert them into other pages. This avoids typing the exact same code into dozens of files. Is that considered a best practice? Is there a better way to organize common page elements? An example:
A file named footer.php:

<?php echo "
Copyright Michael

Go home
" ?>

And a snippet that's in all my other files:

 <?php include "footer.php ?>

What's the best way to store a MySQL connect string? I saved it in a separate "util.php" file. It reads something like:

<?php $con=mysqli_connect("localhost","admin","password","devDatabase");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

All files that connect to the db have:

<?php include "util.php" ?>

Is than an efficient and/or secure way to store the connection string?
What PHP frameworks do you recommend? I'm trying to get a solid understanding of PHP/Javascript/MySQL for basic web design. After that, should I select a particular PHP framework? Or should I skip PHP and move to a newer language like Ruby on Rails?

Finally, can I get feedback by posting my URL here? If I list www.mynewsite.com and post the code for the main PHP files, could I get general feedback on the site?


texts: Improved the output of the related posts in WordPress

texts:
I made a simple code to improve the results for WordPress related posts area and it works fine , but because my experience in coding is low , my code is very long and i believe that there is a way to make simple and better

here is the code :-

$cat = get_the_category();
$cat0 = $cat[0];
$cat1 = $cat[1];
$cat2 = $cat[2];
$cat3 = $cat[3];
$cat4 = $cat[4];
$cat5 = $cat[5];
$cat6 = $cat[5];

    if ($cat0->cat_ID == 10 || $cat1->cat_ID == 10 || $cat2->cat_ID == 10 || $cat3->cat_ID == 10 || $cat4->cat_ID == 10 || $cat5->cat_ID == 10 || $cat6->cat_ID == 10){
        $post = get_the_ID();
        $args = array('cat'=>10, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));
    } elseif ($cat0->cat_ID == 12 || $cat1->cat_ID == 12 || $cat2->cat_ID == 12 || $cat3->cat_ID == 12 || $cat4->cat_ID == 12 || $cat5->cat_ID == 12 || $cat6->cat_ID == 12){
        $post = get_the_ID();
        $args = array('cat'=>12, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));
    } else {
        $cat = $cat[0];
        $cat = $cat->cat_ID;
        $post = get_the_ID();
        $args = array('cat'=>$cat, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));
    }

$related = new WP_Query($args);

Also, i tried to use "foreach" function but it always fails in "else" part

Thanks


texts:
The challenge

  A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,...,n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

  Note: the number of first circle should always be 1.

  Input

  \$n\quad (0 \lt n \le 16)\$

  Output

  The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. You are to write a program that completes above process.

  Sample Input

6
8

  Sample Output

  Case 1:

1  4  3  2  5  6
1  6  5  2  3  4

  Case 2:

1  2  3  8  5  6  7  4
1  2  5  8  3  4  7  6
1  4  7  6  5  8  3  2
1  6  7  4  3  8  5  2

My solution

#include <iostream>
#include <algorithm>

const int MAX_P = 50;
bool primes[MAX_P];

void gen_primes()
{
  std::fill(primes, primes + MAX_P, true);

  primes[0] = primes[1] = false;

  // discard 2's multiples
  for ( int i = 4; i < MAX_P; i += 2 )
    {
      primes[i] = false;
    }

  // discard other prime numbers(3, 5, ..)'s multiples
  for ( int p = 3; p < MAX_P; p += 2 )
    {
      if ( !primes[p] )
        continue;

      for ( int i = p * p; i < MAX_P; i += 2 * p )
        {
          primes[i] = false;
        }
    }
}

const int MAX = 17;
int prime_ring_idx, n;
int prime_ring[MAX];
bool number_taken[MAX];

void print_prime_ring()
{
  std::cout << 1;
  for ( int i = 2; i <= n; ++i )
    {
      std::cout << " " << prime_ring[i];
    }
  std::cout << std::endl;
}

void gen_prime_ring()
{
  // all n numbers filled, print the solution
  if ( prime_ring_idx >= n )
    {
      print_prime_ring();
      return;
    }

  for ( int i = 2; i <= n; ++i )
    {
      if ( !number_taken[i] &&
           primes[i + prime_ring[prime_ring_idx]] )
        {
          // if it is nth number check if it can make a prime
          // with the first number, so as to complete the circle
          if ( prime_ring_idx == n - 1 &&
               !primes[i + prime_ring[1]] )
            {
              continue;
            }

          number_taken[i] = true;
          prime_ring[++prime_ring_idx] = i;

          gen_prime_ring();

          number_taken[i] = false;
          prime_ring[prime_ring_idx--] = 0;
        }
    }
}

int main()
{
  int c = 1;

  gen_primes();
  prime_ring[1] = 1;

  // initially no numbers are taken
  for ( int i = 0; i < MAX; ++i )
    {
      number_taken[i] = false;
    }

  // 1 will always be the first number for the circle so take it
  number_taken[1] = true;

  while ( std::cin >> n )
    {
      if ( c != 1 )
        {
          std::cout << std::endl;
        }
        std::cout << "Case " << c++ << ":" << std::endl;

      prime_ring_idx = 1;
      gen_prime_ring();
    }
  return 0;
}

Share your ideas to improve my code on:

Efficiency
Code style
Design patterns
Readability


texts: Retrieve annotation from a tree annotated with a Monoid

texts:
Working on this homework from 2013 for self-learning.

For the following Algebraic Data Type:

data JoinList m a = Empty
                  | Single m a
                  | Append m (JoinList m a) (JoinList m a)
    deriving (Eq, Show)

I implemented tag:

tag :: Monoid m => JoinList m a -> m
tag Empty                 = mempty
tag (Single x _)          = x
tag (Append x left right) = x

Example:

*JoinList Data.Monoid> tag (Append (Product 100) (Single (Product 10) "foo") (Single (Product 10) "bar"))
Product {getProduct = 100}

*JoinList Data.Monoid> tag (Empty :: JoinList (Product Integer) String)
Product {getProduct = 1}

*JoinList Data.Monoid> tag (Single (Product 5) "foo")
Product {getProduct = 5}

Originally, I had implemented the Append ... case as:

tag (Append x left right) = x  `mappend` (tag left) `mappend` (tag right)

But, I'm not sure if I can assume that the Monoid m in JustList m x is already populated.

Please critique my implementation.


texts: Create a view with a thick inner border that has a gradient

texts:
InnerGradientBorderView is a subclass of UIView that has a thick border with a gradient. I have tried to replicate the Zoom meeting UI. They apply this kind of a border during screenshare.

import UIKit

class InnerGradientBorderView: UIView {

    var gradientLayers = [CAGradientLayer]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.clear
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        for layer in gradientLayers {
            layer.removeFromSuperlayer()
        }

        addGradientInnerBorder(width: 8, color: UIColor.orange)
    }

    func addGradientInnerBorder(width: CGFloat, color: UIColor) {

        // Setup
        let topLeftO = CGPoint(x: 0, y: 0)
        let topLeftI = CGPoint(x: width, y: width)

        let topRightO = CGPoint(x: frame.width, y: 0)
        let topRightI = CGPoint(x: frame.width - width, y: width)

        let bottomLeftO = CGPoint(x: 0, y: frame.height)
        let bottomLeftI = CGPoint(x: width, y: frame.height - width)

        let bottomRightO = CGPoint(x: frame.width, y: frame.height)
        let bottomRightI = CGPoint(x: frame.width - width, y: frame.height - width)

        // Top
        let topPoints = [topLeftO, topLeftI, topRightI, topRightO, topLeftO]
        let topGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 1)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: topPoints), color: color, gradientPoints: topGradientPoints))

        // Left
        let leftPoints = [topLeftO, topLeftI, bottomLeftI, bottomLeftO, topLeftO]
        let leftGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: leftPoints), color: color, gradientPoints: leftGradientPoints))

        // Right
        let rightPoints = [topRightO, topRightI, bottomRightI, bottomRightO, topRightO]
        let rightGradientPoints = [CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: rightPoints), color: color, gradientPoints: rightGradientPoints))

        // Bottom
        let bottomPoints = [bottomLeftO, bottomLeftI, bottomRightI, bottomRightO, bottomLeftO]
        let bottomGradientPoints = [CGPoint(x: 0, y: 1), CGPoint(x: 0, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: bottomPoints), color: color, gradientPoints: bottomGradientPoints))
    }

    func addClosedPathForPoints(points: [CGPoint]) -> UIBezierPath? {
        guard points.count == 5 else { return nil }

        let path = UIBezierPath()
        path.move(to: points[0])

        path.addLine(to: points[1])
        path.addLine(to: points[2])
        path.addLine(to: points[3])
        path.addLine(to: points[4])

        path.close()

        return path
    }

    func addGradientToBeizerPath(path: UIBezierPath?, color: UIColor, gradientPoints: [CGPoint]) -> CAGradientLayer {
        guard let path = path, gradientPoints.count == 2 else { return CAGradientLayer() }

        let gradient = CAGradientLayer()
        gradient.frame = path.bounds
        gradient.bounds = path.bounds // This fixes the code.
        gradient.colors = [color.cgColor, UIColor.white.cgColor]
        gradient.startPoint = gradientPoints[0]
        gradient.endPoint = gradientPoints[1]

        let shapeMask = CAShapeLayer()
        shapeMask.path = path.cgPath
        gradient.mask = shapeMask

        self.layer.insertSublayer(gradient, at: 0)

        return gradient
    }
}


texts:
I'm little frustrated because I don't know how well I can refactor this script. I wrote the authentication function but it's too complicated, maybe too large in one function, and seems like spaghetti code. How will I be able to make this a little better?

I'm using Restify framework for NodeJS. There are a function that checks if a user is logged. There is a session hash (pnp_access_token) that I need check with another webservice, but I don't need check all times, only the first, so I'm using a cache. I'm using Redis to set a cache and only check the first time.

I don't want refactor business rules.  What can be done about this?

"use strict";
var errorResponse = require('../errorResponse'),
    paynopain = require('../../core/paynopain'),
    User = require('../../core/User'),
    cache = require('../../core/cache/cache'),
    validateValues = require('../validateValues'),
    API_PATH = 'v1/';

function authenticate(req, res, next) {

    if (req.url.indexOf(API_PATH) == 0){

        var pnpUserId;
        var validated = validateValues(req, ['pnp_access_token']);
        if(validated.error){
            return next(validated.error);
        }
        var pnpAccessToken = req.params.pnp_access_token;

        cache.read('pnpToken:' + pnpAccessToken)
            .then(function(userId){
                if(userId){
                    storeUserIdInRequest(req, next, userId);
                }else{
                    var user = new User(req.logger);
                    return paynopain.getIdFromAccessToken(pnpAccessToken)
                        .then(function(pnpUserIdResult){
                            pnpUserId = pnpUserIdResult;
                            return user.findByPnpID(pnpUserIdResult);
                        })
                        .then(function(userData){

                            if(userData._id){
                                return storeUserIdInRequest(req, next, userData._id.toString());
                            }else{
                                var newUser = {
                                    pnpId: pnpUserId,
                                    radius: 1000
                                };
                                return user.create(newUser)
                                    .then(function(userData){
                                        return storeUserIdInRequest(req, next, userData._id);
                                    });
                            }

                        });
                }
            })
            .fail(function(e){

                if(e.message === 'invalid_grant'){
                    next(errorResponse.unauthorized());
                }else{
                    req.logger.log('error', 'Error authenticating', {
                        error: {
                            message: e.message,
                            stack: e.stack
                        }
                    });
                    next(errorResponse.internalError());
                }

            });

    }else{
        next();
    }

}

function storeUserIdInRequest(req, next, userId){

    var oneHourInSeconds =  60 * 60;
    cache.write('pnpToken:' + req.params.pnp_access_token, userId, {
        expire: oneHourInSeconds
    })
        .then(function(){
            req.userId = userId;
            req.logger.setExtra({
                userId: userId
            });
            next();
        });

}

function init(server){
    server.use(authenticate);
    require('./configuration/routes')(API_PATH, server);
    require('./products/routes')(API_PATH, server);
    require('./tracking/routes')(API_PATH, server);
    require('./lists/routes')(API_PATH, server);
}
module.exports = init;


texts: Checking that a string matches one regex and doesn't match another

texts:
I'm using pylint and flake8 to control the code quality. However I am in check-mate position, where styling one does not suit the pylint or flake8:

if (not re.search(regexp, summary) and
    not re.search(regexp2, summary)):
    return False

Output from flake8:

visually indented line with same indent as next logical line [E129]

Moving return is not helping, the previous error still occurs and there is new one thrown by pylint:

if (not re.search(regexp, summary) and
    not re.search(regexp2, summary)):
        return False

Output from pylint:

[bad-indentation] Bad indentation. Found 8 spaces, expected 4


texts: Group list items into pages, rows and columns

texts:
I have a list of labels for printing. Now I have go over the list and print the labels. The layout is specified by how many labels per page and per row on a page I can print.

@{
    var labels = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
    var labelsPerPage = 10;
    var labelsPerRow = 2;
    var labelCount = labels.Count;
}

@for (var i = 0; i < labelCount; i++) {
    if (i % labelsPerPage == 0) {
        @Html.Raw("
")
    }

    if (i % labelsPerRow == 0) {
        @Html.Raw("
")
    }

    @PrintLabel(labels[i])

    if (i % labelsPerRow == (labelsPerRow - 1)) {
        @Html.Raw("
")
    }

    if (i % labelsPerPage == (labelsPerPage - 1)) {
        @Html.Raw("
")
    }
}

@helper PrintLabel(int label) {
    @label
}

Is there a better method (eg. using LINQ or nested for/foreach loops) for going through the list and doing something at the start and end of each page and each row?

I would prefer a nested structure to a flat one so it can be used inside a Razor template. The flat version fails here because Razor requires HTML tags to be closed at the end of a code block.

I'm not looking for performance here, I'd rather have more readable code and possibly getting rid of any Html.Raw() calls.


texts:
I'm making a CLI app for myself for tracking my budget. How can I improve this code?

#!/usr/bin/python3

def t_lines():
    import os
    terminal_size = os.get_terminal_size()
    print("-" * terminal_size.columns)

def main():
    import sqlite3 as sql

    conn = sql.connect("expenses.db")
    cur = conn.cursor()

    cur.execute("CREATE TABLE IF NOT EXISTS expenses \
            (Date TEXT DEFAULT \"x\", \
            item TEXT DEFAULT \"x\", \
            category TEXT DEFAULT \"x\", \
            Price REAL DEFAULT 0, \
            Type TEXT DEFAULT \"e\")" )

    t_lines()

    print("Enter in the following format")

    print("Enter 0 to quit")

    print("Date (dd/mmm/yy), Item, Category, Price, Type ([e]xpense/[i]ncome)")

    print("Example:")
    print("12/nov/18, carrot, vegetable, 15.64, e")
    print("13/aug/18, salary, work, 10000, income")

    t_lines()

    user_input = input()
    # the vals below seems unnecessary
    # vals = user_input.split(',')

    while user_input != "0":
        vals = user_input.split(',')

        if len(vals) != 5:
            print("Enter correctly")
        else:
            cur.execute("INSERT INTO expenses \
                VALUES (?, ?, ?, ?, ?)", vals)
            conn.commit()
            user_input = input()

    conn.close()

if __name__ == '__main__':
    main()


texts: Better way to code this code snippet (copy paste)

texts:
I am trying to improve upon a VBA code created through recording a macro. Can the code below be optimized (I was informed to avoid .Select as much as possible)? The code itself works fine for me though.
    Sheets("DataExport").Select
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.ClearContents

    Sheets("Analysis").Select
    Range("BX1:CI4").Select
    Selection.Copy
    Sheets("DataExport").Select
    Range("B1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False


texts:
I have created a method which shows log in logcat and also writes into the file. Every time this method is called it appends String in file. There are so many read/write operations on disk/non-volatile storage/SD card happening. I want to batch these operations so that minimum SD card read/write happens and i do not miss any log info.
   I have a idea to store logs in static StringBuilder variable and check if its length>200000 then write to file otherwise append it in variable. Will that work perfectly, how other developer handle this task?

public static void log(String tag, String s, @ErrorType int error) {
    Log.d(tag, s);
    if (MyApplication.sExternalStorageDirectory == null) {
        new NullPointerException("sExternalStorageDirectory is null")
                .printStackTrace();
        return;
    }
    String fileName = "logs";
    String fileExtension = ".txt";
    if (error == ErrorType.WEBSERVICE_RESPONSE_ERROR) {
        fileName = "web_api_error_log";
    } else if (error == ErrorType.CLIENT_SIDE_ERROR) {
        fileName = "client_log";
    }
    File f = new File(MyApplication.sExternalStorageDirectory, fileName + fileExtension);
    try {
        if (!f.exists()) {
            f.createNewFile();
        }
        BufferedWriter bfw = new BufferedWriter(new FileWriter(f, true));
        bfw.append(tag + "->" + s);
        bfw.newLine();
        bfw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


texts: Append a incrementing number to a slug username

texts:
Im using Laravel 5.4 and I'm using a slug to look-up users in database.

Im adding first_name and last_name to the slug, and if there is a user with the same name, appending a number (increment it if there is more than one with same name) to the end ex John.doe.3.

This is what I have in RegisterController.php

protected function create(array $data)
    {
        // Set the may be name
        $maybe_slug = strtolower($data['first_name'] . '.' . $data['last_name']);

        // Check if there is another one in the DB with the same name
        $user = User::where('slug', 'like', $maybe_slug . '%')->orderBy('created_at', 'desc')->first();

        if($user){
            $split_user_name = explode('.', $user->slug);
            $number = isset($split_user_name[2]) ? $split_user_name[2] : null;
            if(isset($number)){
                $slug = $maybe_slug . '.' . ($number + 1);
            }elseif($user->slug == $maybe_slug){
                $slug = $maybe_slug . '.2';
            }
        }else{
                $slug = $maybe_slug;
        }
        return User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'slug' => $slug,
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

This is how RegisterController looks like un-edited (GitHub)

Can I do this in a better way?


texts:
I am trying to plot heatmap with three variables x, y and z, each with vector length of 932826. The time taken with the function below is 28 seconds, with a bin size of 10 on each x and y. I have been using another program where the same plot happens in 6 - 7 seconds. Also, I know that the plot function of that program uses Python in the background
When debugging I see that the maximum time consumed is while using the griddata function. So, I was wondering if there are any alternatives that I can use instead of griddata to make the interpolation quicker
In future I will be handling even bigger data (8 to 10 times the size of current one), so I am in need to finding something robust, which handles all the data, without going into memory overflow
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.interpolate import griddata
import os

arr_len = 932826
x = np.random.uniform(low=0, high=4496, size=arr_len)
y = np.random.uniform(low=-74, high=492, size=arr_len)
z = np.random.uniform(low=-30, high=97, size=arr_len)

x_linspace = 10
y_linspace = 10
x_lab = 'x_label'
y_lab = 'y_label'
title = 'some title'
plot_name = 'example plot'

xi = np.linspace(min(x), max(x), x_linspace)
yi = np.linspace(min(y), max(y), y_linspace)
start = time.time()
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='linear')
print('Time elapsed = ', time.time()-start)


texts:
What do you consider the readability of this program?
Do you think it's easy to understand what the variables and functions do just by reading their names?
Would you prefer more, less, or this amount of comments?
Do the comments make it easier or harder for you to understand the program?
Do you like a program to have comments (in general)?

# This program generates prime numbers

# Introduces user
def welcome():
    print("""
         Welcome to the prime number generator!

         This program genarates all prime numbers starting from zero
         to an upper limit. You´ll decide the upper limit.

         Have fun :)
         """)

# User inputs a natural number that will be the upper limit for checking primenumbers
def limit(question):
    while True:
        try:
            limit = int(input(question))
        except:
            limit = ""
        if limit:
            return limit
            break

# Checks if the number is a prime number. If it is, the number will be returned. If it is not, then None will be returned
def is_it_prime(current_number, prime_number):
    y = 0
    while True:
        ratio = current_number / prime_number[y]
        y += 1
        if ratio == int(ratio):
            break
        if y == len(prime_number):
            return current_number

# Adds prime number to list
def ad_prime(prime_number, it_is_prime):
    a = len(prime_number)
    prime_temp = (a+1)*[None]
    for i in range(a):
        prime_temp[i] = prime_number[i]
        if i+1 == a:
            prime_temp[i+1] = it_is_prime
    return prime_temp

# Main program
upper_limit_question = "Type the upper limit and press enter. It has to be a natural number expressed in digits: "
lower_limit = 2
prime_number = [2]
welcome()
upper_limit = limit(upper_limit_question)
while lower_limit < upper_limit:
    lower_limit +=1
    it_is_prime = is_it_prime(lower_limit, prime_number)
    if it_is_prime != None:
        prime_number = ad_prime(prime_number, it_is_prime)
print("\n" +str(prime_number), "\n\nThanks for generating prime numbers :)")


texts: CSV lookup problem solved with CoffeeScript

texts:
Source code with some test:

assert = require('assert')

compile_csv_search = (text, lookupKey)->
    [header, body...]= text.split('\n').filter(Boolean).map((el)->
        el.split(',')
    )
    col = header.indexOf(lookupKey)
    assert(col isnt -1)
    lookupIndex = body.reduce(
        (acc, row, i)->
            cell = row[col]
            acc[cell] = i
            return acc
        {}
    )
    return (lookupName)->
        rowNum = lookupIndex[lookupName]
        return body[rowNum].reduce(
            (acc, el, i)->
                acc[header[i]] = el
                return acc
            {}
        ) if rowNum?

# test one
(()->
    csvText = "ip,name,desc\n"+
        "10.49.1.4,server1,Main Server\n"+
        "10.52.5.1,server2,Backup Server\n"
    csv_by_name = compile_csv_search(
        csvText
        "name"
    )

    assert.deepEqual(
        csv_by_name("server2")
        {ip: "10.52.5.1", name: "server2", desc: "Backup Server"}
    )
    assert not csv_by_name("server9")?
)()

I think it is pretty descriptive.


texts: Highlighting partitions in distinct color

texts:
Given:

G is an arbitrary graph
partitions is a list of its edges divided into (in this case) 3 sets.

Color generation:

Its purpose is to generate one distinct color for each partition.
The function turns a number between 0 and 1 into an RGB color.
For the given example, with 3 partitions, it would be called with 1/3, 2/3, and 1, and return a list of codes for green, blue, and red.
For other numbers it would be used to spread the different colors as widely as possible.
Visually, think of a circle with R, G, and B equally spaced around it.
The number is the fraction of the way around the circle from R to pick the color, so if the number is .4, the color would be between G and B, closer to the G.

Color assignment:

For each set in the partition, a different color is generated and assigned to a list of colors.
In this case edge_color_list would be 9 greens, 4 blues, and 2 reds.
The actual list is:
[(0, 1.0, 0.0), (0.0, 0, 1.0), (0.0, 0, 1.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0.0, 0, 1.0), (0, 1.0, 0.0), (1.0, 0, 0.0), (1.0, 0, 0.0), (0.0, 0, 1.0)]

Problem:
The top and bottom sections can't really be changed, but the def_color() function and edge_color_list sections each look like they were written in C, and I think they could be done more elegantly.
It's obvious how I was thinking while writing it (i.e. how I would write it in C), but I'd like to know how python coders think.
I'm having trouble writing python without a heavy C accent (I wrote C for decades).
I understand the python language fairly well (or know how to recognize what I don't know and how to look it up).
And I've reached the stage where what I've written feels wrong.
But I still don't seem to think in native python:
#!/usr/bin/env python3
import matplotlib.pyplot as plot
import networkx as nx

G = nx.petersen_graph()
partitions = [{0, 3, 4, 5, 6, 7, 8, 9, 11}, {1, 2, 10, 14}, {12, 13}]

def get_color(fraction):
    if fraction < 1/3:
        color = (1-3*fraction, 3*fraction, 0)
    elif fraction < 2/3:
        fraction -= 1/3
        color = (0, 1-3*fraction, 3*fraction)
    else:
        fraction -= 2/3
        color = (3*fraction, 0, 1-3*fraction)
    return color

edge_color_list = [None] * len(G.edges())
for i in range(len(partitions)):
    items = list(partitions[i])   # convert from set
    for j in range(len(items)):
        edge_color_list[items[j]] = get_color((i+1)/len(partitions))

nx.draw(G, with_labels=True, pos=nx.circular_layout(G), width=2,
        node_color='pink', edge_color=edge_color_list)
plot.show()

Any suggestions about how I could have thought differently while writing the above would be appreciated.


texts: How can this functional implementation of Kadane's algorithm be improved?

texts:
Some time ago I posted on Stack Overflow an imperative C# implementation of Kadane's algorithm for finding a subarray with maximum sum. Then I considered implementing the same functionally in F# and came up with the following:

let kadanes (xs: int []) =
    xs
    |> Array.mapi (fun i x -> (x, i))
    |> Array.fold (fun (partSum, partIdx, maxSum, startIdx, endIdx) (x, i) ->
                        let newPartSum, newPartIdx =
                            if partSum + x > x then (partSum + x, partIdx) else (x, i)
                        if newPartSum > maxSum then
                            (newPartSum, newPartIdx, newPartSum, newPartIdx, i)
                        else (newPartSum, newPartIdx, maxSum, startIdx, endIdx))
                        (0,0,xs.[0],0,0)
    |> fun (_, _, maxSum, startIdx, endIdx) -> (maxSum, startIdx, endIdx)

While the implementation above is functional and correct I cannot consider it easily understandable; in particular, dragging tuple of 5 elements through the fold seems rather ugly.

What can be done for improving this F# code?

Thank you.


texts: Given a list of integers, write a function that returns the largest sum of non-adjacent numbers? Numbers can be 0 or negative

texts:
Given a list of integers, write a function that returns the largest
  sum of non-adjacent numbers. Numbers can be 0 or negative.

  For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and
  5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.

  Follow-up: Can you do this in O(N) time and constant space?

class DailyCodingProblem9 {

    public static void main(String args[]) {

        int arr[] = { 2, 4, 6, 2, 5, 13 };
        int res = solution(arr);
        System.out.println(res);

        int arr1[] = { 1, 0, 3, 9, 2, 14 };
        res = solution(arr1);
        System.out.println(res);
    }

    static int solution(int[] arr) {
        int n = arr.length;
        int[] maxArr = new int[n];
        int max = 0;
        for (int i = n - 1; i > 0; i--) {
            maxArr[i] = findLargestSum(arr, i, n, maxArr);
            max = Math.max(max, maxArr[i]);
        }
        return max;

    }

    static int findLargestSum(int[] arr, int i, int n, int[] max) {
        System.out.println(i);
        if (max[i] != 0) {
            return max[i];
        }
        if (i == 0 || i == 1) {
            return arr[i];
        }
        if (i - 2 == 0) {
            return arr[i] + findLargestSum(arr, i - 2, n, max);
        }
        return arr[i] + Integer.max(findLargestSum(arr, i - 2, n, max), findLargestSum(arr, i - 3, n, max));

    }

}

How do I solve it in constant space? I found an answer here, but could not understand the logic.


texts:
So I've picked up PyYAML over the past few days but I feel like some of the documentation is vague or I'm misinterpreting it. Here is a function for writing data to a .yaml which can write the values to each element I have in the list:

def writeSave(filename, **kwargs):
    with open(filename, 'r') as yamlFile:
        yamlDict = yaml.load(yamlFile)
        if not yamlDict: yamlDict = {}

    with open(filename, 'w') as write:
        z = yamlDict.copy()
        z.update(kwargs)
        yaml.dump(z, write)

Which will then overwrite the values below when called:

saveData:
        {mission_state: 7, playername: 'steve'}

Using this function seems simple:

writeSave('../path/savedata.yaml', mission_state=2)

Which will then change the mission_state in the list.

I don't know if I've done this smoothly or if there is a better practice to performing these kind of functions. If there are, it'd be nice to have some kind of pointers.

Is there a way to make this more readable? Maybe more readable vars or more commenting?


texts:
I'm a beginner and it is my first project in Python 2.7.

My goal is writing a script that I can run with two or three arguments.
If run with two arguments like python currency.py RUB USD then the output will be current RUB rate by USD base: .015169.
If run with three arguments like python currency.py 1000 RUB USD then it will convert 1000 RUB to dollar.

#!/usr/bin/env python
import ast, requests
import sys, argparse
def checker(base, symbol):
    url = "http://api.fixer.io/latest?base=%s" % base.upper()
    r = requests.get(url)
    content = ast.literal_eval(r.content)
    rate = content["rates"][symbol.upper()]
    return rate
parser = argparse.ArgumentParser(description = "Currency converter. For instance : 'Convert 100 USD to RUB' Will be: 100 USD RUB. If You need only rate: USD RUB")
if len(sys.argv) > 3:
    parser.add_argument("n", type =int, help = "Amount of currency_for_convert", default=1)
parser.add_argument('currency_for_convert', type=str, help="Currency for convert")
parser.add_argument("currency_converted_to", type=str, help = "Currency that converted to")
args = parser.parse_args()
rate = checker(args.currency_for_convert, args.currency_converted_to)
print rate if len(sys.argv) <= 3 else rate*args.n

But I don't like the way I'm using if statements because the running script help ignore third argument and give information only about first two arguments.

  $ python currency.py --help usage: currency.py [-h]
  currency_for_convert currency_converted_to

  Currency converter. For instance : 'Convert 100 USD to RUB' Will be:
  100 USD RUB. If You need only rate: USD RUB

  positional arguments:   currency_for_convert   Currency for convert
  currency_converted_to  Currency that converted to

  optional arguments:   -h, --help            show this help message and
  exit

Is there another way to write two/tree arguments script?


texts: Controller in an ASP.NET Web API application which generates a CSV file

texts:
I have a controller in an ASP.NET Web API application which generates a CSV file. The controller looks like this:

[System.Web.Http.HttpGet]
public HttpResponseMessage Download(int? id = null)
{
    if ( !id.HasValue)
        return new HttpResponseMessage(HttpStatusCode.NotFound);

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(new MemoryStream(_personService
        .ExportPersonsToCSV().Content));
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new
        ContentDispositionHeaderValue("attachment") {
            FileName = _personService.ExportPersonsToCSV().FileName };
    return result;
}

And method ExportPersonsToCSV() of PersonService class:

public FileDTO ExportPersonsToCSV()
{
    //...
    var dto = new FileDTO()
    {
        FileName = $"Persons {DateTime.Now}.csv",
        MediaTypeHeaderValue = Globals.MEDIA_TYPE_HEADER_VALUE,
        Content = _csvExport.WriteCSV(personDeps, columnNames)
    };
    return dto;
}

And CSVExport class looks like this:

public class CSVExport : ICSVExport
{
    /// <summary>
    /// Converting content of MemoryStream into byte array
    /// </summary>
    public byte[] WriteCSV<T>(IEnumerable<T> objectlist
        , IEnumerable<string> columnNames = null)
    {
        byte[] bytes = null;
        using (var memStream = new MemoryStream())
        using (var sw = new StreamWriter(memStream, Encoding.GetEncoding("Windows-1251")))
        {
            sw.WriteLine("sep=,");
            foreach (var line in ToCsv(objectlist, columnNames))
            {
                sw.WriteLine(line);
            }
            sw.Flush();
            memStream.Seek(0, SeekOrigin.Begin);
            bytes = memStream.ToArray();
        }
        return bytes;
    }

    private IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist,
         IEnumerable<string> columnNames = null, string separator = ",",
         bool header = true)
    {
        //... code omitted for the brevity
        yield return string.Join(separator, fields
                    .ToArray());
    }
}

Recently, I've thought whether a method public byte[] WriteCSV<T>(...) is a violation of Single Responsibility Principle?

My thought it is ok to place here:

It is appropriate place to put a logic of converting csv file into byte array cause a method public byte[] WriteCSV<T>(...) placed into a class CSVExport

My thoughts it is NOT ok to place here:

What is MemoryStream class doing here? It is a class of ExportCSV and nothing more!
It is possible to extract dependency(MemoryStream) into separate class like and use it into CSVExport:
IMemoryStream{ byte[] WriteCSV(IEnumerable objects);}

So is a method public byte[] WriteCSV<T>(...) placed into CSVExport a violation of Single Responsibility Principle?
Any other criticism are welcome.


texts: Maintaining the Single Responsibility Principle with Project Euler #2

texts:
This is my solution to Project Euler problem 2:

  By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

The class fibonacci_Even_Sum_Calculator does two things:

calculate the sum of the even-valued Fibonacci numbers
cache the results in a dictionary

Is this a sign that this code violates the Single Responsibility Principle?

class fibonacci_Even_Sum_Calculator:

        def __init__(self):
                self.cached_result = dict()

        def F(self, n):

                if n == 0:
                        return 0
                elif n == 1:
                        return 1
                else:
                        if(self.cached_result.has_key(n)):
                                return self.cached_result[n]
                        else:
                                result = self.F(n-1) + self.F(n-2)
                                self.cached_result[n] = result
                                return result

        def is_even(self, number):
                return number % 2 == 0

        def get_result(self,limit_value):

                sequence = 2
                sum = 0

                while True:

                        result = self.F(sequence)

                        if result > limit_value:
                                break

                        if self.is_even(result) :
                                sum = sum + result

                        sequence = sequence + 1

                return sum

fibonacci_calculator = fibonacci_Even_Sum_Calculator()
result = fibonacci_calculator.get_result(4000000)
print result


texts: Show the results of linked list operations in sequence

texts:
I'm working on a basic linked list programs. In this program I can insert elements at the beginning, at the middle (after one specific element) of the list and at the end. I also can delete a specific element or delete an element from the end of the list. I have all these four methods in the code.

Now I was trying in the main method to perform this operations in sequence:

insert at the beginning
insert at the middle
delete a specific element
delete an element from the list.

First I want to add 10 elements at the beginning of the list {50, 70, 80, 100, 77, 200, 44, 70, 6, 0}. Then I want to add 10 elements at the middle { 5, 20, 10 ,30 ,7 , 8, 2, 104, 1, 22} after the element 200. Then I want to add 10 elements at the end {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2}. Then I want to delete a specific element 76 and then delete two elements at the end of the list.

So, I want the final list as {0, 6, 70, 44, 200, 22, 1, 104, 2, 8, 7, 30, 10, 20, 5, 77, 100, 80, 70, 50, 40, 30, 20, 1, 7, 4, 0}.

I don't know if it's  a good way. Do you think the code in the main method is OK, the for parts particularly?

Main method:

int main()
{
    printf("hi");
    int i=0;
    int listsize=10;
    int arrBegining[] = {50,70, 80, 100, 77, 200, 44, 70, 6, 0};
    int arrMiddle[] = {5, 20, 10, 30, 7, 8, 2, 104, 1, 22};
    int arrEnd[] = {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2};

    for(i=0;i<listsize;i++){
            insert_at_begning(arrBegining[i]);
        }

    for(i=0;i<listsize;i++){
        insert_at_middle(arrMiddle[i], 200);
    }
    for(i=0;i<listsize;i++){
        insert_at_end(arrEnd[i]);
    }

    for(i=0;i<listsize;i++){
        delete_from_middle(76);
    }

    for(i=0;i<2;i++){
        delete_from_end();
    }
 }

List operations:

void insert_at_begning(int value)
{
    var=(struct node *)malloc(sizeof (struct node));
    var->data=value;
    if(head==NULL)
    {
        head=var;
        head->next=NULL;
    }
    else
    {
        var->next=head;
        head=var;
    }
}

void insert_at_middle(int value, int loc)
{
    struct node *var2,*temp;
    var=(struct node *)malloc(sizeof (struct node));
    var->data=value;
    temp=head;

    if(head==NULL)
    {
        head=var;
        head->next=NULL;
    }
    else
    {
        while(temp->data!=loc)
        {
            temp=temp->next;
        }
        var2=temp->next;
        temp->next=var;
        var->next=var2;
    }
}

int delete_from_middle(int value)
{
    struct node *temp,*var;
    temp=head;
    while(temp!=NULL)
    {
        if(temp->data == value)
        {
            if(temp==head)
            {
                head=temp->next;
                free(temp);
                return 0;
            }
            else
            {
                var->next=temp->next;
                free(temp);
                return 0;
            }
        }
        else
        {
            var=temp;
            temp=temp->next;
        }
    }
    printf("data deleted from list is %d",value);
}

int delete_from_end()
{
    struct node *temp;
    temp=head;
    while(temp->next != NULL)
    {
        var=temp;
        temp=temp->next;
    }
    if(temp ==head)
    {
        head=temp->next;
        free(temp);
        return 0;
    }
    printf("data deleted from list is %d",temp->data);
    var->next=NULL;
    free(temp);
    return 0;
}


texts: Local Storage accessor and modifier helper

texts:
I have created a module/factory/directive for AngularJS which allows to save user input to localStorage and restore it if needed.

Although it works quite good, I am sure that I could improve its code base and am looking for advice to do so.

It can be found on github: https://github.com/sprottenwels/saintAnthony.js

Code :

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

saintAnthony.directive('savior',function(blackbox){
return{
    restrict: 'A',
    scope: true,
    link: function(scope,element,attrs){

        var elementData = {};

        var _getElementData = function(el){
            var data = {};
            var dotIndex = 0;

            el = el.isString ? el : el.toString();
            dotIndex = el.indexOf('.');

            data.container = attrs.savior !== "" ? attrs.savior : false;
            data.index = attrs.saviorindex !== undefined ? parseInt(attrs.saviorindex) : 0 ;
            data.mainGroup = dotIndex !== -1 ? el.substr(0,dotIndex) : el;
            data.key = el.substr(dotIndex +1,el.length);
            data.value = element[0].value;

            return data;
        };

        scope.saveSingleElement = function(){

            var obj = {};

            if (!blackbox.hasGroup(elementData.mainGroup)){
                blackbox.addGroup(elementData.mainGroup);
            }

            obj[elementData.key] = elementData.value;
            blackbox.updateGroup(elementData.mainGroup,obj);

        };

        scope.saveRepeatedElement = function(){
            var obj = {};

            if (!blackbox.hasGroup(elementData.container)){
                blackbox.addGroup(elementData.container,true);
            }

            obj[elementData.key] = elementData.value;
            blackbox.updateRepeatGroup(elementData.container,obj,elementData.index);
            console.dir(blackbox.groups);
        };

        element.bind('input',function(){

            elementData = _getElementData(attrs.ngModel);

            scope.$apply(function(){

                if(!elementData.container){scope.saveSingleElement();}
                else{scope.saveRepeatedElement();}

            });
        });

    }
}
});


texts:
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:

Score  | Grade
-------+------
>= 0.9 | A
>= 0.8 | B
>= 0.7 | C
>= 0.6 | D
 < 0.6 | F

If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.

try:
    inp = raw_input("Enter a number between 0.0 and 1.0: ")
    score = float(inp)
    if (score >= 1.0):
        print("You didn't follow instructions")
        exit()
    elif (score >= 0.9):
        print("A")
    elif (score >= 0.8):
        print("B")
    elif (score >= 0.7):
        print("C")
    elif (score >= 0.6):
        print("D")
    else:
        print("F")
except:
    print("Please enter numerical numbers")
    exit()


texts:
I'm looking for a better way of doing this code I made. I work for tech support and one of the biggest questions I am asked is: "Hey, how did my disk get so full in my VPS?"

I am aiming for output like:

home/ is taking up xGB
home/user1 xgb
home/user2 xgb

and so on. So far I have this, which does alright, but I am looking for a prettier way of getting this done.

#!/bin/bash
for i in $(ls -d */ |  grep -v proc);
 do
printf "**** $i has the following breakdown ********\n"

du -h --max-depth=1 $i
done


texts:
The intro

Yesterday I learned of the existence of Befunge. See my (sort of) related question about a Befunge interpreter in Python. And it made me want to learn the language, and what do programmers do when they learn a new language? They make a FizzBuzz of course!

The following program prints all FizzBuzz's from 1 until 100. I don't think this implementation is the best, since I repeat quite a lot of code and there are many empty fields in my program.

You can check it with an online interpreter:

befunge_online_1 or befunge_online_2

The explanation

Read "!zzuBzziF" to stack
>:#,_ While loop to print stack untill stack is empty
Go down at the end of the line with v
Then it prints a newline ,*52,*84<
+1 Add 1 to top of the stack
: copy top of stack (current fizzbuz number)
*5*2*25 push 100 to stack
go down v and go right >
`| Checks if current fizzbuz number is bigger than 100

if bigger @ end program
if not bigger go down

>:3% copy stack and modulus with 3
Check modulo |

if modulo 3 == 0 print Fizz >"zziF",,,, and add 1 on top of the stack
if not modulo 3 == 0 add 0 to top of the stack

go down v and swap top of stack \ so top op stack is current fizzbuzz number again
%5:< copy stack and modulus with 5
Check modulo |

if modulo 5 == 0 print Buzz ,,,,"Buzz"< swap stack \ and add 1 on top of it
if not modulo 5 == 0 swap stack \ and add 0 on top of it

go down v and go right >
Check if there was a Buzz with |

if there was a Buzz burn top of the stack with $ go to step 18
if there was no Buzz go down

Check if there was a Fizz with |

if there was a Fizz do nothing
if there was no Fizz copy and print the current number :.

go up and ^ and skip following with #
go right > and go up ^ and go to step 4

The code

"!zzuBzziF">:#,_   v
v*2*5*52:+1,*52,*84<
  >@             > ^
>`|   >            v
  >:3%|            0
      >"zziF",,,, 1v
 v\            <   \
 0             |%5:<
 v1\ ,,,,"Buzz"< #
   >$            ^
 > |>            ^
   >|
    >:.          ^

The output

FizzBuzz!
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...
98
Fizz
Buzz

The question

As stated above, I really don't think my implementation is the best, and am curious how other people would solve this problem.

My current doubts about the code:

I repeat code, for example prints. Can they be reworked into functions?
It feels quite large. Can this be condensed?
Readability of the code. Do other people understand the steps I've taken?

I therefore invite you all to burn it down!