Array Dynamic resize in heap I have answered a Question in Stackoverflow link.

  a) Create a function called resize that can be used to increase the
  size of integer arrays dynamically. The function takes three
  parameters. The first parameter is the original array, the second
  parameter is the size of this array, and the third parameter is the
  size of the larger array to be created by this function. Make sure
  that you allocate memory from the heap inside this function. After
  allocating memory for the second array the function must copy the
  elements from the first array into the larger array. Finally, the
  function must return a pointer to the new array.

  b. In main, allocate an array on the heap that is just large enough to
  store the integers 5, 7, 3, and 1.

  c. Resize the array to store 10 integers by calling the resize
  function created in step a. Remove the old (smaller) array from the
  heap. Add the numbers 4, 2, and 8 to the end of the new array.

  d. Write a sort function that sorts any integer array in increasing
  order.

  e. Use the sort function to sort the array of numbers in c above.
  Display the sorted numbers.

Is there a Dangling pointer issue.

#include <array>
#include <iostream>

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

//Bubble Sort
bool sort(int arr[], int size)
{
    for( int i = 0; i< size -1; i++)
    {
        for( int j = 0; j < size - i -1; j++)
        {
            //descending order
            if(arr[j]<arr[j+1])
            {
                swap(&arr[j], &arr[j+1]);
            }
        }
    }
    return true;
}

void Print(int Array[], int nSize)
{
    for( int i = 0; i < nSize; i++)
    {
        std::cout<<" "<<Array[i];
    }
    std::cout<<"\n";
}

void Resize( int *&Array, const int& nSizeOld, const int& nSize )
{
    int * newArray = new int[nSize];

    //Copy Elements of the Array
    for(int i = 0; i< nSize; i++)
    {
        newArray[i] = Array[i];
    }

    delete[] Array;

    //Assign ptr of Prev to new Array
    Array =  newArray;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int kNewSize = 10, kSize = 5;
    int *pMyArray = new int[kSize];

    //Set Values
    for( int i = 0; i< kSize; ++i )
    {
        pMyArray[i] = i * 5;
    }

    Resize( pMyArray, kSize, kNewSize );

    //Set Values
    for( int i = kSize; i< kNewSize; ++i )
    {
        pMyArray[i] = i * 10;
    }

    Print(pMyArray, kNewSize);

    sort(pMyArray, kNewSize);

    Print(pMyArray, kNewSize);

    if( pMyArray!=NULL )
    {
        delete[] pMyArray;
    }

    return 0;
}

If you had tagged this code as C, it would have been acceptable. Since you tagged it as C++, it's horrible.

Instead of writing your own swap function, there's already std::swap in <algorithm>.

Instead of writing bubble sort yourself, just use std::sort, also from <algorithm>.

Instead of using arrays and resizing them yourself, just use std::vector<int>, from <vector>.

After applying these transformations, you cannot have a dangling pointer anymore since your code is completely pointer-free.

As part of an exercise for learning the basic operations on memory management, it's ok to write code like this, but never ever use such code in production. In production the code should look like this:

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

void Print(const std::vector<int> &nums)
{
    for(int num : nums)
    {
        std::cout << " " << num;
    }
    std::cout << "\n";
}

int main()
{
    std::vector<int> nums { 5, 7, 3, 1 };

    // There's probably a more elegant way to add the elements to the vector.
    nums.push_back(4);
    nums.push_back(2);
    nums.push_back(8);

    std::sort(nums.begin(), nums.end());

    Print(nums);
}

By the way, your original code doesn't have any dangling pointer as well. Well done.

You don't need the != NULL check before the delete[] since that pointer cannot be null. In modern C++ (since C++11 I think) you would also write nullptr instead of NULL. The reason is that historically NULL had not been guaranteed to be of pointer type.

Have a look at https://en.cppreference.com/w/cpp/algorithm for more algorithms that you shouldn't implement yourself in C++.

I would have liked to write the push_back block in a shorter way, as well as the Print function. I'm sure there's a more elegant way, I just don't know it.


Page Object Model class structure in Selenium I am automating a webform, and this is what I've coded so far. I am curious if you find the code good and readable. But most important to me is to get some feedback for learning purposes.

The remove account page:

public class RemoveAccountsPage extends Page {

    private Boolean accountsToRemove() {
        by = By.className("zero-results-filter");
        return ((elementExists(by)) ? true : false);
    }

    private void selectAllAccounts() {
        by = By.id("accounts-select-all");
        element = waitForPresenceOfElement(by);
        element.click();
    }

    private void clickRemoveButton() {
        by = By.id("account-delete");
        element = waitForPresenceOfElement(by);
        element.click();
    }

    private void confirmRemovingAccounts() {
        by = By.id("confirm");
        element = waitForPresenceOfElement(by);
        element.click();
        //driver.findElement(By.id("NO_DEAL_VIA_MP")).click()
    }

    public void removeAccounts() throws Exception {
        String request = Page.URL + "/hu/accounts/index.html";
        goToWebPage(request);

        Boolean result = accountsToRemove();
        if(result == false) {
            selectAllAccounts();
            clickRemoveButton();
            confirmRemovingAccounts();
        }

        Thread.sleep(1000);
    }
}

Main class:

public class AccountManager {
    public static void main(String args[]) throws Exception {
        Bot bot = new Bot();
        bot.setUp();

        ........

        RemoveAccountsPage removeAccountsPage = new
        RemoveAccountsPage();
        removeAccountsPage.removeAccounts();

        ........

        bot.tearDown();

    }
}

Some lines may be simplified.

1) elementExists() already returns boolean, so use it directly:

return ((elementExists(by)) ? true : false);

to

return elementExists(by);

2) You may inline a method calls into condition statements:

Boolean result = accountsToRemove();
if(result == false) {

to

if(!accountsToRemove()) {

3) Name the main test method correspondingly:

removeAccounts()

to

testRemovingAllAccounts()
userRemovesAllAccounts()


Security of a custom table in JsGrid This is my old topic,it is about show table's records by JavaScript using a JsGrid file and can edit or delete by ajax.

This is my topic How can I load rows in JsGrid table that got from php file?,
The problem I am not sure the data is secure during inserting and loading or not?

Is it really secure?

The names of PHP files are: newsConf, controll and getnewscat

HTML file: basic.html

in controll.php:

public function newsConfig(){ $this->CONN = new Conn();//class from external page to connect DB try{
    $dfnet = $this->CONN->open_connect();
    $qnco = mysqli_query($dfnet,"select * from category");
    if(!$qnco) return "";
    else{
        while($qncoarray = mysqli_fetch_assoc($qnco)){
            //here I try copy rows into array
            $nnopCo[] = array(
                'ID' => $qncoarray['ID'],
                'Name' => $qncoarray['Name']
            );
        }
        return $nnopCo;
    }
    $this->CONN->close_connect($dfnet); } catch(Exception $er){ }

in getnewscat.php:

<?php require_once "../../bin/controll.php";
$db_controll = new Controll();
$cat_news = new ArrayObject($db_controll->newsConfig());

header('Content-type: application/json');
echo json_encode($cat_news->getArrayCopy());

?>

in basic.html: is the same file from jsgrid demo, but I change the code in JavaScript and canceled the db.js file

    <script>
            $(function() {
                {

                $("#jsGrid").jsGrid({
                    height: "70%",
                    width: "50%",//100%
                    selecting: false,
                    filtering: false,
                    editing: false,
                    sorting: false,
                    paging: true,
                    autoload: true,
                    pageSize: 15,
                    pageButtonCount: 5,
                    controller: {
                        loadData: function(filter) {
return $.ajax({url: "../bin/getnewscat.php",data:filter
                            });

                        }
    },
                    fields: [
                        { name: "ID", type: "number", width: 50 },
                        { name: "Name", type: "text", width: 50},
                        { type: "control", modeSwitchButton: false, deleteButton: false }
                    ]
               });
    $(".config-panel input[type=checkbox]").on("click", function() {
                    var $cb = $(this);
                    $("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
                });

            });
        </script>

In newsConf.php: that file should call basic.html and give the result by using an iframe:

<iframe name="demo" src="jsgrid-1.2.0/demos/basic.html"></iframe>

As far as I can see you are not using user input in your queries so there really isn't any security issue. When using user input in queries always make sure it's through prepared statements.


Find the smallest divisible number for the given input 'n' such that number is evenly divisible by 1 to n Given a number n, the task is to complete the function which returns an integer denoting the smallest number evenly divisible by each number from 1 to n.

I have solved it using the following function:

long long getSmallestDivNum(long long n)
{
   //number should be multiplier of n
    bool found = true;
    int i = 2;
    while(1)
    {
        long long r = n*i;
        found = true;
        for(int j=2;j<=n;j++)
        {
            if( r % j != 0)
            {
                found  = false;
            }
        }
        if(found != true)
        {
            i++;
        }
        else
        {
            return r;
        }
    }
}

But I am getting a time-limit-exceeded-error like this:

  Run Time Error Time Limit of 5 seconds exceeded.

When I execute the code in my local NetBeans, it works fine with a runtime of 62ms.

Your solution to the problem is "check every number to see if it has that property", but that's a lot of numbers. You can do a lot better.

Let me give you a big hint.

Suppose you want find the solution for n == 9. Suppose you had the solution for n == 8 is 840.  Don't worry about how you know that.

Given the fact that 840 is the smallest number that is divisible by 1, 2, 3, 4, 5, 6, 7 and 8, and that 9 is 3 times 3, how do you find a number that is divisible by 1, 2, 3, 4, 5, 6, 7, 8 and 9?  Plainly multiplying 840 by 9 gives a number that is too large, because 9 is already 3 x 3.  We only need to multiply by 3. So the solution for 9 is 2520.

Now suppose we want to find the solution for 10. We already know the solution for 9, and hey, it is already divisible by 10. So we're done.

Now suppose we want to find the solution for 11.  2520 is not divisible by 11, and 11 is prime.  So we have to multiply by 11.

What about 12?  12 is 3 x 4, and we already have a number that is divisible by both 3 and 4, so the solution for 11 is the same as the solution for 12.

And so on.

So is it now clear how to solve this problem efficiently?

UPDATE

Apparently it was not clear.

Think about it this way.

The solution for 2 is 2.
The solution for 3 needs to have a factor of 3, but the solution for 2 has no factor of 3. So the solution for 3 is 2 x 3.
The solution for 4 needs two factors of 2. The solution for 3 has only one factor of 2, so we add an additional factor of two: 2 x 3 x 2.
The solution for 5 needs a factor of 5, but we don't have one in the solution for 4. So 2 x 3 x 2 x 5.
The solution for 6 needs a factor of 2 and a factor of 3. The solution for 5 has a 2 and a 3 already, so 2 x 3 x 2 x 5 works for 6.
The solution for 7 needs a factor of 7, but the solution for 6 doesn't have one.  So 2 x 3 x 2 x 5 x 7.
The solution for 8 needs three factors of 2, but the solution for 7 only has two.  So 2 x 3 x 2 x 5 x 7 x 2.
The solution for 9 needs two factors of 3, but the solution for 8 only has one.  So 2 x 3 x 2 x 5 x 7 x 2 x 3.
The solution for 10 needs a factor of 2 and a factor of 5. The solution for 9 already has those. So 2 x 3 x 2 x 5 x 7 x 2 x 3.
Now do you see the pattern?


std::vector of pointers with the rule of three I have a class that has a std::vector of pointers, I'm NOT going to give any of those pointers to objects outside of it, I mean, I'm not going to share the pointers. - I was reading that isn't everywhere that we will use smart pointers and that raw pointer isn't useless as long that someone is responsible for deleting it. The problem with that class is that it can be inherited and if I don't use the rule of three all the classes that inherits from will have a copy of the vector with the pointers then the destructor of those objects will result in double delete. - Is it safe or I still need to use std::shared_ptr in this case?

class Keeper
{
public:
    Keeper() {}
    Keeper(const Keeper&) = delete;
    Keeper& operator=(const Keeper&) = delete;

    virtual ~Keeper()
    {
        for (int i = 0; i < pointers.size(); ++i)
        {
            delete pointers[i];
        }
    }

    void push_back(Pointer * pointer)
    {
        pointers.push_back(pointer);
    }

    // erase method...
protected:
    std::vector<Pointer *> pointers;
};

Is it safe? To a point.
Naming
I hope the name Pointer is just for illustration purposes as otherwise that is a pretty terrible name.
The changes I would make are:
Accepting pointers must indicate ownership.
Your current interface does not indicate that it is taking ownership of the pointers. So as a user of your class I need to dig inside and find out if you are taking ownership or not before I can use it.
void push_back(Pointer * pointer);

I would change the interface to specifically take a unique_ptr that way people know that you are taking ownership of the object.
void push_back(std::unqiue_ptr<Pointer> pointer);

No confusion here.
Storage of pointers.
I have no problem with you storing a vector of pointers or a vector of smart pointer. Either makes sense. As long as you define the Copy Constructor/ Assignment Operator and Destrtuctor if you use pointer (like you have). You could argue that keeping an array of smart pointers will save you some work in coding (tiny (probably insignificant cost1  of managing the data). Alternatively you can use a container specifically designed to hold pointers.
 std::vector<Pointer*>                 data;  // Add Rule of Three.
 std::vector<std::unique_ptr<Pointer>> data;  //
 boost::ptr_vector<Pointer>            data;  // Takes ownership of pointers.
                                              // Only exposes members as references
                                              // to actual object (not pointer) and thus
                                              // makes using it with standard algorithms
                                              // much easier and intuitive.

To Clarify because of comments: I suspect for most compilers the cost of std::unique_ptr will be zero at runtime. But it is something worth validating with your compiler before assuming.
Access from derived types.
Personally I would not give direct access to the vector from derived class like that.
protected:
      std::vector<Pointer *> pointers;

Even if you have a vector of unique_ptr it is still to easy for the derived class to break encapsulation and do something you don't intend. You should provide them with a safer interface. How you do that depends.
If you know none of the members will be NULL then I would provide them with a function that returns a reference.
 protected:
       // Anybody that wants to access the data gets a reference.
       Pointer&    data(std::size_t index) {return *pointers[index];}

       // Note: the above code just uses the original code as a base line.
       //       If you change the storage medium I would probably still
       //       provide this as an interface layer so that I don't
       //       break encapsulation.
       //
       //       Of course there are a lot of caviats that depend on how
       //       this will be used. But without further context this is
       //       the best I can do at the moment.

 private:
       std::vector<Pointer*> pointers;

If you want derived classes to modify the class you may need to think of something else. But you have not provided enough context for me to go further.
Iterator
Based on comments just showing how easy it would be to throw an iterator together that can be used without exposing implementations details. Note: this one is not complete but shows enough of how it would work (and I was slightly bored at the time and wanted to write some code).
class MyIterator
{
    Keeper* parent;
    int     index
    public:
        MyIterator(Keeper& parent, int index)
           : parent(&parent)
           , index(index)
        {}
        MyIterator& operator++()
        {
            ++index;
            return *this;
        }
        MyIterator operator++(int)
        {
            MyIterator result(*this);
            ++(*this);
            return result;
        }
        Pointer& operator*()
        {
            return parent->data(index);
        }
}


Website register functionality I have two links in my header:

Register
Login

I am not creating it dynamically. If the user clicks on "login," the login form will be visible, similarly for the register form.

My registration:

<?php
 include 'configdb.php';
 global $connection;

 if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password']))
 {
   /*
    *Get Details From User Table To Check Whether User Is Registered Already
    *Used Prepare Statement To Avoid SQL Injection
    */
    if($getUserData = mysqli_prepare($connection,"SELECT emailID FROM users WHERE emailID = ?"))
    {
       mysqli_stmt_bind_param($getUserData,"s",$_POST['email']);
       mysqli_stmt_execute($getUserData);
       mysqli_stmt_store_result($getUserData);/*It Is Required To Get Number Of Rows By stmt_num_rows Method */
      //mysqli_stmt_fetch($getUserData);
    }
    /*
     *Check Whether ResultSet Is Empty
     *If Not Empty, Return This JSON Error Message
     */
    if (mysqli_stmt_num_rows($getUserData) > 0)
    {
     mysqli_stmt_close($getUserData);
     die(
          '{
            "status":"1",
            "message":"Email Already Exists"
           }'
        );
    }
    else
    {
      $email = htmlentities($_POST['email'], ENT_QUOTES, "UTF-8");
      $password = password_hash(htmlentities($_POST['password'], ENT_QUOTES, "UTF-8"), PASSWORD_DEFAULT);
      $com_code = md5(uniqid(rand())); /* It Will Be Used Later For Confirmation-link*/

      if($insertData = mysqli_prepare($connection, "INSERT INTO users (emailID, password, com_code) VALUES(?,?,?)"))
       {
         mysqli_stmt_bind_param($insertData, "sss", $email, $password, $com_code);
         mysqli_stmt_execute($insertData);
         //print_r($insertData); - Handle error by checking num_rows in the object insertdata
       }
       else
       {
          print_r("Prepared statement error");
       }

       //$_SESSION['username'] = $_POST['email'];
       die('{
          "status":"0",
          "message":"Registration Successful"
        }');
    }
 }
?>

My Ajax method

/**
*
* @param form
*
* AJAX METHOD FOR REGISTER
*/
function callAjaxRegisterSubmitMethod(form)
{
  $.ajax({
     type: "POST",
     url: "lib/registration_validate.php",
     data: $("#id_registerForm").serialize(),
     dataType: 'json',
     beforeSend: function()
     {
        $(".cls_register_login_error label, .cls_register_login_error .error_link").text('');
     },
     success: function(response,status,jqXHR)
            {
                //Show homepage
                if(response.status == 1)
                {
                    $(".cls_register_login_error .cls_register_login_error_message").text(response.message+". Try");
                    $(".cls_register_login_error .error_link").text("login");
                    $(".cls_register_login_error .error_link").addClass("enable_login");
                    $(".cls_register_login_error .error_link").removeClass("enable_register");
                    $(".cls_registerForm input[type='password']").val('');
                }
                else if(response.status == 0)
                {
                    console.log("Registered Successfully");
                    alert("Registered Successfully");
                    //$(".body_content").load("",function(){});
                }
                else
                {
                    console.log("Common Success Error Page");
                }
            },
    error:function(jqXHR,status,error)
            {
                console.log("Common Error Page");
            },
    complete:function(response)
            {
            }

 });
}

Please let me know of any problems with this approach.

And I am planning to use load method to load my homepage into contnets div because I have fixed header and footer which is common for all the pages.

htmlentities is used to protect against XSS, and should be used when echoing data, not when inserting it into the database.

Your approach leads to bad data (for example, now you always have to use htmlentities when checking a password, as it will otherwise be wrong), and weak security (using htmlentities before inserting data leads to it not being used when echoing - because it's already been encoded - which leads to data being forgotten, because nobody can remember what was encoded and what was not).

Misc

Functions: I would extract code blocks to functions. It makes those blocks reusable and leads to more readable code. Possible functions are eg getUserByEmail and insertUser.
rename $com_code to $confirmationCode, so it's clear what it is without reading the comments.
always use camelCase or always use snake_case for variables, don't mix this.
uniqid and rand are not good at creating random values. Even though a confirmation token isn't that sensitive, I would still use something like openssl_random_pseudo_bytes instead.
be more consistent with your spacing (eg after ,).
your error handling could be more consistent. Eg sometimes you handle the else case of mysqli_prepare, and sometimes you don't; you never check the result of mysqli_stmt_execute.
It is possible that the user will get the following error message: Prepared statement error [...] Registration Successful.
your comments are mostly not necessary. And those that are - eg the one about confirmation - would not be with better variable names and code extracted to well named functions (which could then have proper PHPDoc type comments). Having too many comments that don't add any new information is not good, because after a while a reader will just ignore all your comments, even the important ones.


Check a string for any occurrences of certain character classes This is a warm-up programming exercise for learning string methods in Python from HackerRank:

  You are given a string S.
  Your task is to find if string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.

  Input Format

  Single line containing, string S.

  Constraints

0 < len(S) < 1000

  Output Format

  In First line, print True if S has alphanumeric character otherwise print False.
  In Second line, print True if S has alphabetical character otherwise print False.
  In Third line, print True if S has digits otherwise print False.
  In Fourth line, print True if S has lowercase character otherwise print False.
  In Fifth line, print True if S has uppcase character otherwise print False.

My working solution is here:

def parse_input():
    string = raw_input()
    return string

def check_string(string):
    check_funs = [str.isalnum,
                  str.isalpha,
                  str.isdigit,
                  str.islower,
                  str.isupper,
                  ]
    return [any(fun(char) for char in string) for fun in check_funs]

def print_output(results):
    for el in results:
        print el

if __name__ == '__main__':
    string = parse_input()
    print_output(check_string(string))

Apologies for the lack of docstrings; I think aside from that, I'm PEP8 compliant but please let me know if I missed something.  I'm interested in any and all feedback of course, but in particular:

I feel like my check_string() function isn't very pretty.  What's the preferred syntax for folding a list of class methods into a list comprehension?  I found a possibly relevant Stack Overflow question but couldn't quite make heads or tails of it.  It just doesn't seem right to have to do str.method to refer to a function, but then call it with fun(my_string) for fun in func_list instead of my_string.fun() for fun in func_list. (But that latter bit doesn't work of course.)

What are some better ways?

I think your way of calling the methods is just fine. Readable and succinct. My problem is with the names check_funs and fun. Why are we having fun here?

Generally it's best not to use a function or an abbreviation of functions as a name. At the very least, use func as a much clearer abbreviation for function. Even though it is a somewhat relevant name here, it's not important that they're functions. What matters is what they do or what they're for. I'd cut it down to just checks and then for check in checks. Even aside from that though, make sure an abbreviation is clear and not just removing letters. If I was asked what fun was short for, function would be low down on my list. I could only follow in this instance because I knew that you were actually putting functions in the list.


JQuery Slide Show Simplification I'm trying to come up with the most basic example of making a JQuery slide show where you click on the current image you're viewing and you cycle through a gallery of photos. I know its probably not the most basic example, because if I want to add a new image I have to code more JQuery. Is there a more abstract approach where I don't have to code JQuery in terms of div id's and let classes take care of the work?
Here is my JQuery

$(document).ready(function() {
$("#pic1").click(function() {
    $("#pic1").hide();
    $("#pic2").show();
});
$("#pic2").click(function() {
    $("#pic2").hide();
    $("#pic3").show();
});
$("#pic3").click(function() {
    $("#pic3").hide();
    $("#pic1").show();
});
});

The rest is here.
http://jsfiddle.net/XjdTX/3/

This should do the trick:

http://jsfiddle.net/XjdTX/11/

I changed the
...
 to use a class instead. This will allow you to have multiple slide shows functioning off the same code, as shown in the jsFiddle. For toggling through the pics, the pic class is used and cycles based on the index of the clicked image.

There is also code in the jsFiddle that will fade the images instead of just toggling their visibility.

$(document).ready(function() {

    $('.slideframe').each(function() {

        var $pics = $(this).find('.pic'),
            max = $pics.length;

        $pics.on('click.slideframe', function(e) {
            var idx = $pics.index(this);
            if (idx < 0) {
                return false;
            }
            $(this).hide();
            $pics.eq(++idx % max).show();
        });
    });
});


Making the parsing of a String to an Int32 robust (valid, positive, not 0 validation) I've a static method which parses a String (from the App.config) to a Int32. I need to have a valid (since the parsing would fail of course^^), positive and not zero integer. I've done it like this:

    public static int uiScale ()
    {

        int retint = 0;

        try
        {

            retint = Int32.Parse(ConfigurationManager.AppSettings.Get("UiScale"));

        }
        catch (FormatException) {}
        catch (OverflowException){}

        return retint != 0 ? Math.Abs(retint) : 1;

    }

This feels (don't ask me why) a little bit smelly I've to admit. Is this the best way to achieve this?

First: parsing

The shortest you can do is

int uiScale;
return
    int.TryParse(ConfigurationManager.AppSettings.Get("UiScale"), out uiScale)
    && uiScale!= 0 ? Math.Abs(uiScale) : 1 ;

Second: style

uiScale

This method should be called either GetUiScale or be a property if named UiScale because in C# we use PascalCase for public members and methods usually contain a verb (where it makes sense).

retint

Don't just call it like this. It's better to use the real name that better describes the purpose of the variable so uiScale would be fine.


Planned Economy Bakery - Trying to scale a nested loop with a heap Let's say you are living in a controlled economy where there is a baker in town, and every day he bakes a random number of loaves of bread (sometimes the oven breaks, or he has less ingredients). The people in the town queue up to buy a loaf of bread (you can only buy one loaf) based on a pre-assigned ticketing system. Your position in the queue is constant every single day.
There are more people in the queue than loaves of bread available. The bread is ready at different times each day, and some people in the queue need to be at work. If the bread isn't ready before they have to leave for work, they leave the queue and the next person in line takes their place. But they still have their original queue ticket. The values in the people list are the number of hours before the person in the queue has to leave for work
I want to know what is the number on the last ticket given to the baker each day before he runs out of loaves of bread.
I can get my existing code to work for relatively small numbers of people, but if there are millions of people, lots of days (planned economies plan for 5 years ahead), you get the picture.
def BakerQueue(loaves, people, bake_time):
    got_some_bread = []
    for b in bake_time:
        counter = 0
        for p in range(len(people)):
            if people[p] >= b:
                counter += 1
                if counter == loaves:
                    got_some_bread.append(p + 1)
                    counter = 0
                    break
                elif p == len(people) - 1:
                    got_some_bread.append(0)
                    break
            elif counter < loaves and p == len(people) - 1:
                got_some_bread.append(0)
                counter = 0
    return got_some_bread

You can use this to run the code:
in this example, there are 3 loaves, 19 people in the queue [list], and different bake times [list] for each of the days in a week, so on the first day, ticket 1, 2, 3 get loaves, on the second day 2,3,4 get loaves because 1 went to work as the bread wasn't ready in time, on the third day, 7, 9 and 15 get loaves because the bread took 5 hours to be ready and those people went to work. I only care about who gets the last loaf on each day which is what the function is returning.
BakerQueue(3, [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],[1, 2, 5, 4, 5, 4, 7])

This will return as expected
[3, 4, 15, 7, 15, 7, 19]

So I thought about implementing a priority queue using the heapq library, however, I need to maintain the original ticket order, so I thought to create a list of tuples with the values and the index and convert to a heap and pop the top person off of the heap if they have gone to work or if they have gotten a loaf of bread and there are still loaves available. This is the point where I begin to fail. I only care which ticket number got the last loaf of bread each day

I think I understood your problem.
Problem description
Given:

num_items - the number of available items
targets - a list of potential targets, each having a value
threshold - a cutoff limit

Task:

Choose the first num_items elements of targets, whose values are above or equal to threshold.
Return the array index of the last chosen element from targets (starting with 1), or 0 if not enough targets are available. (Odd decision, I would have gone with indices starting at 0 and return len(targets) if none found, but fine)
Optimize for speed. targets and num_items are identical every time, threshold is the only value that changes.

Example
num_items = 3
targets = [5,3,4,1,3,3,7,4]
threshold = 4

Chosen targets would be the ones at the positions [0,2,6], with the values [5,4,7], as those are the first 3 values that are above or equal to threshold. We only search the index of the last one, which in this case would be 6.

Approach
Your original idea was to iterate through all the people which is very fast if the threshold is very low, but becomes really slow if the threshold is higher, as we need to iterate through all the people until we find a candidate.
I rewrote your original idea to iterate through all of them, as I wasn't able to understand your code:
def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id + 1
    return 0

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    results = []
    for today_baking_time in required_baking_times:
        results.append(choose_first_n(num_loaves_per_day, people_max_waiting_time, today_baking_time))
    return results

print(baker_queue(3,
                  [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],
                  [1, 2, 5, 4, 5, 4, 7]))
# Returns: [3, 4, 15, 7, 15, 7, 19], as in the original code.

Using a heap is an interesting idea, but I don't think we benefit from that in any way. Heaps are only really fast for item removal/insertion, which we don't do. We just iterate over them.
The fastest way that I could think of is to pre-process the threshold list into something more efficient, as if, create an 'index' of the last target.
Demonstration:
We use our previous code, and look at the results based on the threshold value:
def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id + 1
    return 0

targets = [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8]
num_items = 3

for threshold in range (10):
    result = choose_first_n(num_items, targets, threshold)
    print(f"Threshold: {threshold}, Result: {result}")

Threshold: 0, Result: 3
Threshold: 1, Result: 3
Threshold: 2, Result: 4
Threshold: 3, Result: 4
Threshold: 4, Result: 7
Threshold: 5, Result: 15
Threshold: 6, Result: 15
Threshold: 7, Result: 19
Threshold: 8, Result: 19
Threshold: 9, Result: 0

You can see that if the threshold goes up, the result goes up. There is a steadily increasing relationship between the threshold and the result.
If we can compute the values at which the result changes, we can compute the result directly via a divide-and-conquer search, which is a LOT faster than iterating through the list. (O(logn) instead of O(n), in case you are familiar with Big-O notation)
One thing to note here is that the last result is 0, which breaks that scheme. That is the reason why it is benefitial to let the indices start with 0 instead of 1, and have the 'error' case be len(targets) instead of 0.
Preprocessing
The hardest thing is the preprocessing to get to that mapping.
Let's look at it from the other way round.
For the sake of simplicity, let's say num_items is 3, and we have 10 targets.
Will the chosen targets be within the first 5 targets?
The answer is: yes, IF at least 3 of the first 5 targets are above or equal to the threshold. Or in other words, the 3rd largest number in the list is the deciding factor. If the threshold is above the 3rd largest number, the first 5 targets will not provide all the chosen targets.
Therefore, for all items, we need to compute the 3rd largest number. Funnily, this is actually where a heap WILL come in handy ;)
Implementation
import heapq
import bisect

def preprocess(targets, num_items):
    # Special case if we have more items than targets, would break later.
    # Return an empty lookup table with len(targets) as fallback, so the
    # result will always be len(targets)
    if num_items > len(targets):
        lookup_table = ([], [], len(targets))
        return lookup_table

    # our heap, will contain the first num_items smallest targets
    largest_targets_heap = []

    # Our first preprocessing result, will contain the
    # third large number between the first item and the current item,
    # for every item.
    third_largest_number_per_target = []

    # Compute the third largest previous value for every target
    for target in targets:
        heapq.heappush(largest_targets_heap, target)
        if len(largest_targets_heap) > num_items:
            heapq.heappop(largest_targets_heap)

        current_third_largest = largest_targets_heap[0]
        third_largest_number_per_target.append(current_third_largest)

    # We now have the third largest number for every target.
    # Now, consolidate that data into a lookup table, to prevent duplication.
    # Therefore, find the first occurrence of every number
    lookup_table_indices = []
    lookup_table_values = []
    current_value = third_largest_number_per_target[num_items - 1]

    # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the
    # first num_items were processed
    lookup_table_indices.append(num_items - 1)
    lookup_table_values.append(current_value)

    # Fill the rest of the lookup table
    for index, value in enumerate(third_largest_number_per_target):
        if index < num_items - 1:
            continue
        if value != current_value:
            lookup_table_indices.append(index)
            lookup_table_values.append(value)
            current_value = value

    # The lookup table we have, consisting of values, indices and a maximum value
    lookup_table = (lookup_table_values, lookup_table_indices, len(targets))

    return lookup_table

def choose_first_n_preprocessed(lookup_table, threshold):
    (lookup_table_values, lookup_table_indices, max_value) = lookup_table

    # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold
    # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.
    position = bisect.bisect_left(lookup_table_values, threshold)

    # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the
    # threshold ist too high.
    if position >= len(lookup_table_indices):
        return max_value

    # Read the result from the table of incides
    value = lookup_table_indices[position]
    return value

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    # Create the preprocessed lookup table
    lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)

    # For every day, compute the result
    results = []
    for today_baking_time in required_baking_times:
        # Use our fast lookup based algorithm now
        result = choose_first_n_preprocessed(lookup_table, today_baking_time)

        # Convert indices back to starting with 1, and 0 in error case, as
        # the original format was
        if result == len(people_max_waiting_time):
            results.append(0)
        else:
            results.append(result + 1)
    return results

print(baker_queue(3,
                  [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],
                  [1, 2, 5, 4, 5, 4, 7]))
# [3, 4, 15, 7, 15, 7, 19]

Theoretical Analysis
This should now be a LOT faster, especially for a large number of days, but also for a large number of people.
The complexity of the naive implementation was
O(days * people)

The complexity of the preprocessed implementation is
O(people * log(bread) + days * log(people))

This doesn't sound a lot different, but it is. It basically says if the limiting factor is the people, it doesn't matter how many days, and if the limiting factor is the days, it doesn't matter how many people.
Benchmarking Results
Setup was:

900 bread per day
10,000 people
10,000 days

Result:

Naive: 2.13 seconds
Preprocessed: 0.012 seconds

I then tried to push the algorithm so far that it also takes 2 seconds, and got those numbers:

90,000 bread per day
1,000,000 people
1,000,000 days

I didn't run those numbers on the naive algorithm, but the math says it would have taken about 20,000 seconds, or 5.5 hours.
The benchmark code can be found at https://ideone.com/2ZMBVH or here:
import heapq
import bisect
import random
import time

def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id
    return len(targets)

# 2s for optimised
#num_bread = 90000
#num_days = 1000000
#num_people = 1000000

# 2s for unoptimized
num_bread = 900
num_days = 10000
num_people = 10000

targets = [random.random() for _ in range(num_people)]

result_sum = 0
algo_naive_start = time.time()
for threshold in range(num_days):
    result = choose_first_n(num_bread, targets, threshold/num_days)
    result_sum += result
    #print(f"Threshold: {threshold}, Result: {result}")
algo_naive_end = time.time()
print(f"Result naive: {result_sum}")

def preprocess(targets, num_items):
    # Special case if we have more items than targets, would break later.
    # Return an empty lookup table with len(targets) as fallback, so the
    # result will always be len(targets)
    if num_items > len(targets):
        lookup_table = ([], [], num_items, len(targets))
        return lookup_table

    # our heap, will contain the first num_items smallest targets
    largest_targets_heap = []

    # Our first preprocessing result, will contain the
    # third large number between the first item and the current item,
    # for every item.
    third_largest_number_per_target = []

    # Compute the third largest previous value for every target
    for target in targets:
        heapq.heappush(largest_targets_heap, target)
        if len(largest_targets_heap) > num_items:
            heapq.heappop(largest_targets_heap)

        current_third_largest = largest_targets_heap[0]
        third_largest_number_per_target.append(current_third_largest)

    # We now have the third largest number for every target.
    # Now, consolidate that data into a lookup table, to prevent duplication.
    # Therefore, find the first occurrence of every number
    lookup_table_indices = []
    lookup_table_values = []
    current_value = third_largest_number_per_target[num_items - 1]

    # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the
    # first num_items were processed
    lookup_table_indices.append(num_items - 1)
    lookup_table_values.append(current_value)

    # Fill the rest of the lookup table
    for index, value in enumerate(third_largest_number_per_target):
        if index < num_items - 1:
            continue
        if value != current_value:
            lookup_table_indices.append(index)
            lookup_table_values.append(value)
            current_value = value

    # The lookup table we have, consisting of values, indices, a minimum and a maximum value
    lookup_table = (lookup_table_values, lookup_table_indices, num_items, len(targets))

    return lookup_table

def choose_first_n_preprocessed(lookup_table, threshold):
    (lookup_table_values, lookup_table_indices, min_value, max_value) = lookup_table

    # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold
    # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.
    position = bisect.bisect_left(lookup_table_values, threshold)

    # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the
    # threshold ist too high.
    if position >= len(lookup_table_indices):
        return max_value

    # Read the result from the table of incides
    value = lookup_table_indices[position]
    return value

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    # Create the preprocessed lookup table
    lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)

    # For every day, compute the result
    results = []
    for today_baking_time in required_baking_times:
        # Use our fast lookup based algorithm now
        result = choose_first_n_preprocessed(lookup_table, today_baking_time)

        # Convert indices back to starting with 1, and 0 in error case, as
        # the original format was
        if result == len(people_max_waiting_time):
            results.append(0)
        else:
            results.append(result + 1)
    return results

algo_preprocessed_start = time.time()

lookup_table = preprocess(targets, num_bread)

algo_preprocessed_mid = time.time()
#print(lookup_table)

result_sum = 0
for threshold in range(num_days):
    result = choose_first_n_preprocessed(lookup_table, threshold/num_days)
    result_sum += result
    #print(f"Threshold: {threshold}, Result: {result}")
algo_preprocessed_end = time.time()
print(f"Result preprocessed: {result_sum}")

print(f"Time naive: {algo_naive_end - algo_naive_start} s")
print(f"Time preprocessed (preprocessing step): {algo_preprocessed_mid - algo_preprocessed_start} s")
print(f"Time preprocessed (evaluation step): {algo_preprocessed_end - algo_preprocessed_mid} s")
print(f"Time preprocessed total: {algo_preprocessed_end - algo_preprocessed_start} s")

Well that took a while, I hope it was worth it ;)
I think this was my biggest post yet, it was a really interesting task!
I hope you appreciate it.
Greetings


Script for adding a set of form fields on clicking an Add More button This is a script that I use to add a set of form fields on clicking an Add More button:

This is the form:

                    Add More Field

                    Item:	Quantity:	Price:	Discount %	VAT %:	Final Price:

                    <input class='item form-control' id="find" type='text'  name='item[]' required>
                    <input class='qty form-control' id="find" type='number' name='qty[]' required>
                    <input class='price form-control' id="find" type='number' name='price[]' required>
                    <input class='discount form-control' id="find" type='number'  name='discount[]' required>
                    <?php $query = mysqli_query($con, "SELECT * FROM `tax_vat` "); echo '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>"';while ($row = mysqli_fetch_array($query)) {echo '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option>
';}echo '</select>';?>
                    <input class='total form-control' id="find" type='number' name='total[]' readonly required>

            Total : <input id='totaldp' class="form-control" type='number' name='totaldp' readonly required>
            <input type="hidden" id="name_id" name="name_id" />

In the form, there is a dropdown box which fetch certain details from the database. The PHP code to fetch and display the dropdown box is coded in the form so that it is displayed on the initial load of the page, and then, the same code is coded in the append function the script so that the same set of input fields are displayed on clicking the Add More button.

The whole thing works perfectly fine. But the code looks terribly ugly. Is there a better way to do it?

Put the php code outside the form, run it once and create a variable with the options, something like:

$dropDownList = '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>';

$query = mysqli_query($con, "SELECT * FROM `tax_vat` ");
while ($row = mysqli_fetch_array($query))
{
$dropDownList .= '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option>';
}

$dropDownList .= '</select>';

Now, in your form you just need to <?php echo $dropDownList?> where you want the drop down to appear.

For your javascript you could do something like this:

var dropOption = "<?php echo $dropDownList?>";

And modify the append() html data like this:

$(InputsWrapper).append('
<input id="find" type="text" name="item[]">	<input id="find" type="number" name="qty[]">	<input id="find" type="number" name="price[]">	<input id="find" type="number" name="discount[]">	'+dropOption+'	<input id="find" type="number" name="total[]" readonly >
');

Hope this helps.


Polling AJAX client for P2P file sharing website I have this function:

function Filer() {
    setTimeout(function () {
        $.ajax({
            url: '/Pages/Handlers/filecheckerhandler.ashx',
            data: { id: GetMyId(), sid: GetSessionId() },
            success: function (data) {
                if (data == "true") {
                    window.open('/Pages/Handlers/livesharehandler.ashx?id=' + GetMyId() + '&sid=' + GetSessionId(), '_self');
                }
            },
            global: false
        });
        Filer();
    }, 2000)
}
Filer();

Basically, my website allows for peer to peer file sharing online. What this does is checks for files and if it is present the file will be downloaded and the file will be deleted from the server.

The function is recursive as you can see. This is making a lot of requests.

But my function is making a lot of requests which is making the site slow. What can be done?

You are polling filecheckerhandler.ashx regularly at two-second intervals. The fact that such polling is implemented using recursion, with Filer() calling itself, is irrelevant to your performance problem.  You could improve the client code by using setInterval() instead of setTimeout(), but the overall system performance will be just as bad.

There are only three strategies to improve system performance:

Lengthen the polling interval.  Especially if no activity has occurred recently, activity is less likely in the near future, so the polling interval could be adaptive.
Improve the efficiency of filecheckerhandler.ashx.  The constraining factor is probably load on the server, rather than load on the client, so any efficiency gains on the server would likely make an impact.
Improve the efficiency of the communication protocol.  Each AJAX request is essentially a new HTTP request, with the only optimization being possible HTTP keep-alive, which might avoid the TCP handshake.  Consider a technique that is more suitable for client-to-server notifications, such as Comet.


Possible combinations of bills that sum to the given amount Question:

  You are given an array that represents bills in certain currency
  (for example 1, 2, 5, 10) and an amount, for example 17. You should output
  the number of possible combinations of bills that sum to the given amount.

Answer:

  {2, 5, 10}

Can I optimize/improve below code? Current complexity is: O(2(n-1)), where n is the bill list length.

//Returns possible Bills List
public static List<Set<Integer>> possibleBills(Integer amount, int[] bills){
    List<Set<Integer>> result = new ArrayList<Set<Integer>>();

    if(amount < 0){
        return null;
    }

    if(bills.length == 0){
        return null;
    }

    if(amount-bills[0] == 0){
        Set<Integer> set = new TreeSet<Integer>();
        set.add(bills[0]);
        result.add(set);
        return result;
    }

    //Include 0'th bill and generate possible bills
    List<Set<Integer>> result1 = possibleBills(amount - bills[0], Arrays.copyOfRange(bills, 1, bills.length));
    if(result1 != null){
        Iterator<Set<Integer>> result1Itr = result1.iterator();
        while(result1Itr.hasNext()){
            Set<Integer> set = result1Itr.next();
            set.add(bills[0]);
        }
        result.addAll(result1);
    }

    //exclude 0'th bill and generate possible bills
    List<Set<Integer>> result2 = possibleBills(amount, Arrays.copyOfRange(bills, 1, bills.length));
    if(result2 != null){
        result.addAll(result2);
    }

    if(result.size() == 0){
        return null;
    }
    return result;
}

You could do some dynamic programming solution.

The basic idea of it in this situation would be you keep track of what you can get with just the 1 dollar bill, then figure out where you can reach with the 2 dollar bill, then the 5 dollar bill.  (For the sake of example, I'll use a 7 dollar bill as well as the one's you have in you example)

So, for example you would start with an array of size 18. Because you can reach 0 dollars, you would have

1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 1 dollar bill you can reach 0 dollars and 1 dollar

1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 2 dollar bill and the 1 dollar bill you can reach 0,1,2,or 3 dollars

1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

then with the 5,2, and 1 dollar bill you can reach 0,1,2,3,5,6,7,or 8 dollars

1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0

then, with the 7 dollar bill: you can reach 7 and 8 in two ways

1,1,1,1,0,1,1,2,2,1,1,0,1,1,1,1,0,0,0

10 dollar bill

1,1,1,1,0,1,1,2,2,1,2,1,2,2,1,2,1,2,2

So, there are two ways to reach 18


Remove duplications from a Java String today I tackled this coding challenge: Remove duplications from string.
I was thinking of either using a Hashmap or a Set but realized that a set might have a longer run time since the way it determines if a numbers is in there or not is by traversing each element. This lead me to use a hashmap instead. I have not taken care of any edge cases but wanted to get people's opinion of this implementation. From what I understand this would be a \$O(n)\$, (\$n\$ being the length of the input String), correct?

  String test = "Banana";
    HashMap<Character, String> nodups = new HashMap<>();
    for(int i = 0; i < test.length();i++){
        nodups.put(test.charAt(i),String.valueOf(test.charAt(i)));
    }

    StringBuilder noDupsString = new StringBuilder();
    for(Character key : nodups.keySet()){
        noDupsString.append(nodups.get(key));
    }

    System.out.println("String value with no dups :" + noDupsString);
}

Soo.. let me tell you a secret about Java's HashSet...

  This class implements the Set interface, backed by a hash table (actually a HashMap instance)

to cut the chase short: you could've just used a HashSet, it would've been at worst equally slow.

now to review the code... Since you don't make any guarantees for execution order in your code, neither will I:

System.out.println("String value with no duplicates: "
    + new HashSet<>(Arrays.asList(test.toCharArray())).stream().collect(Collectors.joining("")));

It should be acceptably easy to see, that this is horrendous code, but it does the same thing as your code...

Either way, the code presented also has some issues:

Unnecessary creation of (relatively speaking) expensive objects.
String.valueOf(test.charAt(i)) is just bad form
Strangely hidden complexity.
In nodups.put(..) there's a hideous hidden complexity. You're hashing the character (which basically just turns it into an int and does some modulo calculations) and then put the char into it's place.
Double loop, where one is sufficient.
Currently the code does two loops, where one is sufficient. In a HashSet the contains-operation is \$\mathcal{O}(1)\$. This allows you to just collapse the loops instead of repeatedly overwriting the same value:

Set<Character> knownChars = new HashSet<>();
StringBuilder nodupsString = new StringBuilder();
for (Character c : test.toCharArray()) {
    if (!knownChars.contains(c)) {
        knownChars.add(c);
        nodupsString.append(c);
    }
}

This reduces the mathematical complexity from \$\mathcal{O}(2n)\$ to \$\mathcal{O}(n)\$. And don't come with the "constants are ignored in O-notation" fallacy. The problem is that too many people think that and as a result write badly performing code, which they think can't be made faster ... </rant>

Aside from that ... good job, I guess?


Faster way of converting a 1-d table to predefined userdata in Lua I have defined a userdata in Lua (Lua version is 5.1) as shown below-

#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>

typedef struct FloatArray {
  int size;
  float values[1];
} FloatArray;

static int new_array(lua_State *L) {
  int n = luaL_checkint(L, 1);
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;
  return 1;
}

I can create a new array of given size by using following Lua code-

a = array.new(10)

Now, I am extending the above function for converting any given 1-d table to array. Please see the code snippet below-

static int new_array_from_table(lua_State *L) {
  luaL_argcheck(L, lua_type(L, -1) == LUA_TTABLE, 1, "'1-d array' expected");

  // get the length of input table
  int n = lua_objlen(L, -1);
  int index;
  float values[n];

  // fetch data and use it to fill the array
  for (index = 1; index <= n; index++) {
    lua_rawgeti(L, -1, index);
    values[index - 1] = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }

  // create new userdata
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;

  // fill the userdata
  for (index = 0; index < n; index++)
    a->values[index] = values[index];

  return 1;
}

The above code works. However, as you can notice that fetching the table data and filling the userdata are done separately.

I wish to have a better implementation, in which we first create new userdata and then we fill the userdata from fetched data at one step.

In other words, I am looking for a way to do the following-

// get the length of input table
int n = lua_objlen(L, -1);

// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;

// fetch data and use it to fill the array
int index;
for (index = 1; index <= n; index++) {
  lua_rawgeti(L, -1, index);
  a->values[index] = (float)lua_tonumber(L, -1);
  lua_pop(L, 1);
}

I noticed that after creating new userdata, the data is being converted to 0. Any workaround, please?

You have a duplication of the allocation and init part in the 2 functions, instead you can create a helper that will create the usertable, return a pointer to it and leave it on top of the stack:

static FloatArray *create_array(lua_State *L, int n) {
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;
  return a;
}

static int new_array(lua_State *L) {
  int n = luaL_checkint(L, 1);
  create_array(L, n);
  return 1;
}

When accessing parameters in the C api it's easier to always index them from the bottom of the stack. That wat you won't end up being mistaken about the state of the stack and try to use the wrong value by accident (like you did in your attempt).

static int new_array_from_table(lua_State *L) {
  luaL_argcheck(L, lua_type(L, 1) == LUA_TTABLE, 1, "'1-d array' expected");

  // get the length of input table
  int n = lua_objlen(L, 1);

  // create new userdata
  FloatArray *a = create_array(L, n);
  //leaves the new table at the top of the stack

  // fetch data and use it to fill the array
  int index;
  for (index = 1; index <= n; index++) {
    lua_rawgeti(L, 1, index);
    a->values[index-1] = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
  return 1;
}

With the creation bit in a single place you can now add a metatable to it so the script can access the values using the indexing syntax.

luaL_Reg[] floatArrayFuncs = { {"__index", get_array_value},
         {"__newindex", set_array_value},
         //...
         {NULL, NULL},};

//call on initialization
static void init_FloatArray(lua_State *L){
    luaL_newmetatable (L, "FloatArray");
    luaL_setfuncs(L, floatArrayFuncs , 0);
    lua.pop(1);
}

static FloatArray *create_array(lua_State *L, int n) {
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  luaL_setmetatable (L, "FloatArray", -1);
  a->size = n;
  return a;
}

The metatable also allows you an easy way to type check the userdata from lua using

FloatArray *a = (FloatArray *)luaL_testudata (L, arg, "FloatArray");

Also you can overload the creation function by doing

static int new_array(lua_State *L) {
  switch(lua_type(L, 1)){
  case LUA_TNUMBER:
      int n = luaL_checkint(L, 1);
      create_array(L, n);
      return 1;
  case LUA_TTABLE:
      return new_array_from_table(L);
  case LUA_TUSERDATA:
      return duplicate_array(L);  //exercise for the reader
  default:
      luaL_argcheck(L,0, 1, "expected number, 1D array or FloatArray");
  }
  return 0; //never reached
}


Create an array of objects from array of arrays I have the following function that creates an array of JSON objects with properties from an array of arrays, where the first 'row' in the array contains the keys.

It works, but could it be improved?

var myArray = [
    ["a","b","c","d"], // will become keys
    [1,2,3,4],
    ["foo","bar","baz","bob"]
];

function makeObjProp(arr) {

    var keys = arr[0];
    var numRows = arr.length;
    var numCols = keys.length;

    var result = [];

    // starts i = 1 to avoid adding an object of 'keys':'keys'
    for (var i = 1; i < numRows; i++) {
        var obj = {};

        for (var j = 0; j < numCols; j++) {
            obj[ keys[j] ] = arr[i][j];
        };
        result.push(obj);
    };
    console.log(result);
}

makeObjProp(myArray);

fiddle

I don't see any significantly better way of doing this. It can be written in different ways (like below), but yours is pretty simple and straightforward.

That said, you'll probably want your function to actually return the new array instead of just logging it.

And you'll want some error checking. I'd say you should assume that an array has been passed in (if it isn't, well, that's not really this function's responsibility. Garbage In, Garbage Out), but don't assume it's actually populated. So check that it contains at least 2 rows.

You may also want to check that the items in the array are also arrays, though again: GIGO.

And I'd rename the function. It doesn't "make an object property" as its name suggests; it converts an entire array to objects, following some scheme. I can't quite say what that better name might be, though. The input resembles tabular data (header row, etc.), so maybe something along those lines.

If you're targeting modern browsers, you could do some map/reduce stuff instead:

function rowsToObjects(table) {
  var keys = table[0],
      rows = table.slice(1);

  if(rows.length === 0) return [];

  return rows.map(function (row) {
    return keys.reduce(function (memo, key, index) {
      memo[key] = row[index];
      return memo;
    }, {});
  });
}


Autocompleting when a certain class is present This jQuery actually autocomplete when the onkeydown class is present and load the autocomplete with corresponding variable. This is working but I want to make it shorter.

var autocomp_opt = {
    source: "<?php echo base_url();?>description/get_description",
    minLength: 1,
    select: function(evt, ui) {
        this.form.sub_description.value = ui.item.sub_description;
    }
};

var autocomp_opt1 = {
    source: "<?php echo base_url();?>description/get_description",
    minLength: 1,
    select: function(evt, ui) {
        this.form.sub_description2.value = ui.item.sub_description;
    }
};

$(document).on("keydown", ".sn", function () {
    $(this).autocomplete(autocomp_opt);
});

$(document).on("keydown", ".sn2", function () {
    $(this).autocomplete(autocomp_opt1);
});

I'm proposing to reduce code by putting all similar code to one function:

function initAutocomplete(selector, field) {
  $(selector).on('keydown', function() {
    $(this).autocomplete({
      source: '<?php echo base_url();?>description/get_description',
      minLength: 1,
      select: function(evt, ui) {
        this.form.elements[field].value = ui.item.sub_description;
      }
    });
  });
}

initAutocomplete('.sn', 'sub_description');
initAutocomplete('.sn2', 'sub_description2');


Is this a reasonable algorithm for shuffling cards? So I based my "algorithm" on the poke method defined by Persi Diaconis. You start with the card at the bottom of a given deck and then poke the top card into a random position in the deck. At first the probability of this happening is 1/52 but once a card is below the bottom most card it increases to 2/52 since there is now two positions a card could go to move the bottom card up the deck.

He claims it takes about 200 of these pokes to get the bottom card to the top. Then you poke the that bottom card which is now at the top somewhere random in the deck and he claims it is now completely randomized.

My results have held true to that, I haven't calculated mean or standard deviation yet to check but just from initial runs it seems to hold true(he is a mathematician and I am a first year undergrad, of course its true).

public void shuffle()
{
    SecureRandom rnd = new SecureRandom();
    Card bottomCard = deck.get(deck.size() - 1);
    int i = 0;
    while(!deck.get(0).equals(bottomCard))
    {
        Card poke = deck.get(0);
        deck.remove(0);
        deck.add(rnd.nextInt(52), poke);
    }
    deck.remove(bottomCard);
    deck.add(rnd.nextInt(52), bottomCard);
}

It's an interesting approach...  Some cleanup to consider...

int i = 0;

i is never used...

rnd.nextInt(52)

You might want to interrogate the size of deck at the start of the method, rather than using a fixed 'magic' number.  That would mean that you'd be able to use the method to shuffle decks of multiple packs of cards for example...

deck.remove(bottomCard);

Although you're treating this as a unique case, it's still card 0, I'd consider defining a constant FIRST_CARD_IN_DECK=0 to represent the card to remove.

It's unclear where deck comes from should it be passed into the shuffle function?


Deleting a node in a singly linked list? Please critique the following code on removing a node from a singly linked list, at the moment it seems to me like the code is quite clunky.
typedef struct Node {
    int data;
    struct Node* next;
}Node;

Node* create(int A[], int n){
    Node *head = malloc(sizeof(Node));
    Node *temp = NULL;
    Node *tail;
    head->data = A[0];
    head->next = NULL;
    tail = head;
    int i;
    for (i = 1; i < n; i++){
        temp = malloc(sizeof(Node));
        temp->data = A[i];
        temp->next = NULL;
        tail->next = temp;
        tail = temp;
    }
    return head;
}

void delete(Node** head, int index) {
    Node* temp;
    Node* curr;
    Node* prev = NULL;
    curr = *head;
    int pos;
    if (*head == NULL) {
        return;
    }
    if (index == 0) {
        temp = curr->next;
        *head = temp;
        free(curr);
    }
    else {
        for (pos = 0; pos < index; pos++) {
            prev = curr;
            curr = curr->next;
        }
        prev->next = curr->next;

        free(curr);
    }

}

int main(){
    int A[] = {3, 5, 7, 9, 10};
    Node *head = create(A, 5);
    delete(&head, 1);
    return 0;
   }

Mark variables that will remain constant as const.
Initialise variables right away when they're created, if possible. You're just adding one extra line with no benefit.
Limit the scope of variables by creating them only when they're required, not at the top. They'll go unused in certain conditions. Also one won't have to sanity check the whole function to see if the variable has been modified since it was created.
Use a more descriptive function name. del_node_at_index is even better.

void delete_node(Node **head, const int index)
{
  // Initialise curr when it's defined.
  Node *curr = *head;

  if (head == NULL) {
    return;
  }
  if (index == 0) {
    // Keep the scope of temp limited.
    // Initialise temp when it's defined.
    Node *temp = curr->next;
    *head = temp;
    free(curr);
  }
  else {
    // Keep the scope of prev limited.
    Node *prev;
    // Define pos if and when needed.
    for (int pos = 0; pos < index; pos++) {
      prev = curr;
      curr = curr->next;
    }
    prev->next = curr->next;

    free(curr);
  }
}


Rails 5 controller to get information about Steam users I've done a bit of modifications and finally got it working, and did a lot of reading about @ vs @@ vs just declaring and I came up with.

It goes to Steam's API to return information (JSON Format) based on the endpoint. A list of games they own, a list of games they recently played, profile information, etc.

class SteamController < ApplicationController

  def initialize
    @steamKey = ENV["steam_api_key"]
    @ISteamUrl = "http://api.steampowered.com/ISteamUser/"
    @IPlayerUrl = "http://api.steampowered.com/IPlayerService/"
  end

  def get_steam_summary_per_user #/steam/:id
    @steamEndpoint = "GetPlayerSummaries/v0002/?key="+@steamKey+"&steamids="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @ISteamUrl + @steamEndpoint + @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

  def get_steam_recently_played_per_user #/game/:id
    @recPlayedEndpoint = "GetRecentlyPlayedGames/v0001/?key="+@steamKey+"&steamid="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @IPlayerUrl + @recPlayedEndpoint + @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

  def get_steam_owned_games_per_user #/allGames/:id
    @allGamesUrl = "GetOwnedGames/v0001/?key="+@steamKey+"&steamid="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @IPlayerUrl + @allGamesUrl +  @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

end

Routes

  get '/steam/:id',  to: 'steam#get_steam_summary_per_user'
  get '/games/:id',  to: 'steam#get_steam_recently_played_per_user'
  get '/allgames/:id', to: 'steam#get_steam_owned_games_per_user'

I originally just has @baseUrl but realized they have multiple services and versions, but even before that I couldn't figure out why doing

@baseUrl = "http://api.steampowered.com/"+@recPlayedEndpoint+"etcetc
wouldn't work - I assumed it was related to initializing the `@recPlayedEndpoint and then re-assigning it later.

Ths code feels very redundant to me and I still have 5-6 more functions to build out.

The routes make sense, and I'm not sure if I can do them better. Please also tell me if my syntax is not proper for Rails - While I have an Angular front-end I'm trying to understand when to use camel case vs snake, vs pascal etc etc.

(All of this outputs to pure JSON and I use my Angular side render it, so if there is an easier way to do this. However, this is NOT set up on an api version of Rails)

You don't need all those @s. Everything in the action methods can be handled with local variables, and the initlization can be made more Rails-like. For instance:

class SteamController < ApplicationController
  BASE_URL = "http://api.steampowered.com".freeze

  before_action :load_user

  def get_steam_summary_per_user #/steam/:id
    endpoint = url_for_path_and_id("/ISteamUser/GetPlayerSummaries/v0002/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  def get_steam_recently_played_per_user #/game/:id
    endpoint = url_for_path_and_id("/IPlayerService/GetRecentlyPlayedGames/v0001/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  def get_steam_owned_games_per_user #/allGames/:id
    endpoint = url_for_path_and_id("/IPlayerService/GetOwnedGames/v0001/", @user.steamId)
    render json: HTTParty.get(endpoint).to_json
  end

  private

  def url_for_path_and_id(path, id)
    "#{BASE_URL}#{path}?key=#{ENV["steam_api_key"]}&steamid=#{id}"
  end

  def load_user
    @user = User.find(params[:id])
  end
end

Here I'm using Rails's before_action setup to load the user, since that's common for all actions. The constants have been moved to, well, constants, or their values to where they're used. A method has been added to construct the URLs. I'm using the more Ruby-like approach of string interpolation to build the URLs rather than string concatenation.

Yes, I've hard-coded a few strings into the methods, although they do have some parts in common, but I've based it on the sections of a URL: Base (constant), path (varies from method to method, even if parts of it repeat), and query string (appended at the end).

One thing that stands out is that the User model has a steamId attribute: That should be steam_id - in Ruby you should use snake_case for attribute and method names.

However, a different (and, I think, better) approach would be to make a service object to wrap the Steam API. Basically a plain old Ruby class (you can place it in app/services, for instance).

Your controller actions would simply construct a service object, passing in the user, and then call the relevant method to get what they want. E.g. your controller would be just:

class SteamController < ApplicationController
  before_action :create_client

  def get_steam_summary_per_user
    render json: @steam_client.summary
  end

  def get_steam_recently_played_per_user
    render json: @steam_client.recently_played
  end

  def get_steam_owned_games_per_user
    render json: @steam_client.owned
  end

  private

  def create_client
    user = User.find(params[:id])
    @steam_client = SteamAPIClient.new(user)
  end
end

where SteamAPIClient is your service object. Keep the controller skinny, and put the logic elsewhere.

Another thing that stood out is the way you set up your routes. The Rails Way™ would be to make the API part of the User controller. From your application's standpoint, you're trying to get information about a user - the fact that it comes from Steam's API is an implementation detail.

In other words, I'd rather see URLs like:

/users/:id/summary
/users/:id/owned
/users/:id/recent

than URLs like /steam/:id, or /games/:id. If you follow common RESTful API patterns, those URLs indicate that you have a collection of "steams" and a collection of "games", and the :id is used to pick out a particular one. But that's not your model; you don't have multiple "steams". What you have a users, identified by an id, which in turn have some associated data you can fetch.

Or in route-speak:

resources :users do
  member :summary, via: :get
  member :owned, via: :get
  member :recent, via: :get
end

Doing things this way is another reason to extract the actual Steam API-fethcing code into a service object, so you can just call it from the Users controller.

The give-away in your current code is that all your actions are called ..._per_user. Well, if it's per user, then make it per user by making it member actions on the Users controller.

Basic idea is that you treat the Steam API as you would treat the database: It's a data source. You don't put all the database connection and querying logic in a controller, you just put User.find(x), and the rest happens elsewhere. Same here, in a sense.


Method GetById and SingleResult Here is my method that I use to get one entity in an ASP.NET Web API application.

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

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

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

How can I improve it?

You can wrap the single entity into an IQueryable.  Something like this should work:

SingleResult.Create(new[]{entity}.AsQueryable());

You could write a helper function that uses this trick to convert from a single T to an IQueryable<T>.  There may even be a built-in way of doing this.


Add ImageIndex to Treeview As the title states. I need a different type of icon for the different nodes types. at the moment I have this hacky way of achieving that.

for (var x = 0; x <= nodeList.Count - 1; x++)
{
     if (xNode.Attributes["TYPE"].Value == "server.point.AV")
     {
         var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, AnalogImagesIndex, AnalogImagesIndex);
         inTreeNode.Nodes.Add(tNode2);
         tNode2 = inTreeNode.Nodes[x];
         AddNode(xNode, tNode2);
     }
     else if (xNode.Attributes["TYPE"].Value == "schedule.NSPDigitalSchedule")
     {
         var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, ScheduleImageIndex, ScheduleImageIndex);
         inTreeNode.Nodes.Add(tNode2);
         tNode2 = inTreeNode.Nodes[x];
         AddNode(xNode, tNode2);
     }
     else if (xNode.Attributes["TYPE"].Value == "server.point.SV")
     {
         var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, StringImageIndex, StringImageIndex);
         inTreeNode.Nodes.Add(tNode2);
         tNode2 = inTreeNode.Nodes[x];
         AddNode(xNode, tNode2);
     }
     else if (xNode.Attributes["TYPE"].Value.StartsWith("trend"))
     {
         var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, TrendImageIndex, TrendImageIndex);
         inTreeNode.Nodes.Add(tNode2);
         tNode2 = inTreeNode.Nodes[x];
             AddNode(xNode, tNode2);
         }
    .
    .
    .and so on

I do not want to add the long list of else if's.

The moment you start copy-pasting code and only changing one small thing, it's time to move that code to a method.

private void CreateAndAddNode(WhateverTypeImagesIndexIs imagesIndex, int x)
{
    var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, imagesIndex, imagesIndex);
    inTreeNode.Nodes.Add(tNode2);
    tNode2 = inTreeNode.Nodes[x];
    AddNode(xNode, tNode2);
}

I'm assuming AnalogImagesIndex etc. all inherit from some base type; that's the one to use as the method's parameter.

Moreover, all of those ifs can be changed to a switch.


Getting the current chat room ID I need roomId (an auto_increment primary key) to locate a specific room to update chat info. My way of doing it right now is dumb.

In createRoom.js, I use roomName from a form that a user has entered to create a room model and find its roomId, then make roomId a param of a URL:

var Room = require('../models/database').Room

exports.create = function (req, res) {

Room
    .create({
        room_name: req.body.roomName
    })
    .complete(function () {

        Room
            .find({where: {room_name: req.body.roomName}})
            .success(function (room) {

                res.redirect('rooms/videochat/' + req.body.roomName + '/' + room.room_id);

        })

    })

};

in routes.js, I grab roomId with req.params.roomId and pass it to a view file jade so it can be displayed on a video chat page:

app.get('/rooms/videochat/:roomName/:roomId', function (req, res) {
    res.render('videochat.jade', {roomName: req.params.roomName, roomId: req.params.roomId});
});

In the client side JavaScript, I use

var roomId = $('#roomId span').text();

to get the roomId, then use socket.emit to pass it back to server side:

socket.emit('updateStartTime', roomId);

Interesting question,

my first point is that it is not clear how you wrote the Room module, but ideally, that module should do 2 things:

Provide the created room to complete
Provide a way to deal with failure

Then, I would expect in the top code to see something like this:

var Room = require('../models/database').Room

exports.create = function (req, res) {
    Room.create({
        room_name: req.body.roomName
    })
    .complete(function ( success, room ) {
        if( success )
            res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );
        else
            res.redirect('cuteapologetickittenvideo/');
    });
};

You will notice that I also changed req.body.roomName -> room.room_name -> room.roomName which makes more sense to me. On a general note I find it bad practice to require room_name in your call to the constructor, but roomName in the request. I would suggest to stick to 1 convention (The JavaScript One) and use roomName everywhere. Then you could write

var Room = require('../models/database').Room

exports.create = function (req, res) {
    Room.create( req.body ).complete(function roomComplete( success, room ) {
        if( success )
            res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );
        else
            res.redirect('cuteapologetickittenvideo/');
    });
};

For the Jade processing, you should be able to get room id and name from the matching on '/rooms/videochat/:roomName/:roomId'.

Same for the client side javascript, I would be more inclined to get this from the URL than from a field in the HTML.


Find index of array item starting at a given location I've written a lot of C++ but now I'm learning Swift.  I did an exercise, the standard Sieve of Erastosthenes. It works fine, but it seems a bit clunky and I wonder if I'm missing some language features that might streamline it a bit and make it more idiomatic Swift.

Here's the code:

struct Sieve {
    let primes: [Int]
    init(_ maxValue: Int) {
        var numbers = Array<Int?>(repeating: nil, count:maxValue + 1)
        for n in 2...maxValue { numbers[n] = n }
        var start = 2
        while start < maxValue {
            guard let prime = numbers.first(where: {$0 != nil && $0! >= start}) else {break}
            let lo = 2 * prime!
            if lo < maxValue {
                for x in stride(from: lo, to: numbers.count, by: prime!) {
                    numbers[x] = nil
                }
            }
            start = prime! + 1
        }
        primes = numbers.compactMap{$0}
    }
}

With the line starting "guard let prime", I'd like to supply a starting index for the 'find' operation, which would be a lot more efficient and would let me drop the comparison $0! >= start altogether. Something along the lines of

guard let prime = numbers.first(where: {$0 != nil}, start: start) else {break}

I also tried

guard let prime = (start...maxValue).first(where: {index in numbers[index] != nil}) else {break}

and that does work but it seems even more awkward. It does have the advantage of starting the search at the index start instead of index zero each time. What's the preferred way to search an array beginning somewhere in the middle of it?

To answer your immediate question: You can search in an array slice:

 guard let prime = numbers[start...].first(where: {$0 != nil}) else {break}

That works because array slices share their indices with the originating array.

There is a small bug in your program, as one can see here:

let sieve = Sieve(4)
print(sieve.primes) // [2, 3, 4]

The reason is that the

if lo < maxValue { ... }

loop does not include the last value. The test should be lo <= maxValue.

There are also some possible improvements:

        let lo = 2 * prime!

can be replaced by

        let lo = prime! * prime!

because all lower multiples have been “nilled” before. As a consequence, the outer loop

    while start <= maxValue { ... }

can be replaced by

    while start * start <= maxValue { ... }

Now instead of repeatedly searching for the next non-nil entry in the array you might as well iterate over the array. This allows also to get rid of the ugly forced unwrapping prime!:

    for i in (2..<numbers.count).prefix(while: { $0 * $0 <= maxValue }) {
        if numbers[i] != nil {
            for x in stride(from: i * i, to: numbers.count, by: i) {
                numbers[x] = nil
            }
        }
    }

At this point it becomes apparent that the information in the numbers array is redundant: Each element is equal to its index or nil. Therefore  a boolean array is sufficient instead of an array of optional integers, this reduces the required memory considerably.

I suggest that you first try to implement that yourself, otherwise have a look at func eratosthenesSieve() in Prime Number Generator & Efficiency.


Basic OpenGL drawing shapes I'm drawing shapes to OpenGL using the standard commands and function calls to OpenGL. Everything works fine, however since this is a learning process I know sometimes what works in theory and using simple basic examples doesnt always work in real time situations so I wanted to ask if this is correct what I am doing here with my drawing commands.

Everything works fine, and draws correctly as expected but I am just curious is it correct way to do things and could i result in problems when drawing far more objects in a real world rendering scene.

Here is the drawing part of the code:

//raw data
   GLfloat vec[] = {0.0f, 0.0f,
                            1.0f, -1.0f,
                           -1.0f, -1.0f};

   GLfloat vec2[] = {0.0f, 1.0f,
                            1.0f, 0.0f,
                           -1.0f, 0.0f};

   //next step is to upload data to graphics memory

   //generating a buffer from openGL
   GLuint vbo;
   GLuint vao;

   glGenBuffers(1, &vbo);

   glGenVertexArrays(1, &vao);

   //to upload the actual data must make the object active by binding it to a target
   glBindBuffer(GL_ARRAY_BUFFER, vbo);
   //upload the data of active object to memory
   glBufferData(GL_ARRAY_BUFFER, sizeof(vec), vec, GL_STATIC_DRAW);

   //first triangle bind and enable
   glBindVertexArray(vao);

   glEnableVertexAttribArray(0);
   glVertexAttribPointer(0,2,GL_FLOAT, GL_FALSE, 0, NULL);

   glDrawArrays (GL_TRIANGLES, 0, 3);
   glXSwapBuffers ( dpy, glxWin );

   sleep(1);

   glClear(GL_COLOR_BUFFER_BIT);

   glBufferData(GL_ARRAY_BUFFER, sizeof(vec2), vec2, GL_STATIC_DRAW);

   glDrawArrays (GL_TRIANGLES, 0, 3);
   glXSwapBuffers ( dpy, glxWin );

   sleep(1);

So as you can see what i am doing , since the triangles are the same dimensions just different vector positions, i am simply just uploading/transferring the data to the server memory of one object instead of creating whole other object with exactly the same set-up as the first object but different position vectors and i would like to know is this safe to do and practical?

For the most part this looks like a typical way to draw geometry in OpenGL. I see a few things that could be improved.
Use structures for structured data
Currently you're storing your vertex coordinates in a 1 dimensional array of floats. But that data isn't just 6 floats. It's 3 points. So you should create a point structure:
struct Point2D {
    float x;
    float y;
};

And your vertex coordinates should be defined using that struct:
struct Point2D triangle1[] = {
    { 0.0f, 0.0f },
    { 1.0f, -1.0f },
    { -1.0f, -1.0f }
};

struct Point2D triangle2[] = {
    { 0.0f, 1.0f },
    { 1.0f, 0.0f },
    { -1.0f, 0.0f }
};

This will make it easier to read and understand. It also makes it much easier to find bugs. If your geometry looks weird, and it turns out you missed an x coordinate in one vertex, good luck figuring out that's the problem with a 1D array of floats. If you miss a coordinate with this struct, you'll get a compiler error.
And since you're working with triangles in this case, you could even make a Triangle2D structure containing 3 Point2Ds. It might be overkill for this simple example, though.
Use meaningful variable names
Names like vao and vbo tell you that those variables store the names for vertex array objects and vertex buffer objects. But they don't tell you which object in your scene they're used for, or how they differ from any other vertex array or buffer you're going to allocate later in the code. Obviously in this example, they only represent the arrays/buffers for the 2 triangles you're drawing, so suggesting a better name is difficult. But at least something like triArrayObj and triBufferObj would be more clear. In a game, for example, you might keep one set around for the scenery and another for the player's character, and another for an enemy, or something like that. They should be named as such.
The names of vec and vec2 are even worse, though. They're vectors, but vectors of what? As with the VAOs and VBOs, there's no real meaning in this particular code since it's just an example, so I'd at least name them tri1 and tri2 for "Triangle 1" and "Triangle 2".
Don't use sleep
You should not be calling sleep() in this code. It's not clear what you're trying to accomplish by doing that. It looks like you're drawing a frame with 1 triangle, then clearing it and drawing a frame with another triangle. Normally, you'd have an event driven application that takes input from the user and tells you to draw with some period, so you wouldn't want to use sleep() because you'd slow it down.
Efficiency
You ask a fair question about whether the way you're doing things is efficient or not. It's a little hard to answer given the simplicity of your example, but here are my thoughts.
In general you want to generate OpenGL objects like vertex array objects and vertex buffer objects infrequently. Allocating memory takes time. You also want to minimize sending data to the GPU. What that means in general is allocate whatever you can upfront and load it onto the GPU as infrequently as possible. In many cases you have a large amount of geometry that won't change, and a little bit of geometry that will change. You might also have a set of textures that are used throughout your rendering. If you can load all your unchanging geometry and unchanging textures onto the card at the start of your app (or assuming it's a game, the start of a level), that will help minimize the overhead of sending data to the GPU.
But you have to be careful. If you load more data onto the GPU than you have memory for, you could get VRAM swapping, or even just rendering errors. It's often the case that all the data you need to draw a scene won't fit on the GPU at once and you have no choice but to upload some of it every frame, or in severe cases, multiple times per frame.
You may find this becomes more difficult than it sounds at first as you attempt to support a wider range of possible GPUs. Your users may have hardware that ranges from extremely low-end to extremely high-end.


