C++ insertion sort implementation I was wondering if this implementation of insertion sort could be improved. Are there any things that I have done wrong?

template<typename Element>
void insertion_sort(Element arr[], size_t size) {
    size_t index, index_sorted;
    for (index = 0u; index < size; ++index) {
        auto temp = arr[index];
        index_sorted = index - 1;
        while (arr[index_sorted] >= 0 && arr[index_sorted] > temp) {
            arr[index_sorted + 1] = arr[index_sorted--];
        }
        arr[index_sorted + 1] = temp;
    }
}

Small nitpicks

The for loop can be started from 1, as the iteration with 0 doesn't actually do anything.
Prefer to reduce the scope of variables if possible. This allows better reasoning for the compiler/optimizer, and makes the code more readable because the variable declaration is nearer to the actual usage.
The check arr[index_sorted] >= 0 in the while loop should probably be index_sorted >= 0u (after all, Element might not be comparable to integers), but this is true in all cases (-1 for an unsigned integer type is equal to that type's maximum value). However, even checking this becomes unnecessary if the first iteration starts at 1.
The array elements could possibly be moved to their new locations (this might improve performance in some cases).

template<typename Element>
void insertion_sort(Element arr[], size_t size) {
    for (auto index = 1u; index < size; ++index) {
        auto temp = std::move(arr[index]);
        auto index_sorted = index - 1;
        while (arr[index_sorted] > temp) {
            arr[index_sorted + 1] = std::move(arr[index_sorted--]);
        }
        arr[index_sorted + 1] = std::move(temp);
    }
}

Technically, the size of the array could be deduced automatically by taking a reference (though it has an ugly syntax). However, by taking an explicit size parameter one can sort a partial array, so I'd prefer the flexibility of this approach.


Efficient way of finding perfect squares I was trying to solve a problem which needed you to count the number of perfect squares in the given range:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int isPerfectSquare(int x)
{
    float s = sqrt(x);
    if (fmod(s,1) ==0)
        return 1;
    else
        return 0;
}
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int testcases;
    unsigned int a,b;
    scanf("%d",&testcases);
    while(testcases--)
        {
        int counter =0;
        scanf("%d %d",&a,&b);
        unsigned int i;
        for(i=a;i<=b;i++)
            {
                int last_digit = i%10;
            if( (last_digit == 2) || (last_digit == 3) || (last_digit == 7) || (last_digit == 8) )
                continue;
            else
            {
                if (isPerfectSquare(i))
                    counter++;
            }
        }
        printf("%d\n",counter);
    }
    return 0;
}

However, this code fails for certain test cases due to a timeout. I found that perfect squares do not end with a 2 or 3 or 7 or 8 so I ignored such values. Yet, I'm unable to solve this problem within the required run time.

I have found similar questions here, but either they were not in C or they didn't have answers that were quite relevant to C.

Could you suggest a way that I can optimize this code so that it could run faster?

You could easily find the number of perfect squares up to (and including) a number by simply using (int)sqrt(x)

If you want the number of squares between two numbers, you should simply need to do this:

(int)sqrt(max) - (int)sqrt(min)

Though note if min is a perfect square, it is excluded/subtracted from the range. You can use a +/- 1 if you want to exclude the max number (if it's a perfect square), or include the min number (if it's a perfect square), from the range.


Typesetting A* in LaTeX using algorithm2e (See the next iteration.)

The result looks like

and my code is:

\documentclass[10pt]{article}

\usepackage{amsmath}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

\begin{document}

  \begin{algorithm}
    \SetKw{Nil}{nil}
    \SetKw{Is}{is}
    \SetKw{Not}{not}
    \SetKw{Mapped}{mapped}
    \SetKw{In}{in}
    \SetKw{ChildNode}{child node}
    \SetKw{Of}{of}
    \SetKw{Continue}{continue}
    $\text{OPEN} = \{ s \}$ \\
    $\text{CLOSED} = \emptyset$ \\
    $\pi = \{ (s \mapsto$ \Nil $)\}$ \\
    $g = \{ (s \mapsto 0) \}$ \\
    \While{$|\text{OPEN}| > 0$}{
      $u = \textsc{ExtractMinimum}(\text{OPEN})$ \\
      \If{$u$ \Is $t$}{
        \KwRet \textsc{TracebackPath}$(u, \pi)$ \\
      }
      $\text{CLOSED} = \text{CLOSED} \cup \{ u \}$ \\
      \ForEach{\ChildNode $v$ \Of $u$}{
        \If{$v \in \textsc{CLOSED}$}{
          \Continue \\
        }
        $c = g(u) + w(u, v)$ \\
        \If{$v$ \Is \Not \Mapped \In $g$}{
          $g(v) = c$ \\
          $\pi(v) = u$ \\
          \textsc{Insert}$(\text{OPEN}, v, c + h(v))$ \\
        }
        \ElseIf{$g(v) > c$}{
          $g(v) = c$ \\
          $\pi(v) = u$ \\
          \textsc{DecreaseKey}$(\text{OPEN}, v, c + h(v))$ \\
        }
      }
    }
    \KwRet $\langle \rangle$
    \caption{\textsc{AStarPathFinder}$(s, t, w, h)$}
  \end{algorithm}

  \begin{algorithm}
    \SetKw{Is}{is}
    \SetKw{Not}{not}
    \SetKw{Nil}{nil}
    $p = \langle \rangle$ \\
    \While{$u$ \Is \Not \Nil}{
      $p = u \circ p$ \\
      $u = \pi(u)$ \\
    }
    \KwRet $p$
  \caption{\textsc{TracebackPath}$(u, \pi)$}
  \end{algorithm}

\end{document}

Can I make my code better? For example, is there a way to defined custom keywords in a "global scope" so that I don't have to repeat myself?

Instead of writing \textsc and \text all the time, I prefer semantic markup, such as \func and \var. These simple name changes make the source code easier to read for me. Compare:

\var{p} = \func{prime}(\var{x})
\text{p} = \textsc{prime}(\text{x})

When reading the first line aloud, you will quickly notice any discrepancy between a name and its type.

It looks weird to me that the math mode is closed before the first \Nil and another math mode is opened again immediately after it. This could influence the spacing in subtle ways. It's probably better to write it like this:

$\pi = \{ (s \mapsto \text{\Nil})\}$

This wording feels more natural since there is really only a single math expression here.

The last \caption is not indented properly.


Implementing carryless multiplication using normal multiplication In carryless multiplication the partial products are XORed (ie addition without carry) together rather than added normally. The partial products themselves are still the product of a power of two (namely a bit extracted from one operand) and the other operand. For a multiplication by a power of two there is no difference between carryless multiplication and regular multiplication, so this step can be done with a normal multiplication. But then in JavaScript the question arises, which multiplication? It could be written like this:

function clmul_u32(a, b) {
    var prod = 0;
    while (a != 0) {
        prod ^= Math.imul(b, a & -a);
        a &= a - 1;
    }
    return prod;
}

Using Math.imul is correct by definition, so no problems there.

Or it could be written like this:

function clmul_u32(a, b) {
    var prod = 0;
    while (a != 0) {
        prod ^= b * (a & -a);
        a &= a - 1;
    }
    return prod;
}

This version avoids Math.imul, which I am often told to "avoid or polyfill", but it is less clear why this version should work. Multiplication by a power of two is actually safe, it cannot mangle the integer part of significand unlike multiplication by values that have simultaneously a low number of leading zeroes and a low number of trailing zeroes. I feel like if I used this version, I would have to write a long-winded comment justifying its correctness.

So which way should I go? Or perhaps there are better ways entirely?

Question 1

So which way should I go?

That depends on what is the assessment criteria. Three basic criteria are performance, readability and ease of use.
Readability
That depends on the reader. Knowing that bitwise operators coerce numbers to signed 32 ints the need to clarify this by using Math.imult is mute. Personally operators are more readable than functions, but some argue the opposite. I would opt for the second version.
Ease of use
Is the function easy to use? Can it be misused? Yes and no. The Math.imult is a little easier because it does not rely on coercion and thus handles different number types better.
The second version has a bug that makes its use difficult.
Example of a failure.
clmul_u32_coerced(0b1110000000000, 1.2); // >> incorrect 0b1111001100110
clmul_u32_imult(0b1110000000000, 1.2);   // >> correct 1110000000000

Why does clmul_u32_coerced fail? The reason is that javascript coerces to the left and for numbers to the highest precision. Thus if you have a double in the operation the result will be a double.
To fix  clmul_u32_coerced you need to coerce b to an int32. But this comes at a performance cost (see below) Well I assumed it would be slower, not so the extra line is worth it, even if you pass int's as args.
function clmul_u32_coerced_f(a, b) {
    var prod = 0;
    b |= 0;
    while (a !== 0) {  // Note strict not equal add ~1% performance
        prod ^= b * (a & -a);
        a &= a - 1;
    }
    return prod;
}

Ease of use means that the caller need not worry about type so clmul_u32_imult is the better option, or use the variant above.
Performance
In terms of performance the use of the * operator gives a benefit. This is expected as any function call has overhead that is generally unavoidable. Testing shows the performance comparison.
Tests using double. Note that 32Int coerced fails
Testing Compare clmul(0b1110000000000, 1.2) 400 times. Sorted by performance.
32Int coerced fixed *.: 0.836µs OPS 1,195,472 100% Total 786ms 940 cycles
Math.imul.............: 0.878µs OPS 1,139,002  95% Total 904ms 1030 cycles
32Int coerced **......: 0.973µs OPS 1,028,149  86% Total 1,002ms 1030 cycles

// * Fixed includes the line `b |= 0;`
// ** This call fails to return the correct result

Tests using arguments that are typed as Signed Int32 eg const a = 0b1110000000000 | 0, b = 1 | 0; clmul(a, b); so there is no failure.
Testing Compare clmul(0b1110000000000, 1) 400 times.
32Int coerced fixed *.: 0.358µs OPS 2,791,501 100% Total 1,214ms 1130 cycles
32Int coerced.........: 0.404µs OPS 2,478,225  89% Total 1,114ms 920 cycles
Math.imul.............: 0.525µs OPS 1,903,171  68% Total 1,497ms 950 cycles

// * Fixed includes the line `b |= 0;`

Thus the test device can do 2,791,501 * 400 ~= 1,116,600,400 clmul's a second. Not bad for Javascript on a 1.60GHz Core.
Question 2

Or perhaps there are better ways entirely?