Subset sum problem implementation Here is a recursive implementation of the Subset sum problem:

using System;

namespace Exercise
{
  class SubsetSum
  {
    static void Main(string[] args)
    {
         set = new int[] { 2, 3, 1, -1};
         PrintSet(set, "Initial Set.");

            sum = 4;
            Console.WriteLine("Wanted sum = {0}", sum);

            FindSubsetSum();
        }
        //-------------------------------------------------------------

        static int[] set;
        static int[] subSetIndexes;
        static int sum;
        static int numberOfSubsetSums;

        //------------------------------------------------------------

        /*
            Method: FindSubsetSum()
        */
        private static void FindSubsetSum()
        {
            numberOfSubsetSums = 0;
            int numberOfElements = set.Length;
            FindPowerSet(numberOfElements);
        }
        //-------------------------------------------------------------

        /*
            Method: FindPowerSet(int n, int k)

        */
        private static void FindPowerSet(int n)
        {
            // Super set - all sets with size: 0, 1, ..., n - 1
            for (int k = 0; k <= n - 1; k++)
            {
                subSetIndexes = new int[k];
                CombinationsNoRepetition(k, 0, n - 1);
            }

            if (numberOfSubsetSums == 0)
            {
                Console.WriteLine("No subsets with wanted sum exist.");
            }
        }
        //-------------------------------------------------------------

        /*
            Method: CombinationsNoRepetition(int k, int iBegin, int iEnd);

        */
        private static void CombinationsNoRepetition(int k, int iBegin, int iEnd)
        {
            if (k == 0)
            {
                PrintSubSet();
                return;
            }

            for (int i = iBegin; i <= iEnd; i++)
            {
                subSetIndexes[k - 1] = i;
                ++iBegin;
                CombinationsNoRepetition(k - 1, iBegin, iEnd);
            }
        }

    }
}

Input:

  -

Output:

  Initial Set.
   {2 ,3 ,1 ,-1}
   Wanted sum = 4
   (1 ,3)
   (-1 ,3 ,2)

The algorithm is based on finding the Power setexcept the trivial empty set of indexes, which is in turn based on finding all the combinationswithout repetition of indexes with size 1, 2,..., n. Then the sets of indexes corresponding to array elements with the wanted sum are printed.

Any comments regarding the style and implementation will be appreciated.

Is the complexity of this algorithm 2n, where n - number of elements in the array?

Is there more efficient approach to that problem, probably iteration instead of recursion?

Here are the helper functions:

    private static void PrintSubSet()
    {
        int currentSubsetSum = 0;

        // accumulate sum of current subset
        for (int i = 0; i < subSetIndexes.Length; i++)
        {
            currentSubsetSum += set[subSetIndexes[i]];
        }

        // if wanted sum: print current subset elements
        if (currentSubsetSum == sum)
        {
            ++numberOfSubsetSums;

            Console.Write("(");
            for (int i = 0; i < subSetIndexes.Length; i++)
            {
                Console.Write(set[subSetIndexes[i]]);

                if (i < subSetIndexes.Length - 1)
                {
                    Console.Write(" ,");
                }
            }
            Console.WriteLine(")");
        }
    }
    //-------------------------------------------------------------

    private static void PrintSet(int[] arr, string label = "")
    {
        Console.WriteLine(label);

        Console.Write("{");
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);

            if (i < arr.Length - 1)
            {
                Console.Write(" ,");
            }
        }
        Console.WriteLine("}");
    }