In javascript there is no easy better way. The functions performance is dependent on the number of bits in a. The operation b * (a & -a) lets you shift b via a multiplication. However if you could get the bit position of (a & -a) then you could use b << bitPos(a & -a) which would be quicker if bitpos had no overhead.
Consider the following variation that avoids the multiplication by shifting b and xoring it with the product.
function clmul_u32_b(a, b) {
    var p = 0;
    while (a > 0) {
        while((a & 1) === 0) {
            a >>= 1;
            b <<= 1;
        }
        p ^= b;
        a >>= 1;
        b <<= 1;
    }
    return p;
}

The problem is that its performance is dependent on the position of the highest bit in a. Thus with four bits at the top it runs at a poor 35% of your fixed coerced version
Testing Compare clmul(0xF000000, 1).
32Int coerced.: 0.520µs OPS 1,924,528 100% Total 530ms 1020 cycles
Shifting......: 1.497µs OPS 667,984  35% Total 1,467ms 980 cycles

But swap the arguments and the table is turned upside down out performing all other versions with ease.
function clmul_u32_b(b, a) {  // swapped args
    ... code see above snippet
    return p;
}

Results
Testing Compare clmul(0xF000000, 1).
Shifting swap.: 0.188µs OPS 5,324,813 100% Total 563ms 1000 cycles
32Int coerced.: 0.521µs OPS 1,918,526  36% Total 1,564ms 1000 cycles

You may think, why not add a line that swaps the arguments, ensuring that a is less than b allowing for the least number of shifts. This does not work. A JS statement will force a cache miss and you lose any benefit.
Conclultion
In terms of ease of use, readability (4+ years JS experience reader), and performance your coerced version with the extra line to force b to an int has in my view the best for all 3 criteria.
// includes the line b |= 0
function clmul_u32_coerced(a, b) {
    var prod = 0;
    b |= 0;
    while (a != 0) {
        prod ^= b * (a & -a);
        a &= a - 1;
    }
    return prod;
}

Though the shifting version I present can in a best case out perform by a factor of 3, the best case is rare and any code to select for best cases will result in an overall performance loss.
Notes on testing

A call is via a function that grouped function calls by 400 see below.
Calls are run in strict mode.
Calls have been allowed to run until optimisations complete (eg testing waits till times are stable before logging time)
Device and setup "Chrome Version 70.0.3538.102 (Official Build) (32-bit)" on a  "Win10 CPU i7 Q720 @1.6GHz" laptop

function call(a, b) {
    var i = 25;
    while (i--) {
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
    }
}

In javascript the performance landscape is in constant flux, browser version changes can have significant changes to performance comparisons, and not always positive. If performance is important than you must monitor performance for each browser update, and use code that is tuned for each browser's type.


Creating many random test database entries I'm working on a simple time sheet webapp. I have created the following query (simplified - I actually have several mapped columns of a similar type to project_id) to generate test data:

INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `date`, `comment`, `hours`)
VALUES
( null,
  0,
  (SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
  CURRENT_DATE(),
  '# TEST DATA #',
  (SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
);

I'm currently running this query inside a PHP loop.

This code is currently adequate for my needs now, as I can iterate 50 loops in 0.3037 seconds. However, I fear that when it comes time to test large data sets (searching and report generation for rows > 1 000 000), I may run into problems creating them.

How can I optimize this algorithm? Should I consider using a stored procedure? Or should I just not worry about it, and run the loop to longer iterations, more times?

DROP PROCEDURE IF EXISTS `create_test_entries`;

DELIMITER //

CREATE PROCEDURE `create_test_entries` (IN number INT)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY INVOKER
COMMENT 'Creates `number` of random test entries in the timesheet'
BEGIN
    DECLARE i INT;
    SET i = 0;

    WHILE i < number DO
        INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `department_id`, `task_id`, `date`, `comment`, `hours`)
        VALUES
        ( null,
          0,
          (SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
          CURRENT_DATE(),
          '# TEST DATA #',
          (SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
        );
        SET i = i + 1;
    END WHILE;
END //

It feels like (SELECT project_id FROM projects ORDER BY RAND() LIMIT 1) stands for "get random but still valid project_id". You could probably just iterate over all of your projects (with no randomness) and for every project add a random number of records. I don't think it affects your intention but this will probably work faster.


Animation of multiple text elements in sequence I feel like this isn't the most effective nor efficient way of doing things:

line.stop(true, true).show('slide', {direction: whichway}, speed-150, function() {
  title.stop(true, true).fadeIn(speed-200, function() {
    sub.stop(true, true).show('slide', {direction: whichway}, speed-50, function() {
      subtext.stop(true, true).show();
      paragraph.stop(true, true).slideDown(speed);
    });
  });
});

whichway/speed are dynamic, but other than that it's all stuff that has to be in sync and queued up.

Is there a more efficient way of doing this?

For readability, take advantage of jQuery methods that use the jQuery Deferred object to eliminate your deeply nested callback structure.
Example jQuery.when() can turn your code into this.

$.when({}).then(function(){
    return line.stop(true, true).show('slide', {direction: whichway}, speed-150);
}).then(function() {
    return title.stop(true, true).fadeIn(speed-200);
}).then(function() {
    return sub.stop(true, true).show('slide', {direction: whichway}, speed-50 );
}).then(function() {
    subtext.stop(true, true).show();
    return paragraph.stop(true, true).slideDown(speed);
});

Here's another example of using $.when: http://jsfiddle.net/Tp569/

Code from demo.

CSS:

.box{
    width: 10em;
    height: 10em;
    display:none;
}

HTML:

Box 1

Box 2

JS:

$.when({}).then(function(){
    return $("#box1").css("backgroundColor", "blue" )
        .fadeIn( "slow" ).delay(500).animate({
            opacity: 0.5,
            margin: '50'
        }, "slow").delay(1000);
}).then(function() {
    return $("#box2").css("backgroundColor", "yellow" ).fadeIn( "fast" );
});

For speed, try out animate.css, which is a pure css 3 base animation library.
If that's not enough then read this


Set default value for remaining size of list by use of Java 8 and Stream I have written a method which will return the size 16 List every time. If the input List has size less than 16, the remaining list object will be filled with default values.  Is there any way to remove the if and for condition from the enrichAddress method?.
@Component
public class TestService{

public List<TestB> enrichAddress(List<TestA> cardAccountDetails) {
if (CollectionUtils.isEmpty(cardAccountDetails)) return Collections.emptyList();

List<TestB> testBList = cardAccountDetails.stream().map(AccountService::buildAddress).collect(Collectors.toList());
if (testBList.size() < 16) {
  int accountCounts = testBList.size();
  for (; accountCounts < 16; accountCounts++) {
    testBList.add(buildDefaultAddress());
  }
}
return testBList;
}

private TestA buildDefaultAddress() {
TestA testA = new TestA();

testA.setA("NONE");
testA.setAccS("TEST_STATUS");

testA.setAccT("TEST_ACCOUNT_TYPE");
testA.setADes("");

return testA;
}

private static TestA buildAddress(TestB testB) {
TestA testA = new TestA();

testA.setDes(testB.getDes());
testA.setAcc(testB.getAcN());
testA.setAccSt(testB.getAccS());

testA.setAccT(testB.getAcCT());
testA.setAc(testB.getAct());

return testA;
 }
}

As mtj already mentioned in the comment, adding stream trickery to fulfill this need only makes the code less readable. Streams are nifty, exciting and popular but they are not always the right tool for the job. Sometimes a plain loop is still the best choice.
The common pattern in padding a collection (well, most often it's a string that gets padded) to certain size is to use a while loop. It has least amount of excess variables and code and the syntax communicates intent quite naturally ("while size is less than 16, do this"). But this still only tells that you are intentionally padding the collection to 16 elements. You also need to document in comments the reason why you are padding the collection to 16 elements.
List<Address> addresses = cardAccountDetails
    .stream()
    .map(AccountService::buildAddress)
    .collect(Collectors.toList());

while (addresses.size() < 16) {
    addresses.add(buildDefaultAddress());
}


Alternate for nested Ajax requests I have one button on clicking I need multiple things need to be done, so I went for AJAX and PHP:

$('.go_nxt_lsn').live('click',function(e){
    e.stopPropagation();
    var user_id = $('input[name=user_id]').val();
    var course_id = $('input[name=course_id]').val();
    var taskName = "SaveActivity";
    var subTask = "watchvideo";
    var lesson_id = $(this).attr('data-lesson-id');
    var video_id = $(this).attr('data-video-id');
    var course_box = '.course_'+course_id;
    var refresh_boo = 1;

    $.ajax({
        type        : 'POST',
        url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
        datatype    : 'html',
        data        : {subtask:subTask,lessonid:lesson_id,theSubModID:video_id,userid:user_id,prodid:course_id,taskname:taskName},
        success:function(data)
        {
            taskName = "GoToNextLesson"
            $.ajax({
                type        : 'POST',
                url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
                datatype    : 'html',
                data        : {subtask:subTask,lessonid:lesson_id,userid:user_id,prodid:course_id,taskname:taskName},
                success:function(data)
                {
                    $.ajax({
                        type        : 'POST',
                        url         : '<?php echo $vars['url']?>learn/pages/syllabus/learn.php',
                        datatype    : 'json',
                        data        : {user_id:user_id,course_id:course_id},
                        success:function(data)
                        {
                            $.ajax({
                                type        : 'POST',
                                url         : '<?php echo $vars['url']?>mod/event_calendar/views/default/event_calendar/instantlearn.php',
                                datatype    : 'html',
                                data        : {learn_details:data,refresh_boo:refresh_boo,prodid:course_id},
                                success:function(data)
                                {
                                    $(course_box).replaceWith(data);
                                    $(".accordion").accordion({
                                        active: false,
                                        collapsible: true,
                                        heightStyle: "content"
                                   });
                                }
                            });
                        }
                    });
                }
            });
        }
    });
});

I am sending four AJAX requests one by one, so I want an alternate for this. This code works fine. But this is so lengthy. Can anybody suggest how I can minimize it?

The chain of Ajax calls can be set programmatically, instead of being "hardcoded" as in your code. The next snippet shows a possible approach.

However, as Piotr pointed out, you should study your application a bit more to determine whether that is a good solution.

// First generate an array with all the ajax calls than need to be done, in order.
var ajaxCalls = [

    // First ajax
    function(){
        return $.ajax({
            type        : 'POST',
            url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
            datatype    : 'html',
            data        : {subtask:subTask,lessonid:lesson_id,theSubModID:video_id,userid:user_id,prodid:course_id,taskname:taskName}
        });
    },

    // Second ajax
    function(data){
        return $.ajax({
            type        : 'POST',
            url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
            datatype    : 'html',
            data        : {subtask:subTask,lessonid:lesson_id,userid:user_id,prodid:course_id,taskname:taskName}
        });
    },

    ...

    // Last function doesn't need to return a promise
    function(data){
        $(course_box).replaceWith(data);
        $(".accordion").accordion({
            active: false,
            collapsible: true,
            heightStyle: "content"
        });
    }
];

// Every time you run an ajax, you want to set it up so that the next
// ajax will be called as a response. Let's do a function for that:
function callAjax(var index){

    var thisAjax = ajaxCalls[index];

    // Run the ajax
    var promise = thisAjax();

    // Set up next one if necessary.
    var isLastAjax = (index === (ajaxCalls.length - 1));
    if(!isLastAjax){
        promise.done(function(){
            callAjax(index + 1);
        });
    }
}

// Call the first one
callAjax(0);


JavaScript Determine if Number is Lucky A challenge from Code Fights; a function that takes a number no less than 10 and that will always have an even number of digits and determines if the sum of the first half of the digits equals the sum of the second half of digits. The function returns a Boolean. Maximum execution time is 4000 milliseconds.

Here is the function:

// tickets are lucky when sum of first half equals sum of second half
const isLucky = n => {
  // min is 10 and we know it's false
  if (n === 10) return false;
  // store digits in an array
  const digitCorral = [];
  // use modulo, division and Math.trunc
  while (n > 0) {
    // push reverses the order but that doesn't matter
    // since the sum of each half will still be the same
    digitCorral.push(n % 10);
    n /= 10;
    n = Math.trunc(n);
  }
  // get sum of first half of array
  const firstHalf = digitCorral
    .slice(0, digitCorral.length / 2)
    .reduce(function(a, b) {
      return a + b;
    });
  // get sum of second half of array
  const secondHalf = digitCorral
    .slice(digitCorral.length / 2, digitCorral.length)
    .reduce(function(a, b) {
      return a + b;
    });
  // return a boolean
  return firstHalf === secondHalf;
};

The function passes all tests, however, I wonder if there is an even more efficient way write it--would recursion be faster? Can the speed of this algorithm be improved?

Bad storage and time

Your code solves the problem but is a memory hog.

Algorithm complexity

You are looping over the digits twice, once to extract each digit, and then once to sum each half. The logic can be improved if you calculate the sums as you extract each digit. This also means you do not have to store each digit in the array for the sum calculations.

If you include the two Array.slice calls that is a total of 3 iteration of each digit in n and two stored copies of each digit.

JavaScript performance

In terms of JavaScript performance array functions that take callbacks, like Array.reduce, have a high per iteration overhead when compared to standard loops. When the inner code is small that overhead is a significant part of the overall iteration time.

Array.slice should only be used when you need a copy of items in a new array. (Note items that are references only copy the reference. IE shallow copy).

Arrays in JavaScript are expensive in terms of performance because they do not get space from the heap but rather invoke the memory management system for allocation and disposal.

Code style

Never create un-delimited blocks. if (n === 10) return false; should be if (n === 10) { return false; } or if (n === 10) { return false }
The reduce callback is written in the long form, .reduce(function(a, b) { return a + b }) it would be less noisy to write it as .reduce((a, b) => a + b)
Too many comment, and one that conflicts with the code (a lie).

Apart from that the code is well formatted, has good naming, and good use of variable declaration type.

Your question

  would recursion be faster?

Seldom is recursion faster. Recursion is used to simplify state stack management, the function call is the state push, and return the state pop.

Until tailcalls are implemented in JavaScript, functions that are O(1) storage, become O(n) storage if converted to recursive solutions. There is no time complexity change. The solution is a O(1) storage problem and thus will not benefit from recursion.

  I wonder if there is an even more efficient way write it

Yes there is, see bottom rewrite.

Rewrites

Using your algorithm and API use.

Comment are only added as I am not sure if you recognize the code or why.

The test for 10 is not worth the cost [1]

const isLucky = n => {
    const sum = (a, b) => a + b; // minor memory/parse gain with one rather than two functions
    const digitCorral = [];
    while (n > 0) {
        digitCorral.push(n % 10);
        n = n / 10 | 0;  // Bitwise OR 0 is the faster form of Math.trunc
    }
    const first = digitCorral
        .slice(0, digitCorral.length / 2)
        .reduce(sum);
    const second = digitCorral
        .slice(digitCorral.length / 2)
        .reduce(sum);
    return first === second;
}

A better way.

Improved with O(1) storage, O(n) complexity where n is the number of digits in argument n

const isLucky = n => {
    var midDigit, n1, sum1 = 0, sum2 = 0;
    midDigit = (Math.log10(n) + 1 | 0) >> 1;
    const midMod = 10 ** midDigit;
    n1 = n / midMod | 0;
    n %= midMod;
    while (midDigit --) {
        sum1 += n % 10;
        sum2 += n1 % 10;
        n = n / 10 | 0;
        n1 = n1 / 10 | 0;
    }
    return sum1 === sum2;
}

1. The following calculations are orders of magnitude approximations only. The early exit test for 10 (about 1/100 operations) is only worth the CPU time if there is a high probability of 10. That's a cost of 1% of operations, for gain of 1e-7%. The gain should always outweigh the cost by at least one order.
 That will only happen when 10 is about 100Million times more likely than any other number


Point inside Polygon check I have written a method to determine whether a Vector2 lies inside a polygon or outside of it. The polygon is defined by an array of clockwise vertices, p[]. It returns true if the point is inside, false otherwise.

public bool polyCheck(Vector2 v, Vector2[] p)
{
    int j = p.Length-1;
    bool c = false;
    for(int i=0;i<p.Length;j=i++)c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;
    return c;
}

It is perfectly functional, works with all edge cases, and is blazing fast. I want to know how I could make the method look prettier, and have better 'coding practices' though.

I want to know how I could make the method look prettier, and have better 'coding practices' though

avoid single letter variable if they aren't iterator variables. If you or Sam the maintainer needs to come back to this method in a few months, neither you nor Sam will grasp at first glance what the variables are about.
avoid shortening of method names. polyCheck does not tell anything about what the method tries to do. A name like IsInPolygon would be better. With a more OO approach by adding a Polygon class having a method Contains(Vector2) it would be more clear.

public class Polygon
{
    public Vector2[] Vertices { get; private set; }
    public Polygon(Vector2[] vertices)
    {
        Vertices = vertices;
    }
    public bool ContainsVector(Vector2 vector)
    {
        // do the magic
        return true;
    }
}

always use braces {} although they are optional for single lined for's. This will help you to make your code less error prone.
let your variables and operators have some space to breathe. This

c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;

is just not readable.


Convert plain text to HTML C# I have the ToHtml() Extension Method

public static class StringMethodExtensions
{
    private static string _paraBreak = "\r\n\r\n";
    private static string _link = "{1}";
    private static string _linkNoFollow = "{1}";

    ///
    /// Returns a copy of this string converted to HTML markup.
    ///
    public static string ToHtml(this string s)
    {
        return ToHtml(s, false);
    }

    ///
    /// Returns a copy of this string converted to HTML markup.
    ///
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    public static string ToHtml(this string s, bool nofollow)
    {
        StringBuilder sb = new StringBuilder();

        int pos = 0;
        while (pos < s.Length)
        {
            // Extract next paragraph
            int start = pos;
            pos = s.IndexOf(_paraBreak, start);
            if (pos < 0)
                pos = s.Length;
            string para = s.Substring(start, pos - start).Trim();

            // Encode non-empty paragraph
            if (para.Length > 0)
                EncodeParagraph(para, sb, nofollow);

            // Skip over paragraph break
            pos += _paraBreak.Length;
        }
        // Return result
        return sb.ToString();
    }

    ///
    /// Encodes a single paragraph to HTML.
    ///
    /// <param name="s">Text to encode</param>
    /// <param name="sb">StringBuilder to write results</param>
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    private static void EncodeParagraph(string s, StringBuilder sb, bool nofollow)
    {
        // Start new paragraph
        sb.AppendLine("
");

        // HTML encode text
        s = HttpUtility.HtmlEncode(s);

        // Convert single newlines to

        s = s.Replace(Environment.NewLine, "
\r\n");

        // Encode any hyperlinks
        EncodeLinks(s, sb, nofollow);

        // Close paragraph
        sb.AppendLine("\r\n
");
    }

    ///
    /// Encodes [[URL]] and [[Text][URL]] links to HTML.
    ///
    /// <param name="text">Text to encode</param>
    /// <param name="sb">StringBuilder to write results</param>
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    private static void EncodeLinks(string s, StringBuilder sb, bool nofollow)
    {
        // Parse and encode any hyperlinks
        int pos = 0;
        while (pos < s.Length)
        {
            // Look for next link
            int start = pos;
            pos = s.IndexOf("[[", pos);
            if (pos < 0)
                pos = s.Length;
            // Copy text before link
            sb.Append(s.Substring(start, pos - start));
            if (pos < s.Length)
            {
                string label, link;

                start = pos + 2;
                pos = s.IndexOf("]]", start);
                if (pos < 0)
                    pos = s.Length;
                label = s.Substring(start, pos - start);
                int i = label.IndexOf("][");
                if (i >= 0)
                {
                    link = label.Substring(i + 2);
                    label = label.Substring(0, i);
                }
                else
                {
                    link = label;
                }
                // Append link
                sb.Append(String.Format(nofollow ? _linkNoFollow : _link, link, label));

                // Skip over closing "]]"
                pos += 2;
            }
        }
    }
}

Do you see any improvement / issue?

public static string ToHtml(this string s, bool nofollow)
{
    s = HttpUtility.HtmlEncode(s);
    string[] paragraphs = s.Split(new string[]{"\r\n\r\n"}, StringSplitOptions.None);
    StringBuilder sb = new StringBuilder();
    foreach (string par in paragraphs) {
        sb.AppendLine("
");
        string p = par.Replace(Environment.NewLine, "
\r\n");
        if (nofollow) {
            p = Regex.Replace(p, @"\[\[(.+)\]\[(.+)\]\]", "$1");
            p = Regex.Replace(p, @"\[\[(.+)\]\]", "$1");
        } else {
            p = Regex.Replace(p, @"\[\[(.+)\]\[(.+)\]\]", "$1");
            p = Regex.Replace(p, @"\[\[(.+)\]\]", "$1");
            sb.AppendLine(p);
        }
        sb.AppendLine("
");
    }
    return sb.ToString();
}

In general, if you find yourself with a variable that you pass around through a bunch of static methods (like nofollow), it may be time to make those methods not static.


Majorly refactored my code, is this good enough? namespace SharpDream.Api
{
    public enum SourceType
    {
        Test,
        Xml
    }

    public class UserFinder
    {
        private IUserInformationSource _sourceType;
        private IParser _parserType;
        private string _source;

        public UserFinder(SourceType sourceType)
        {
            switch (sourceType)
            {
                case SourceType.Test:
                    var testSource = new TestSource();
                    _sourceType = testSource;
                    break;
                case SourceType.Xml:
                    var xmlSource = new XmlSource();
                    var xmlParser = new XmlParser();
                    _sourceType = xmlSource;
                    _parserType = xmlParser;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// Returns a User object loaded with information.
        /// </summary>
        /// <param name="forumUserId">The DIC forum users ID number.</param>
        /// <returns>A User object.</returns>
        public User GetUserById(int forumUserId)
        {
            _source = _sourceType.GetResponseSource(forumUserId);
            return _parserType.ParseUserFromSource(_source);
        }
    }
}

What I'm aiming for:

Separation of concerns. Which is working believe it or not! It's so refreshing to feel confident that your code won't break if you change something somewhere else. I finished this bit, and now I can work on the parsing area without having to put anything else in the mental buffer.
Flexibility during usage.

Here is an example of how my library will be used:

UserFinder userFinder = new UserFinder(SourceType.Xml);
var foundUser = userFinder.GetUserById(1);

Compare this to the old version of the library:

//Let's create an XmlMemberFinder, since we'll use the XML api as our data source.
XmlMemberFinder xmlMemberFinder = new XmlMemberFinder();

//MemberList is the class you'll use in your application to get anything you need
//relating to members.
MemberLister memberList = new MemberLister(xmlMemberFinder);

//This is an example of fetching and listing a user.
var member = memberList.FindMember(1);

I think I have made improvements, but there is always someone smarter out there. :)

Thanks for your time!

Personally I'd make the UserFinder class source-independent.
This could be either by seeing the Xml and Test sources as a mapper and the UserFinder as a model (some kind of DataMapper):

public interface UserMapperInterface {}
public class XmlSource : UserMapperInterface { // ... }
public class TestSource : UserMapperInterface { // ... }

public class UserFinder {
     public UserFinder(UserMapperInterface $source) { // ... }
     public UserFinder() { // use default source }
}

This way you make the GetUserById method source-independent. Basic usage would be:

UserFinder t = new UserFinder(new TestSource());
// UserFinder t = new UserFinder(); // using the default source
t.GetUserById(43);

This way you seperate the source logic from the operations and you can easily add new sources without touching the UserFinder class.


196-Algorithm Program Attempting to see whether using 196 as a respectively in my program will have a result or not, I made a simple function to test it. Now the 196-Algorithm requires this:

Take any positive integer with at least two digits, a
Take a and reverse it (for example 23 becomes 32)
Now add the new number to a
Repeat the process until the a is a palindrome (when reversed, a palindrome's value should still be the same)

This is my function:

def one_nine_six_algorithm(a):
    b = a
    if a > 9:
        while str(b)[::-1] != str(b):
            c = str(b)[::-1]
            b += int(c)
        return b

In this program, I literally did how do the algorithm. The integer, a, is taken in and checked that it is a positive, two-digit number. Then, the algorithm is run in the while loop, where b is the new/current value of a and c is basically b reversed but as a string  in able to use [::-1]. Then c as an integer (int(c)) is added to b and is continued until b is a palindrome (checked in the while line). Then it returns b, which is used for whatever reason I need it for.

Now for complicated integers, this might go through a lot of loops and take a lot of time to finish. Is there a more efficient way to improve my program in terms of speed and readability?

Why bother renaming a to b?

This function would be more useful as a generator, because you will be interested in finding the next number in the sequence.  That is, you should yield rather than return the result.

You wrote str(b) three times.  Once would be better, but that would still be once too many, if you care about performance.  Keep in mind that stringifying a number involves allocating an object, some buffer space, some arithmetic, and translation to ASCII behind the scenes.  A function to compute the reversed integer yourself, even if it involves writing more code, should be faster.


Finding the longest string and its length using Java streams Java 8 streams are my new golden hammer that I try to use as often as possible with often enormous gains in brevity and readability. Getting multiple return values, such as a maximum value and its associated element, is a bit cumbersome though (and requires an additional "pair" class).

Should I go back to "normal Java" for this task or is this syntax preferable? Is there a more concise way?

List<String> names = Arrays.asList("John","Paul","Ringo");
Pair<String,Integer> longestName = names.stream()
 .map(n->new Pair<>(n,n.length())) // pretend n.length() to be a lengthy operation
 .max(Comparator.comparing(Pair::getB)).get();
System.out.println(longestName.getA()+" "+longestName.getB());

P.S.: With "lengthy operation" I mean long running, as in I don't want to calculate it twice.

You don't need the Pair.  You can get the String with the maximum length by doing

names.stream().max(Comparator.comparingInt(String::length))


Script to generate documents based on conditionals and CSV data I wrote this script a while back to generate press releases. It consumes a csv of data where each row contains the data for a country and fills in values in pre-written text based on the data. In its current state, it's basically a mad libs implementation with some hard coded conditionals. I'd like to refactor it to make it a bit smarter. I had the following ideas:

create separate methods for static text paragraphs, paragraphs with conditionals and paragraphs with complex conditionals. How would I do this without constructing methods that take too many complicated arguments?
use the NLTK for parsing plurals and verb tenses.
Put this entire script into a Django app so that I don't have to do the tweaks myself every time they want new press releases.

An abbreviated version of the script is below. I also welcome any changes to make it more Pythonic.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
import sys
import csv
from docx import Document

def generate_documents():
    with open(sys.argv[1], 'rb') as csvdata:
        reader = csv.DictReader(csvdata)
        timestamp = "output/" + datetime.datetime.now().strftime('%d-%m-%Y_%H-%M-%S')
        os.makedirs(timestamp)
        os.chdir(timestamp)
        for row in reader:
            document = Document()
            name = row['country'].decode('cp1252') + ".docx"

            embargo = u"EMBARGOED FOR RELEASE UNTIL {0}, DECEMBER {1} at {2} ({3})".format(row['weekday'], row['day'], row['time'], row['capital'].decode('cp1252').upper())

            headline = "Colored Walls Gain International Popularity"

            subheadline = u" {0} walls become common in {1}, citiznes think this development is {2}".format(row['color'], row['country'].decode('cp1252'), row['adjective'])

            if row['country'].decode('cp1252') == "Andorra" or row['country'].decode('cp1252') == "Canada" or row['country'].decode('cp1252') == "Zimbabwe" or row['country'].decode('cp1252') == "Qatar" or row['country'].decode('cp1252') == "Gabon":
                cond_para_1 = u"{0} – Today, fewer people are painting walls {1} in {2}, according to a new, comprehensive analysis of trend from 188 countries.".format(row['capital'].decode('cp1252').upper(), row['color1'], row['country'].decode('cp1252'))
            else:
                cond_para_1 = u"{0} – Today, fewer people are painting walls {1} and {2} in {3}, according to a new, comprehensive analysis of trend from 188 countries. ".format(row['capital'].decode('cp1252').upper(), row['color1'], row['color2'], row['country'].decode('cp1252'))

            static = "Everyone thinks this is very exciting"

           if row['bestColor'] == "yellow":
               cond_para_2 = "Shockingly, residents of {0} prefer yellow walls.".format(row['country'].decode('cp1252'))
           else:
               cond_para_2 = "Most of the world likes white walls."

            # add the content to the document
            document.add_paragraph(embargo)
            document.add_paragraph().add_run(headline).bold = True
            document.add_paragraph().add_run(subheadline).italic = True
            document.add_paragraph(cond_para_1)
            document.add_paragraph(static)
            document.add_paragraph(cond_para_2)
            document.save(name)

generate_documents()

Instead of decoding each field within the CSV as CP1252, you should open the entire file that way.

I think that you should approach this more as a templating problem than a document-generation problem.  Templating is a challenge that has been solved many times before — though mainly generating HTML rather than OOXML.  Authoring OOXML directly looks like it would be a pain though.  Perhaps you would be better off using a templating solution (Django has one built in) to produce semantically correct HTML as an intermediate format.  Then, you can convert the HTML into DOCX using one of many such tools available, involving Python or not.

Basically, that strategy would decompose one programming headache into two solved problems.


Counting inversions with merge sort I am piggybacking an iterator-based implementation of merge-sort to count array inversions. My first correct solution looks as follows:

#include <vector>
#include <iterator>
#include <stdio.h>

template<typename It>
std::vector<typename It::value_type> SortAndCountInversionsSubroutine(const It begin, const It middle, const It end, unsigned int& count)
{
    std::vector<typename It::value_type> v;
    It left{ begin }, right{ middle };
    while (left != middle && right != end)
    {
        if (*left <= *right)
        {
            v.push_back(*left++);
        }
        else
        {
            count+= std::distance(left, middle);
            v.push_back(*right++);
        }
    }
    v.insert(v.end(), left, middle);
    v.insert(v.end(), right, end);
    return v;
}

template<typename It>
void SortAndCountInversions(It begin, It end,unsigned int& count)
{
    auto size = std::distance(begin, end);
    if (size < 2)
        return;
    auto mid = std::next(begin, size / 2);
    SortAndCountInversions(begin, mid, count);
    SortAndCountInversions(mid, end, count);
    auto v = SortAndCountInversionsSubroutine(begin, mid, end, count);
    std::move(v.cbegin(), v.cend(), begin);
}

The implementation can be used as follows:

std::vector<int> v1{ 1, 3, 5, 2, 4, 6 };
unsigned int inversionCount = 0;
unsigned int expectedCount = 3;
SortAndCountInversions(v1.begin(), v1.end(), inversionCount);
Assert::AreEqual(expectedCount, inversionCount);

inversionCount = 0;
expectedCount = 5;
std::vector<int> v2{ 1, 20, 6, 4, 5 };
SortAndCountInversions(v2.begin(), v2.end() , inversionCount = 0);
Assert::AreEqual(expectedCount, inversionCount);

I am looking for any suggestions to improve my code. Particularly, I would like to return the inversion count as a return value, instead of a parameter reference. Any ideas?

Looks nice and clean.

One thing to note:

With Iterators Const Iterator is not the same as Iterator_Const. The first means you will not change the iterator while the second means you will not change what the iterator points at. You actually want to mean the second the first one is rarely useful.

<ReturnType> SortAndCountInversionsSubroutine(
                 const It begin, const It middle, const It end,
            //   ^^^^^           ^^^^^             ^^^^
                 unsigned int& count)

That's not a very useful const.
Just use:

template<typename It>
// When C++ concepts get added just uncomment the line below.
// requires std::is_const<typename std::iterator_traits<It>::reference_type>::value
<ReturnType> SortAndCountInversionsSubroutine(
                 It begin, It middle, It end,
                 unsigned int& count)

I "might" change this:

auto v = SortAndCountInversionsSubroutine(begin, mid, end, count);
std::move(v.cbegin(), v.cend(), begin);

I might move the std::move() into the SortAndCountInversionsSubroutine() the trouble with that is you need to change the iterators from being iterator_const (once you have fixed the first point) to non const. The advantage of course is that you don't have to return a vectorfrom a function.


Variable to byte decaying function A function that prints out the values of each of the bytes of a variable, which value is given from stdin.
Consists of size detector and a loop.

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

int main(void)
{
    unsigned char uint_8;
    unsigned short uint_16;
    unsigned long uint_32;
    unsigned long long uint_64, n = 0;

    int i;
    size_t size;

    printf("Enter a number: ");
    scanf("%lld", &n);

    if(n < 257) size = 1;
    if(n < 256*256 && n > 256) size = 2;
    if(n < 256*256*256 && n > 256*256) size = 3;
    if(n < pow(256, 4) && n > pow(256, 3)) size = 4;

    for(i = 0; i < size; i++)
    {
        unsigned char* p = (((unsigned char*)&n) + i);
        printf("byte(%i) : %i\n", i, *p);
    }

    return 0;
}

I don't like the size detection though, it could be more safely coded with one line of bit operations I believe.

A couple of remarks:

You should check the return value of scanf. It returns the number of items successfully converted. You initialize n with 0 so any invalid input will yield in a single 0 output but it might be good to indicate failure anyway.
Using EXIT_SUCCESS and EXIT_FAILURE are more portable ways to indicate success/failure upon return to the OS.
256 is is not representable by an 8-bit type. The binary representation is 1 0000 0000 - so the 9th bit is set. An 8 bit unsigned type can only hold 0 - 255.
Multiplying an integer by a power of 2 can be done by a left-shift. So 2^5 for example is 1 << 5 - this eliminates any need for multiplication or even invoking pow.
You print out the order of bytes in big endian notation (the highest ordered byte is printed out with the smallest index) while for example x86 is a little endian architecture where the lowest ordered byte has the smallest index. Actually scratch that. The data in memory is laid out little endian so your code will print it in little endian order.
Your size detection works on the assumption that a char is 8 bit. This is not guaranteed by the C standard which requires CHAR_BIT to be at least 8. For example there DSPs where CHAR_BIT is 16 and in the past there were architectures with 9 and 12 bit bytes.
Your size detection only goes up to 4 bytes however unsigned long long is 8 bytes on many platforms. So if someone puts a large number in the it will simply omit the upper 4 bytes.

In the end the size detection can be generalized by finding which byte is the most significant byte - which boils down to finding the most significant bit (the highest bits which is 1). There are a bunch of clever operations to make this really fast but the simplest is to shift right until all set bits are shifted out:

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

int main(void)
{
    unsigned long long n = 0;
    unsigned long long temp;
    int most_significant_bit = 0;
    int most_significant_byte = 0;
    int i;

    printf("Enter a number: ");
    if (scanf("%lld", &n) != 1)
    {
        printf("Invalid number entered.");
        return EXIT_FAILURE;
    }

    temp = n;
    while (temp >>= 1)
    {
        ++most_significant_bit;
    }
    most_significant_byte = (most_significant_bit / CHAR_BIT) + 1;

    for(i = 0; i < most_significant_byte; i++)
    {
        unsigned char* p = (((unsigned char*)&n) + i);
        printf("byte(%i) : %i\n", i, *p);
    }

    return EXIT_SUCCESS;
}


Getting column values from a datatable Is there a way I can make the code compact and with fewer ifs?

theData = GetData();
if (theData.Rows.Count > 0)
{
    MyModel = new CustomModel();
    dataSetRow = theData.Rows[0];
    if (theData.Columns.Contains("Column1"))
    {
        if ((!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value)))
        {
            MyModel.Column1 = Convert.ToString(dataSetRow["Column1"]);
        }
    }
    if (theData.Columns.Contains("Column2"))
    {
        if ((!object.ReferenceEquals(dataSetRow["Column2"], DBNull.Value)))
        {
            MyModel.Column2 = Convert.ToString(dataSetRow["Column2"]);
        }
    }
    if (theData.Columns.Contains("Column3"))
    {
        if ((!object.ReferenceEquals(dataSetRow["Column3"], DBNull.Value)))
        {
            MyModel.Column3 = Convert.ToString(dataSetRow["Column3"]);
        }
    }
    if (theData.Columns.Contains("Column4"))
    {
        if ((!object.ReferenceEquals(dataSetRow["Column4"], DBNull.Value)))
        {
            MyModel.Column4 = Convert.ToString(dataSetRow["Column4"]);
        }
    }

Useful property names:

I find using names as theData bad practice. It doesn't give any info on the instance. Give it a useful name you, and others, easily understand.

Casing of property names:

Don't use PascalCase for local fields, use camelCase instead. Your MyModel will become myModel. You had already done this correctly for dataSetRow.

Redundant parentheses:

Following:

if ((!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value)))

can be replaced by:

if (!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value))

There's no need to encapsulate the whole expression again in parantheses.

Simplifying the code:

Finally, the important part! :) There's only one way I can think of to achieve this: reflection. I created following extension method to get the PropertyInfo of your instance (note that it doesn't have to be placed in an extension method, I only think it looks cleaner and is good for reusability elsewhere if needed):

public static class Extensions
{
    public static PropertyInfo GetProperty<T>(this T obj, string propertyName) where T : class
    {
        return typeof(T).GetProperty(propertyName);
    }
}

The above allows you to do following (get a property by it's name-value):

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }
}

var user = new User { ID = 1, Name = "Simsons" };
var nameProp = user.GetProperty("Name");

And now you can get and/or set the value of that property using the GetValue() or SetValue() methods:

nameProp.SetValue(user, "Abbas", null);

With this in mind, add following changes to your code:

place all your column names in an array over which you will loop
simplify your code using the reflection part

Here's your code with the above applied:

theData = GetData();

if (theData.Rows.Count > 0)
{
    myModel = new CustomModel();
    dataSetRow = theData.Rows[0];
    var columnNames = new [] { "Column1", "Column2", "Column3", "Column4" };

    foreach(var columName in columnNames)
    {
        if(theData.Columns.Contains(columName))
        {
            if (!object.ReferenceEquals(dataSetRow[columName], DBNull.Value))
            {
                var columnProperty = myModel.GetProperty(columName);
                columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[columnName], null);
            }
        }
    }
}

Update:

As RobH stated in the comments, you can use LinQ to avoid nested if statements. Here's how your code would look like:

var columnNames = new [] { "Column1", "Column2", "Column3", "Column4" };

foreach(var existingColumn in columnNames.Where(x => theData.Columns.Contains(x)))
{
    if (!object.ReferenceEquals(dataSetRow[existingColumn], DBNull.Value))
    {
        var columnProperty = myModel.GetProperty(existingColumn);
        columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[existingColumn], null);
    }
}

You can even take it a final step further to avoid any if statement:

var validColumns = columnNames.Where(x => theData.Columns.Contains(x) &&
                                          !object.ReferenceEquals(dataSetRow[x], DBNull.Value)))

foreach(var column in validColumns)
{
    var columnProperty = myModel.GetProperty(existingColumn);
    columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[existingColumn], null);
}


Old and new shouts controllers I have a photo_shouts_controller.rb and text_shouts_controller.rb which both have almost similar implementations, and I would like to refactor it.

I have implemented a refactoring but I am not too sure if that is the best way to do it.

Current implementation

class PhotoShoutsController < ApplicationController
  def create
    content = build_content
    shout = current_user.shouts.build(content: content)

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def build_content
    PhotoShout.new(photo_shouts_parameters)
  end

  def photo_shouts_parameters
    params.require(:photo_shout).permit(:image)
  end
end

class TextShoutsController < ApplicationController
  def create
    content = build_content
    shout = current_user.shouts.build(content: content)

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def build_content
    TextShout.new(text_shouts_parameters)
  end

  def text_shouts_parameters
    params.require(:text_shout).permit(:body)
  end
end

My new implementation

ShoutBuild.rb

class ShoutBuild
  def initialize(current_user, shout_parameters, shout_class)
    @shout_parameters = shout_parameters
    @shout_class = shout_class
    @user = current_user
  end

  def build
    content = build_content
    @user.shouts.build(content: content)
  end

  private

  def build_content
    @shout_class.new(@shout_parameters)
  end
end

Controllers

class TextShoutsController < ApplicationController
  def create
    shout = ShoutBuild.new(current_user, text_shouts_parameters, TextShout).build

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created'
    end
  end

  private

  def text_shouts_parameters
    params.require(:text_shout).permit(:body)
  end
end

class PhotoShoutsController < ApplicationController
  def create
    shout = ShoutBuild.new(current_user, photo_shouts_parameters, PhotoShout).build

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def photo_shouts_parameters
    params.require(:photo_shout).permit(:image)
  end
end

By moving the build statement into a service you actually aren't saving yourself much, even after the refactor you still have a bunch of code that isn't DRY. Depending on how big your application is I would move pretty much all of the logic for your create actions into either ApplicationController, or, more likely a module. The module could look like this:

module ShoutController
  def create
    shout = current_user.shouts.build(content: build_content)
    redirect_params = shout.save ? {} : {notice: 'not created'}
    redirect_to dashboard_path, redirect_params
  end
end

Then your controllers would simply be:

class PhotoShoutsController < ApplicationController
  include ShoutController

  private

  def build_content
    PhotoShout.new(params.require(:photo_shout).permit(:image))
  end
end

And

class TextShoutsController < ApplicationController
  include ShoutController

  private

  def build_content
    TextShout.new(params.require(:text_shout).permit(:body))
  end
end


Rendering JSON arrays of unequal length as a table I have a website where my users can create "table-like" layout dynamically. So imagine that my users can upload a text document, and then append columns to the document, and the output will then be parsed into a table-like layout.

For example:

My text document              Date: 20-06-2019                Created by: OJN

Content                       Nice Document                   Very!

Content                       Indeed!

                              Even more!

Now imagine that this is a word document for example, and my users have defined two columns on above (right between each block of text). This would output:

{
   "1":[
      {
         "row":"My text document"
      },
      {
         "row":"Content"
      },
      {
         "row":"Content"
      }
   ],
   "2":[
      {
         "row":"Date: 20-06-2019"
      },
      {
         "row":"Nice Document"
      },
      {
         "row": "Indeed!"
      },
      {
         "row": "Even more!"
      }
   ],
   "3":[
      {
         "row":"Created by: OJN"
      },
      {
         "row":"Very!"
      }
   ]
}

As you can see, this will ultimately generate three array objects with unequal elements.

0: Array(3)
1: Array(4)
2: Array(2)

Now when presenting this for the user in the frontend, I wish to show the parsed text content in a table, like: this

        {{cell["row"]}}

However, as said, the arrays are of unequal length - so if I "just" transpose them, it will not generate the desired output. Instead, in above example, it will only create 3 rows in my table, because the first array contains 3 elements.

So in order to overcome this, I check the arrays to find the largest one:

// Transform object in array of its values
let data = Object.values(content);
let colsLength = data.map(r => r.length);
let maxNumCols = Math.max.apply(Math, colsLength);
let recordArraySchema = Array.apply(null, Array(maxNumCols)).map((r, i) => i);

this.dataTable = recordArraySchema.map((col, i) => data.map(row => row[i]));

This way, the array transposing will transpose all "rows", and fill the "empty"/non-existing will null, resulting in a full table.

I was wondering if this approach is acceptable in terms of performance and readability? I do have the option to change the JSON string format all together on the backend if that is more appropriate. However, I do have other backend functions that relies on the current schema, so those would have to be updated as well.

The first thing I noticed is that the format of the data is a collection of columns with rows. The variable maxNumCols seems mis-leading. A more appropriate name for that variable would be maxNumRows because it describes how many rows are needed.

In terms of reducing the transformations needed, one option to consider is finding the maximum number of rows in a column and using that with v-for _with a Range to determine how many rows to add. Then looping over the content would eliminate the need to create recordArraySchema and dataTable - which would reduce the complexity from \$O(n^2)\$ to just \$O(n)\$.

        {{column[r - 1].row}}

Obviously this would require saving maxNumRows in the data collection.

Instead of using Function.apply() the spread syntax can be used to determine the maximum number of rows.

const rowLengths = data.map(r => r.length);
this.maxNumRows = Math.max(...rowLengths);

And instead of using let for variables that are only assigned once, it is wise to use const and then if it is determined that it needs to be re-assigned, use let. This helps avoid accidental re-assignment.


Calculating months elapsed since a given date I am using traceview and DDMS to analyse my operation.  The following is my traceview as displayed in DDMS:

According to the above, the LoaderClass.months() function takes about 51% of the CPU time and 798.80 System time.  I have reproduced this function below:

public int months(String date) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        try {
            d1 = f.parse(date);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        Date d2 = new Date();
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);
        int diff = 0;
        if (c2.after(c1)) {
            while (c2.after(c1)) {
                c1.add(Calendar.MONTH, 1);
                if (c2.after(c1)) {
                    diff++;
                }
            }
        } else if (c2.before(c1)) {
            while (c2.before(c1)) {
                c1.add(Calendar.MONTH, -1);
                if (c1.before(c2)) {
                    diff--;
                }
            }
        }
        return diff;
    }

Below is a more detailed view of the method as on DDMS:

Don't reinvent the wheel for what Joda time has already written for you:

int monthsBetween = Months.monthsBetween(new LocalDate(date1), new LocalDate()).getMonths();

From the localDate doc:

You can pass a string in the constructor. (you could test that)
Empty constructor is current time.


Read binary file by blocks I wrote a function that allow me to read a binary file using 3 blocks what ever the length of file.

I've decided to divide the length of my file into 3:

  block 1: ______________

  block 2: ______________

  block 3: ____

As you can see, this is almost the length of the 3 blocks that I will have using my function.

(What is important for me is to read all characters in my file)

vector< vector<char> >  ReadByBlock(string fileName){

ifstream is (fileName, ifstream::binary);

if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

cout << "Reading " << length << " characters... "<<endl;
const int bloc = 1+length/3;
vector< vector<char> > vect (3,vector<char>(bloc,0));      // create vector of 3 vector of(1+length/3) chars with value 0

    for(size_t j=0;j<3;++j)
    {
        is.read(&vect[j][0], bloc);
        for(size_t i=0;i<bloc;++i)
            cout << " buf ["<<j<<","<<i<<"]: "<<vect[j][i] << endl;
    }

 return vect;}}

Because I'm beginner in the world C++ and because I'm thinking about Java while programming my function, I want to know if it is an efficient function that respects the rules of C++ as well the structure of coding using C++.

using namespace std

Since none of the standard library features you use are prefixed by std::, I will assume that you have using namespace std; somewhere. Actually, you should avoid using namespace std; and fully qualify the standard library functions and classes with std:: instead. Your code won't be much longer, and you may avoid potential problems such as name clashes.

Use std::array

One thing that can be noticed is that you know that you will return a collection of exactly three std::vector<char>. You know the size at compile time, therefore you don't need a dynamic container, a fixed-sized one is enough. Let's make that explicit and have your function return an std::array<std::vector<char>, 3> instead.

Check for potential errors

ifstream is (fileName, ifstream::binary); is great. It's how it should be used. However, it may fail, for example if the file fileName does not exist. You should check whether such an error occured before resuming the function:

std::ifstream is (fileName, std::ifstream::binary);
if (not is)
{
    // handle errors (e.g. throw an exception)
}

Note that operator! (here not) is used to check for errors. If it yields false, it means that an error occured when opening the std::ifstream.

Accessing a std::vector underlying array

You used the C++98 way &vec[0] to get the underlying array of an std::vector. Actually, when reading code, knowing what it does can be pretty hard, and that's partly due to the order of evaluation of the operators that may not be obvious for everyone. You can use vec.data() instead. This method was not available for std::vector before C++11, and that's probably why you found the solution &vec[0].


Sorting an integer array using heap sort I have written this program to sort an array using heap sort. Please review it for further improvements.

public static void main(String[] args) {

    int arr[] = {14, 70, 51, 16};

    System.out.println("Input Array : " + Arrays.toString(arr));

    buildMaxHeap(arr, arr.length);

    System.out.println("Max Heap Order : " + Arrays.toString(arr));

    heapSort(arr);

    System.out.println("Sorted Array : " + Arrays.toString(arr));
}

private static void buildMaxHeap(int[] arr, int len) {
    // any nodes after n/2 are leaves node and could be without children
    for (int i = (len) / 2; i >= 0; i--) {
        // bubble up to build max heap
        bubbleUp(arr, i, len - 1);
    }
}

private static void heapSort(int[] arr) {
    // now run the sort process
    for (int j = arr.length - 1; j >= 0;) {
        // bubble up the nodes so that tree can satisfy the max heap
        // property
        // i.e any Node B <= to its Parent Node A.
        // This swap method will shift lower to down and higher to up.
        swap(arr, j, 0);
        // decrement the size of heap so that previous max value stays in
        // place
        j = j - 1;
        // now bubble up again from 0 to (heap -1) j
        // means put the heap back.
        bubbleUp(arr, 0, j);
        System.out.println("Sorted Array : " + Arrays.toString(arr));
    }
}

private static void bubbleUp(int[] arr, int start, int end) {
    // set the root to start
    int root = start;
    while ((root * 2) + 1 <= end) { // root should have atleast one child
        int child = (root * 2 + 1); // point to left child

        // if child has siblings and left child is less than sibling
        if (child + 1 <= end && arr[child] <= arr[child + 1]) {
            child = child + 1; // make this child right child
        }

        // if root is less than child (could be left | right) then bubble up
        if (arr[root] < arr[child]) {
            // swap the node with max value child node
            swap(arr, root, child);
            // set the root to the child level, so that subtrees if any
            // could be shift
            root = child;
        } else {
            root++; // make it bigger to exit out the loop
            // return; // return if root node is greator than child node.
        }

    }

}

private static void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;

}

Why do you need to pass the length of an array to buildMaxHeap?

private static void buildMaxHeap(int[] arr, int len) {

The functions itself can just use find the length property itself because it is getting the actual array from function parameters.

However, I still believe that it was smart idea to check that i was less than len, which was the length of the array rather than just checking if i was less than the length the array because it is unnecessarily efficient to constantly access the length property of an array.

Here is what I mean:

private static void buildMaxHeap(int[] arr) {
    // any nodes after n/2 are leaves node and could be without children
    int len = arr.length;
    for (int i = (len) / 2; i >= 0; i--) {
        // bubble up to build max heap
        bubbleUp(arr, i, len - 1);
    }
}

All of your functions (except main) are very cluttered up with comments. I recommend that you add JavaDoc to all these functions and include as much explanation as you need up there.

That way, if there any confusions about something in a function, the answer can be found above the function, rather than in the function.

This line of heapSort

System.out.println("Sorted Array : " + Arrays.toString(arr));

is confusing in two ways:

You are printing the same message in main so I don't see why you are doing it again here.
This method is for "heap-sorting" an array, not for sending output to the user. If possible, all input and output should be done inside main.

Note: This may not apply, but you didn't include the class definition so I do not know.

I recommend calling this class HeapSort, and then having a single static public method called sort that takes a single array and "heap-sorts" it.

That way, if you are writing other code that needs to "heap-sort" an array, you can use the HeapSort class and call it's sort method to sort it. This will make your code more organized.

Here is what I mean:

public class HeapSort {
    public static void sort(int[] arr) {
        [heapSort code]
    }

    ... your other private methods...
}

Now your code is more organized and is ready to be used by another class.

Here is how you would use the HeapSort class and it's sort method:

HeapSort.sort(myIntArray);


Looping over a list, checking a boolean and return value There are a number of different ways to do this. What do people prefer and why?

public boolean checkNameStartsWith(List<Foo> foos) {
    for (Foo foo : foos) {
        if (!(foo.getName().startsWith("bar"))) {
            return Boolean.FALSE;
        }
    }
    return Boolean.TRUE;
}

I'd change Boolean.FALSE to false and Boolean.TRUE to true. Using the constants objects from Boolean is rather unnecessary since the method returns with primitive boolean.


Move zipped files from multiple subfolders into one master folder via loop process I am trying to write a code that:

First Prompt: asks the user to select the folder that contains all zipped folders where each zipped folder contains a data file.

Second Prompt: Ask the user to select the master folder path to place the unzipped data files into.

The program will unzip the first zipped folder, copy the data file out, paste the data file into the designated master folder the user was prompted to select from their second prompt.

The program will find the next zipped folder, unzip and open the folder, copy out the file it contains, paste the file into the master folder, rinse and repeat until all the files from each of the zipped folders are moved over.

I am trying to make a folder that contains all the zipped data files in order to concatenate all the data into a master document. Then I will be able to run an analysis on this data.

This code works but I need some help with getting the code to run faster.  I tested the program on a folder that contained only 6 zipped files and it moved the files over in 2 seconds.  But now I'm testing the program on a folder that contains 8020 zipped files and its moving over the files at a rate of 1 file every 8 seconds.

I have "Microsoft Shell Controls And Automation", "Visual Basic For Applications", "Microsoft Excel 15.0 Object Library", OLE Automation", "Microsoft Office 15.0 Object Library", Microsoft Forms 2.0 Objection Library" options enabled.

Can anyone help me speed this up?

Option Explicit

Sub UnzipFileMoveToMasterFolder()

Dim oApp As Shell
Dim strFile As String
Dim FolderPath As FileDialog
Dim MasterFolder As String
Dim ZipFolder As String
Dim i As Integer

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False

'Retrieve target master workbook data folder path from user
Set FolderPath = Application.FileDialog(msoFileDialogFolderPicker)

With FolderPath
  .Title = "Select a master folder location to store the unzipped files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect1
    MasterFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect1:
MasterFolder = MasterFolder
If MasterFolder = "" Then GoTo ResetSettings

'Retrieve target data folder path from user
Set FolderPath = Application.FileDialog(msoFileDialogFolderPicker)

With FolderPath
  .Title = "Select folder location that contains the zipped folders with desired data files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect2
      ZipFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect2:
ZipFolder = ZipFolder
If ZipFolder = "" Then GoTo ResetSettings

'get a shell object
Set oApp = CreateObject("Shell.Application")
'get all the files in the directory that are zip files

strFile = Dir(ZipFolder & "*.zip")
'loop until we cannot find anymore files
Do While strFile <> ""
        'check to see if the zip contains items
        If oApp.Namespace(ZipFolder).Items.Count > 0 Then
            'loop through all the items in teh zip file
            For i = 0 To oApp.Namespace(ZipFolder).Items.Count - 1
            'save the files to the new location
            oApp.Namespace(MasterFolder).CopyHere oApp.Namespace(ZipFolder & strFile).Items.Item(i)
            Next i
        End If
    'get the next file in the directory
    strFile = Dir
Loop
'free memory
Set oApp = Nothing

'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True

'Message Box when tasks are completed
MsgBox "Task Complete!"
Application.Cursor = xlDefault

End Sub

This code is very hard to follow at a casual reading, because of the inconsistent and non-standard indentation (10%) and the liberal use of GoTo's (90%).

Indentation:
The following should increase your indentation level by one level - Sub\ Function, With, If, For, Do.  In addition, labels (which we'll discuss in a moment) should not be indented.  In fact, the IDE will attempt to pin them to the left margin to make that easier.

GoTo:
Just because VBA has "Basic" in the name doesn't mean that it's the non-structured Basic I knew and loved back in the late 80s.  It has evolved into a structured language, so really the only place where you should use GoTo is in error handling.  Everything else that it can possibly be used for can be accomplished with different flow control structure or functions.  For example, this section...

With FolderPath
  .Title = "Select a master folder location to store the unzipped files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect1
    MasterFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect1:

...can be restructured in a much more readable way (and get rid of the heebie-jeebies I get when I see a jump out of a With block) like this:

With FolderPath
    .Title = "Select a master folder location to store the unzipped files."
    .AllowMultiSelect = False
    If .Show = -1 Then
        MasterFolder = .SelectedItems(1) & "\"
    End If
End With

Dead Code:
Think about the line of code MasterFolder = MasterFolder, then ask yourself what this is intended to accomplish.  There is no situation that I can come up with where setting a variable to itself will accomplish anything useful.

VbNullString:
"" should be replaced with vbNullString.  Note that the two are not the same - vbNullString is a compiler constant that is basically a string pointer to null.  "" actually allocates itself as a string with zero length, which is very different, especially if you're using Declare'd functions and API calls.  The following demonstrates:

Debug.Print StrPtr(vbNullString)
Debug.Print StrPtr("")

The first returns 0, the second returns a memory address (no huge speed gains here - the compiler is smart enough to re-use the allocation).

Testing For Empty Strings: Not a huge performance issue, but testing string equity with "" (or VbNullString for that matter) is roughly 25% slower than checking to see if the length is zero.  This is due to how Strings are stored in VBA - internally they are stored as BSTR's, so the Len function only has to grab the length from the start of the string.  This is much more efficient than a string equity check, even with the function call.  So, ...

Do While strFile <> ""

... would be better as this:

Do While Len(strFile) > 0

String v. Variant Functions: You may have noticed that most string handling functions have 2 versions - the "normal" function, and a version that ends in "$".  The ones that end in "$" return a String, the others return a Variant.  If you are assigning the return value to a String or passing it to a function that takes a String as a parameter, you should use the function that returns a String.  The reason is that there is an implicit cast performed, so this...

strFile = Dir(ZipFolder & "*.zip")

...is essentially this when compiled:

strFile = CStr(Dir(ZipFolder & "*.zip"))

Much better to just do this and omit the cast:

strFile = Dir$(ZipFolder & "*.zip")

Misc: You don't need to turn off ScreenUpdating, Events, Calculation, or Alerts.  Your code doesn't do anything that would effect any of them, so it does nothing to "Optimize Macro Speed". You also don't need to set objects to Nothing.  The variable names MasterFolder and ZipFolder are confusing - something like source and destination would be much clearer.  While you're at it, I'd ditch the Hungarian notation.  You also don't need to instantiate the FileDialog twice - you can reuse the same object (which also lets you get rid of a variable, since all of the work can go into one With block).  You also don't need to concat the "\" to the end of your source folder - it's much clearer if you put the concat where it's actually required instead of in the folder dialog code. Finally, the MsgBox at the end is confusing with your current control flow.  It gives the indication that work was performed if the user cancels out of either of the folder selections.

Performance: Unzipping over 8000 files is never going to be fast, but the main performance gain that you'll get is from removing the inner loop that copies items out of the zip files one at a time.  The .CopyHere method doesn't need individual items - it can process the entire collection at once:

oApp.Namespace(MasterFolder).CopyHere oApp.Namespace(ZipFolder & strFile).Items

Final Result: Something more like this:

Sub UnzipFileMoveToMasterFolder()
    Dim appl As Shell
    Dim archive As String
    Dim destination As String
    Dim source As String

    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select a master folder location to store the unzipped files."
        .AllowMultiSelect = False
        If .Show = -1 Then destination = .SelectedItems(1)
        If Len(destination) = 0 Then Exit Sub
        .Title = "Select folder location that contains the zipped folders with desired data files."
        If .Show = -1 Then source = .SelectedItems(1)
        If Len(source) = 0 Then Exit Sub
    End With

    Set appl = CreateObject("Shell.Application")
    archive = Dir$(source & "\*.zip")
    Do While Len(archive) > 0
        appl.Namespace(destination).CopyHere appl.Namespace(source & "\" & archive).Items
        archive = Dir$
    Loop
    MsgBox "Task Complete!"
End Sub


Simple Producer-consumer implementation in Python I implemented a simple solution to the Producer–consumer problem
 that I'd love for you to take a look at.

The producer simply adds random numbers to a queue and the consumer (from a separate thread) pops numbers off the queue and prints them. I'd specifically like feedback on the concurrency aspects of this implementation. Thanks!

from collections import deque
import random
import threading

TIMES = 100

class SafeQueue:
  def __init__(self, capacity):
    self.capacity = capacity
    self.queue = deque([])
    self.remaining_space = threading.Semaphore(capacity)
    self.fill_count = threading.Semaphore(0)

  def append(self, item):
    self.remaining_space.acquire()
    self.queue.append(item)
    self.fill_count.release()

  def consume(self):
    self.fill_count.acquire()
    item = self.queue.popleft()
    self.remaining_space.release()
    return item

class Producer:
  def __init__(self, queue, times=TIMES):
    self.queue = queue
    self.times = times

  def run(self):
    for _ in range(self.times):
      self.queue.append(random.randint(0, 100))

class Consumer:
  def __init__(self, queue, times=TIMES):
    self.queue = queue
    self.times = times

  def run(self):
    for _ in range(self.times):
      print(self.queue.consume())

def main():
  queue = SafeQueue(10)

  producer = Producer(queue)
  producer_thread = threading.Thread(target=producer.run)
  consumer = Consumer(queue)
  consumer_thread = threading.Thread(target=consumer.run)

  producer_thread.start()
  consumer_thread.start()

  producer_thread.join()
  consumer_thread.join()

if __name__ == "__main__":
  main()

Actually, the initial producer-consumer scheme is over-complicated and has the following issues:

Using 2 separate threading.Semaphore objects:
One of them is used for producer (remaining_space), another - for consumer (fill_count). Though they won't be convenient here (as I'll describe below), but for your future potential cases, a better naming would be self.producer_counter and self.consumer_counter.What those 2 semaphors (as internal counters) do is just emulating limitation of the capacity of a resource (the resource is deque in our case)
How it starts and flows:

On running the producer starts appending random items in a loop of 100 iterations:

    ...
    for _ in range(self.times):
        self.queue.append(random.randint(0, 100))

on each iteration the producer thread will acquire self.remaining_space.acquire() decrementing the internal counter. When producer's counter is zero (0) the producer thread will block until the consumer thread calls self.remaining_space.release() thus increasing the producer's counter by 1 and letting the producer thread to proceed.Such a "dragging" of acquire/release in multiple places can be just replaced with well-known queue.Queue, which is FIFO queue that already uses deque under the hood and already provides the needed locking mechanism and timeout logic.

  The queue module implements multi-producer, multi-consumer queues.
  It is especially useful in threaded programming when information must
  be exchanged safely between multiple threads. The Queue class in
  this module implements all the required locking semantics.

...

class queue.Queue(maxsize=0)

  Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the
  queue. Insertion will block once this size has been reached, until
  queue items are consumed. If maxsize is less than or equal to zero,
  the queue size is infinite.

So maxsize already gives us a limited capacity.

Namings:
A better names for a numeric constants in our new scheme would be:

MAX_QSIZE = 10  # max queue size
BUF_SIZE = 100  # total number of iterations/items to process

"Tricky" passing of TIMES constant:
It's not good to pass total number of processed items to Consumer constructor:

class Consumer:
    def __init__(self, queue, times=TIMES):
    ...

that allows compromising and specifying improper number of items to process.Consider the following case:

TIMES = 100
...
    producer = Producer(queue)
    producer_thread = threading.Thread(target=producer.run)
    consumer = Consumer(queue, times=50)
    consumer_thread = threading.Thread(target=consumer.run)

this will point the consumer to consume less items than the queue contains, eventually having the queue with dangled items.If you run that case you'll have the pipeline blocked/hanged. To avoid that we need to ensure the consumer has gotten and processed all items in the queue:

class Consumer:
    def __init__(self, queue):
        self.queue = queue

    def run(self):
        while not self.queue.empty():
            item = self.queue.get()
            self.queue.task_done()
            print(item)

To enrich the queue communication we can incorporate queue.task_done() and queue.join() (the final version will incorporate them).

The final concise version:

from queue import Queue
import random
import threading

MAX_QSIZE = 10  # max queue size
BUF_SIZE = 100  # total number of iterations/items to process

class Producer:
    def __init__(self, queue, buf_size=BUF_SIZE):
        self.queue = queue
        self.buf_size = buf_size

    def run(self):
        for _ in range(self.buf_size):
            self.queue.put(random.randint(0, 100))

class Consumer:
    def __init__(self, queue):
        self.queue = queue

    def run(self):
        while not self.queue.empty():
            item = self.queue.get()
            self.queue.task_done()
            print(item)

def main():
    q = Queue(maxsize=MAX_QSIZE)

    producer = Producer(q)
    producer_thread = threading.Thread(target=producer.run)

    consumer = Consumer(q)
    consumer_thread = threading.Thread(target=consumer.run)

    producer_thread.start()
    consumer_thread.start()

    producer_thread.join()
    consumer_thread.join()
    q.join()

if __name__ == "__main__":
    main()


Round fractional seconds of MySQL Time I've written a method to round a MySQL Time to two decimal places. Here's some examples:

Input           -> Output

13:04:27.127930 -> 13:04:27.13
00:00:14.000000 -> 00:00:14.00
02:19:03.300000 -> 02:19:03.30
07:13:00.954639 -> 07:13:00.96

My current code works, but seems a bit difficult to follow. How could I improve the readability of the code? Performance isn't too much of a concern.

<?php
public function mysql_time_to_human($mysql_time)
    {
        //how many decimal places it should show
        (defined('DECIMAL_PLACES')) ?: define('DECIMAL_PLACES', 2);

        //Separate the sting on the decimal place
        $time_parts = explode('.', $mysql_time);

        //Add a 0 prefix so it can properly round the decimal part
        $time_parts[1] = '0.' . $time_parts[1];

        //Round the number to two decimal places
        $rounded_part = round($time_parts[1], DECIMAL_PLACES);

        //Ensure the part is always two decimal places, including zeroes
        $time_parts[1] = sprintf('%.2f', $rounded_part);

        //Remove the 0 prefix added earlier
        $time_parts[1] = substr($time_parts[1], 2);

        //Glue the parts back together
        $time = implode('.', $time_parts);

        return $time;
    }

While writing this question I've realized a case which my current method won't accurately work for:

Input           -> Desired Output -> My Output
00:00:00.995000 -> 00:00:01.00    -> 00:00:00.00

Why not just cast the field to lesser precision when querying from the database?

For example:

SELECT CAST(time_field AS TIME(2)) FROM table


Calculate the sum of a series with a given accuracy #include <iostream>
#include <cstring>
using namespace std;
int main() {
    system("chcp 1251>nul");
    int i = 1;
    int x;
    cin >> x;
    if (abs(x) >= 1) { cout << "The series is divergent"; }
    else {
    double eps = 0.000001;
    double sum = 0;
    double lastElementOfSequence=1;
    do {
        sum += lastElementOfSequence;
        lastElementOfSequence *= -1 * x * (2 * i + 3) / (2 * i);
         i++;
    } while (fabs(lastElementOfSequence) > eps);
    cout.precision(17);
    cout << "sum=" << sum << endl;
    }
    system("pause>nul");
    return 0;
}

$$S=(1+x)^{-\frac{5}{2}}=1-\frac{5}{2}x+\frac{5\cdot7}{2\cdot4}x^2-\frac{5\cdot7\cdot9}{2\cdot4\cdot6}x^3+\frac{5\cdot7\cdot9\cdot11}{2\cdot4\cdot6\cdot8}x^4$$
$$where\ |x|<1$$
The task in the image, and the code from above I will ask to check up whether the correctly solved task I will be grateful, but if an error that specify please or correct.

We're including the wrong headers.  We don't need <cstring>, but we do need <cmath> (for std::fabs).
Don't do this:

using namespace std;

That might not be so harmful in small programs, but it's a bad habit have because it makes larger programs more difficult to follow, and it increases the risk of identifier collisions, especially as the standard library continues to grow.
Never ignore the return value from std::system().  There are two uses of this function, and both of them are going to fail here, since I don't have either of the programs installed.  Is it right that they both create a file called nul?  Or did you just misspell /dev/null?
Never ignore the return value from stream-reading operations.  std::cin >> x leaves x uninitialised (before C++11) or zero (C++11 onwards) if it can't perform the conversion.
I don't think you wanted an integer as x anyway - shouldn't it be double?
Error messages should go to std::cerr, not std::cout.
Instead of multiplying i by 2 all the time, consider incrementing i in steps of 2.
The addition is being done in the wrong order.  When adding floating-point numbers, we want to accumulate the smallest values first, so as not to lose precision.
Instead of using the precision() function of a stream, consider using <iomanip>.  17 decimal digits of precision seems too large, given that the value of eps means we won't achieve 6 digits.
Don't use std::endl except when you genuinely need to flush the stream.  That unnecessarily slows programs down.

Here's a version that's modified to fix the above problems:
#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

// FIXME - make this a parameter
constexpr double precision = 0.000'001;

int main()
{
    double x;
    std::cin >> x;
    if (!std::cin) {
        std::cerr << "Invalid input\n";
        return 1;
    }

    if (std::fabs(x) >= 1) {
        std::cerr << "The series is divergent above |x|=1\n";
        return 1;
    }

    std::vector<double> terms;
    double term = 1;
    for (auto i = 2ul;  std::fabs(term) >= precision;  i += 2) {
        terms.push_back(term);
        term *= -x * (i + 3) / i;
        if (i > std::numeric_limits<decltype(i)>::max() - 2) {
            // overflow
            break;
        }
    }
    // add smallest terms first
    auto sum = std::accumulate(terms.crbegin(), terms.crend(), 0.0);

    std::cout << std::setprecision(7) << "sum=" << sum << '\n';
}

As suggested by greybeard in comments, the way the function converges means we can get a good estimate of the rest of the series by halving the last term that we consider, and we can terminate when the sum of two consecutive elements is within our precision value:
std::vector<double> terms;
double term = 1;
std::size_t i = 2;
do {
    terms.push_back(term);
    term *= -x * (i + 3) / i;
    i += 2;
} while (std::abs(term + terms.back()) >= precision);

// term/2 is a good approximation to the rest of the series
terms.push_back(term / 2);


Need help with my code using a base class? I my class hierarchy looks like this:

P
I : P
O : P

I have this method. The goal of this method is to return a new object of type I or O depending on a certain condition.

 public P GetP()
 {
    this.Session.Begin();

    var pDetail = GetPDetail();

    if (pDetail == null)
    {
        this.Session.Close();
        return null;
    }

    switch (pDetail.Code)
    {
        case "1":
            var i = new I();
            i.PDetail = pDetail;
            FillBaseP(i);
            FillI(i);
            this.Session.Close();
            return i;
        case "3":
            var o = new O();
            o.PDetail = pDetail;
            FillBaseP(o);
            FillO(o);
            this.Session.Close();
            return o;
        default:
            throw new Exception("Code is invalid");
     }
 }

I'm looking to rewrite this in a more logical way. Both case "1" and case "3" are doing some of the same work.

If I'm constantly checking type like If(var is O) or If(var is I) I feel as though I'm doing something wrong. Is this the case?

I think it would be better if Session.Begin() returned an IDisposable, which would call Session.Close() in its Dispose(). That way, you can enclose the whole method inside using and you don't have to worry about calling it properly. (For example, it's not called in your code if the code is invalid.)
You can extract the creation of I or O into a generic method. It will also have a delegate parameter that represents the type-specific fill method.
It's better if you throw a specific exception (maybe something like InvalidCodeException), not Exception.

With these changes, the code would look like this:

private P CreateP<T>(PDetail pDetail, Action<T> fillT) where T : P, new()
{
    var p = new T { PDetail = pDetail };
    FillBaseP(p);
    fillT(p);
    return p;
}

public P GetP()
{
    using (this.Session.Begin())
    {
        var pDetail = GetPDetail();

        if (pDetail == null)
            return null;

        switch (pDetail.Code)
        {
        case "1":
            return CreateP<I>(pDetail, FillI);
        case "3":
            return CreateP<O>(pDetail, FillO);
        default:
            throw new InvalidCodeException("Code is invalid");
        }
    }
}

  If I'm constantly checking type like If(var is O) or If(var is I) I feel as though I'm doing something wrong. Is this the case?

Yeah, probably. But it's hard to tell (and advise a better approach) without seeing the code.