My major critique of your code is that you mix up all kinds of concerns all over the place. The code that computes the subsets also does the printing and the counting and all that stuff.

Some thoughts on how to improve this:

The problem is the subset sum problem. Its input is a set of integers.  So why do you do everything in arrays?  Make a class Set, or use an existing class, and have that represent your set of integers.
Once you have that class, build basic operations out of it.  So for example, a Set<T> should have a PowerSet member, which returns Set<Set<T>>, or even better, EnumeratePowerSet, which returns IEnumerable<Set<T>>.
Now that you have those operations, you can use LINQ to do queries against them.

In short, I'd like to see a method like this:

// Takes a set and a sum, returns a sequence of subsets that
// sum to the given value.
static IEnumerable<Set<int>> SubsetSum(Set<int> items, int sum)
{
  return from subset in items.EnumeratePowerSet()
         where subset.Sum() == sum
         select subset;
}
static void Display(IEnumerable<Set<int>> subsets)
{
  if (!subsets.Any())
    Console.WriteLine("No subsets sum to that value.");
  else
    foreach(var subset in subsets)
      PrintSubset(subset);

Now, can you implement the EnumeratePowerSet method on Set<T>?

  Is the complexity of this algorithm 2n, where n - number of elements in the array?

Yes.

  Is there more efficient approach to that problem, probably iteration instead of recursion?

There is no known algorithm that does better than exponential in general.  (There is no proof that there is no such algorithm. The discovery of such an algorithm or a proof that none exists would be a major result in computer science.)

However there are algorithms that do better on typical subset sum problems given certain constraints. There is a huge amount of research on this problem; I leave it to you to consult your local university library.


Search in sorted matrix NxM The problem (from Cracking the Coding book):

  Given an NxM matrix in which each row and each column is sorted in ascending order, write a method to find an element.

I thought of a modified version of binary search, and I haven't found this solution anywhere on the internet (some solution about quad partitioning is very similar as seen in this link).

Here's my solution:

def search(elem, matrix, up, down, left, right):

    if up > down or right < left:
        return None

    mid_row = int((up + down) / 2)
    mid_col = int((left + right) / 2)

    mid_elem = matrix[mid_row][mid_col]

    if elem == mid_elem:
        return mid_row, mid_col
    elif up == down and left == right:
        return None

    if elem > mid_elem:
        # Search RIGHT
        right_search = search(elem, matrix, up, down, mid_col + 1, right)

        if right_search == None:
            # Search DOWN
            return search(elem, matrix, mid_row + 1, down, left, right)

        return right_search

    else:
        # Search LEFT
        left_search = search(elem, matrix, up, down, left, mid_col - 1)

        if left_search == None:
            # Search UP
            return search(elem, matrix, up, mid_row - 1, left, right)

        return left_search

    return None

The code can be tested with the following:

if __name__ == "__main__":
    matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24]]
    elem = 8
    N = len(matrix)
    M = len(matrix[0])
    print(search(elem, matrix, 0, N-1, 0, M-1))

I think that my code is pretty neat and easy to understand. As far as I tested it works perfectly, and should have a time complexity similar to the QuadPartition. What I don't understand is why haven't I seen this solution code anywhere? Is there a cleaner and faster way to write it?

With regards to your code, the only comments I have are that lo and hi may be better names than up and down, and that you probably should have a more specific name than search. As to why you don't see this in the wild, the biggest reason is that Step-wise Linear Search is almost always faster, and simpler to implement. step-wise linear search takes 2n steps to complete, has no recursion, and uses no memory. quad-partitioning, on the other hand, is more complicated, has worse complexity (n^ln(3) vs 2n), and has worse constant factors (due to more branching, and recursion).