texts:
This is my queue implementtion in C. Feel free to ask me any questions relating to my code. Any tips or suggestions are welcome, including tips on naming/spacing/common conventions.
Queue_node, Queue, create_queue, destroye_queue, queue_push, queue_pop are meant to work with any node struct which has a member struct Queue_node *next and functions to create the node and destroy the node.
#include <stdlib.h>
/* malloc(), EXIT_SUCCESS */
#include <stdio.h>
/* fprintf */
#include <stddef.h>
/* size_t */

struct Coordinate {
    int x;
    int y;
};

struct Queue_node {
    struct Queue_node *next;
};

struct Queue {
    struct Queue_node *front;
    struct Queue_node *back;

    size_t size;
};

struct Queue* create_queue(void) {

    struct Queue *created_queue = malloc(sizeof(*created_queue));

    if (created_queue == NULL) {
        return NULL;
    }

    created_queue->back = NULL;
    created_queue->front = NULL;
    created_queue->size = 0;

    return created_queue;
}

void destroy_queue(struct Queue *input_queue, void (*delete_node)(void*)) {

    while (input_queue->front != NULL) {

        struct Queue_node *deleted_node = input_queue->front;
        input_queue->front = input_queue->front->next;
        if (delete_node != NULL) {
            delete_node(deleted_node);
        }
    }
    free(input_queue);
}

void queue_push(struct Queue *input_queue, void *input_node) {

    ++input_queue->size;

    if (input_queue->front == NULL) { // first insert

        input_queue->front = (struct Queue_node*) input_node;
        input_queue->back = (struct Queue_node*) input_node;

        return;
    }

    input_queue->back->next = (struct Queue_node*) input_node;
    input_queue->back = input_queue->back->next;
}

void* queue_pop(struct Queue* input_queue) {

    if (input_queue->front == NULL) { // empty queue
        return NULL;
    }

    --input_queue->size;

    struct Queue_node *deleted_node = input_queue->front;
    input_queue->front = input_queue->front->next;

    return deleted_node;
}

/*
nodes that are queue_pop()'d must be free()'d by caller
*/

static struct Weighted_coord_node {
    struct Queue_node *next;
    // parent property

    int weight;
    struct Coordinate coord;
    // child properties
};

static struct Weighted_coord_node* create_node(struct Coordinate coord, int weight) {

    struct Weighted_coord_node *node = malloc(sizeof(*node));

    if (node == NULL) {
        return NULL;
    }
    node->next = NULL;
    node->coord = coord;
    node->weight = weight;

    return node;
}

int main() {

    struct Queue *my_queue = create_queue();
    if (!my_queue) {
        return EXIT_FAILURE;
    }

    struct Weighted_coord_node *my_node;

    my_node = create_node((struct Coordinate){5,5}, 0);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    my_node = create_node((struct Coordinate){7,7}, 2);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    my_node = create_node((struct Coordinate){11,11}, 5);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    while (my_node = queue_pop(my_queue)) {
        fprintf(stderr, "POP->  X: %i, Y:%i   weight: %i\n", my_node->coord.x, my_node->coord.y, my_node->weight);
        free(my_node);
    }

    destroy_queue(my_queue, free);

    return EXIT_SUCCESS;
}

I rewrote the code following @vnp's suggestion. Here is the new version: My queue implementation (in C) [V.2]


texts: Finding the largest absolute difference in a list

texts:
I'm moving away from map, reduce and filter in favour of list comprehensions. I like list comps but I feel like this is getting on the unreadable side.

Is this the most idiomatic way of achieving this? Is it easy enough to read?

int_list = [-1,-3,5,7]

absolute_diffs = [max( [abs( int_2 ) - abs( int_1 ) for int_2 in int_list] ) for int_1 in int_list]

print max( absolute_diffs )


texts: Moving instance variable from partial to helper

texts:
I want to display a town name in my navigation, depending on the town I am requesting from the model. The following code works, but I am mixing logic in my view which I know is wrong and I haven't been successful in accessing the @town instance variable from my TownsController.

Can someone lead me down the road to enlightenment in a situation like this? Should I be using a helper? How do I access it in my _header.html.erb partial?

   <% @towns = Town.all %>
   <% @towns.each do |t| %>

<%= link_to "#{t.name}", '#', id: "logo" %>

   <% end %>


texts: Custom 503 page for MySQLi connection error

texts:
I redirect all my requests to index.php via htaccess and the code below is in my index.php.

I want to ask if my code is properly set for a custom 503 page for an unsuccessful MySQLi connection trial.

Is it also proper to use these metatags?

<meta name="robots" content="noindex,nofollow,noarchive">

<?php
$mysqli = new mysqli(HOSTX, USERX, PSWX, NAMEX);
if ($mysqli->connect_errno) {
    header($_SERVER["SERVER_PROTOCOL"]." 503 Service Unavailable");
    header( 'Content-Type: text/html; charset=utf-8' );
    header( 'Retry-After: 600' ); // 10 minutes
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>DB Connection Error</title>
    <meta name="description" content="DB Connection Error 503 sayfası" />
    <meta name="robots" content="noindex,nofollow,noarchive">
    <meta name="viewport" content="width=device-width, initial-scale=1">

DB Connection Error.

Please try in 1 or 2 minutes.

<?php
    exit();
}
?>


texts:
I have attempted to write a method that checks that images being uploaded are valid.

public function checkValidImages(){
            $errors             = array();
            $allowedImages      = array('image/jpg','image/jpeg','image/png','img/gif');
            $maxFileSize        = 2097152;
            $invalidSize        = 0;
            $invalidTypes       = 0;
            $invalidDimension   = 0;
            $minWidth           = 220;
            $minHeight          = 220;

            // Check atleast one image has been selected
            foreach($_FILES['event-images']['tmp_name'] as $tmp_name){

                if($tmp_name == ""){
                    $errors[] = 'Please select atleast one image.'; // This is okay because instance would only occur once
                }
            }

            // Check Images are valid image types
            foreach($_FILES['event-images']['type'] as $type){

                if(!in_array($type, $allowedImages)){
                    $invalidTypes++;
                }
            }

            // Check images are valid sizes
            foreach($_FILES['event-images']['size'] AS $size){
                if($size > $maxFileSize){
                    $invalidSize++;
                }
            }

            // Check images are atleast 220px high and 220px wide
            foreach($_FILES['event-images']['tmp_name'] AS $image){

                // Get image width and height
                $image_dimensions = getimagesize($image); // returns an array of image info [0] = width, [1] = height
                $image_width = $image_dimensions[0]; // Image width
                $image_height = $image_dimensions[1]; // Image height

                if(($image_width < $minWidth) || ($image_height < $minHeight)){
                    $invalidDimension++;
                }
            }

            // Add errors to return array
            if($invalidDimension > 0){
                $errors[] = 'One or more of your images has invalid dimensions. Images must be atleast 220px by 220px.';
            }
            if($invalidTypes > 0){
                $errors[] = 'One or more of your images has an invalid image type. Please only select jpg, png or gif images.';
            }
            if($invalidSize > 0){
                $errors[] = 'One or more of your images is an invalid size. Please only select images less than 2MB in size.';
            }

            // Return errors
            return $errors;
        }

I was wondering if this could be made cleaner or more efficient.


texts:
I've written a decorator for easily creating multiple dispatch functions:

from functools import wraps

def multi_dispatch(for_function):
    """
    Returns a multiple dispatch version of the function.

    The returned function doesn't allow keyword arguments.

    >>> @multi_dispatch
    ... def foo(a, b):
    ...     pass
    ...
    >>> @foo.add
    ... def _foo(a: int, b: int, c : str = '33'):
    ...     return a + b*3 + len(c)
    ...
    >>> @foo.add
    ... def _foo(a: int, b: int, c = 3):
    ...     return a + b*3 - c
    ...
    >>> @foo.add
    ... def _foo(a: float, b: float):
    ...     return a*2 - b
    ...
    >>> foo(4, 5)
    16
    >>> foo(1.0, 2.0)
    0.0
    >>> foo(4, 5, 'loooong')
    26
    >>> foo(3, 4.5)
    Traceback (most recent call last):
      ...
    KeyError: (<class 'int'>, <class 'float'>)
    """
    @wraps(for_function)
    def decorated(*args):
        return decorated.registry[tuple(type(i) for i in args)](*args)

    decorated.registry = {}

    def adder(func):
        """
        Adds the supplied function to the multiple dispatch registry.
        """
        code = func.__code__
        args = code.co_varnames
        annotations = func.__annotations__
        types = tuple(annotations[a] for a in args if a in annotations)
        decorated.registry[types] = func
        return func

    decorated.add = adder
    return decorated

I'd like to read your comments about the code (efficiency, re-usability, etc.), documentation and everything else that you feel is worth noting.

Update: After fixing all the points listed in the choosen answer, I have created a new version.


texts:
Problem Statement

Input Format

The first line contains a single string, a. The second line contains a single string, b.

Constraints

1<= |a|,|b| <= 10^4

It is guaranteed that and consist of lowercase English alphabetic letters (i.e., through ). Output Format

Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

Sample Input

cde

abc

Sample Output

4

Explanation

We delete the following characters from our two strings to turn them into anagrams of each other:

Remove d and e from cde to get c. Remove a and b from abc to get c. We must delete characters to make both strings anagrams, so we print on a new line.

Solution

public class Solution {
public static int numberNeeded(String first, String second) {

    StringBuilder firstBuilder = new StringBuilder(first);
    StringBuilder secondBuilder = new StringBuilder(second);
    int numberNeeded = firstBuilder.length() + secondBuilder.length();

    for (int i=0; i<first.length(); i++) {

        char currentChar = first.charAt(i);

        for (int j=0; j<secondBuilder.length(); j++) {
            char charToCompare = secondBuilder.charAt(j);

            if (charToCompare == currentChar) {
                firstBuilder.deleteCharAt(0);
                secondBuilder.deleteCharAt(j);
                numberNeeded -= 2;
                break;
            }
        }
    }

    return numberNeeded;

}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String firstArray = in.next();
    String secondArray = in.next();
    System.out.println(numberNeeded(firstArray, secondArray));
}
}

Can I please get feedback on my code and also on my solution approach? Also, can someone guide me about the time and space complexity of this solution? How do we calculate it and how can I make it better?

Thanks in advance


texts: A structure and helper functions for working with polar coordinates

texts:
This started simple, as most things do. I just wanted a little structure to hold polar coordinates for a totally minor class. But starting with this answer and borrowing from existing Objective-C concepts like CGPoint and CGSize, the simple struct quickly morphed into a more complete solution.

I have this all in a _polar.h file that I have included in my files and I was wondering what other things should be included and/or other criticism of my technique. Am I approaching this thing correctly?

(Note: startPoint and endPoint are part of the structure to help solve other problems in my class and are not necessarily "normal" parts of a polar structure.)

#ifndef Polar__polar_h
#define Polar__polar_h

struct _Polar {
    CGFloat angle;
    CGFloat r;
    CGPoint startPoint;
    CGPoint endPoint;
};
typedef struct _Polar Polar;

static inline Polar
PolarMakeFromPoints(CGPoint startPoint, CGPoint endPoint) {
    Polar polar;
    polar.startPoint =startPoint;
    polar.endPoint =endPoint;
    polar.angle =atan2f(endPoint.y -startPoint.y, endPoint.x -startPoint.x);
    polar.r =sqrtf(powf(endPoint.x -startPoint.x, 2.0) + pow(endPoint.y -startPoint.y, 2.0));
    return polar;
}
static inline Polar
PolarMake(CGFloat angle, CGFloat r) {
    Polar polar;
    polar.angle =angle;
    polar.r =r;
    polar.startPoint =CGPointZero;
    polar.endPoint =CGPointMake((cos(angle) *r), (sin(angle) *r));
    return polar;
}
static inline bool
PolarEqualToPolar(Polar polar1, Polar polar2) {
    return polar1.angle ==polar2.angle && polar1.r ==polar2.r;
}
static inline bool
PolarIdenticalToPolar(Polar polar1, Polar polar2) {
    return CGPointEqualToPoint(polar1.startPoint, polar2.startPoint)
        && CGPointEqualToPoint(polar1.endPoint, polar2.endPoint);
}

static inline Polar
_PolarZero() {
    Polar polar;
    polar.angle =0.0;
    polar.r =0.0;
    polar.startPoint =CGPointZero;
    polar.endPoint =CGPointZero;
    return polar;
}
#define PolarZero _PolarZero()

static inline NSString
*NSStringFromPolar(Polar polar) {
    return [NSString stringWithFormat:@"a=%f r=%f", polar.angle, polar.r];
}

// Extend NSValue to work with Polar
@interface NSValue (Polar)
+(id)valueWithPolar:(Polar)polar;
-(Polar)polarValue;
@end
@implementation NSValue (Polar)
+(id)valueWithPolar:(Polar)polar {
    return [NSValue value:&polar withObjCType:@encode(Polar)];
}
-(Polar)polarValue {
    Polar polar;
    [self getValue:&polar];
    return polar;
}
@end

@interface NSString (Polar)
@end
@implementation NSString (Polar)

@end

#endif


texts: Multiple DB record creation after a successful operation

texts:
I am working on a payment process. Upon a successful payment process, I have to create multiple records. For that, I have made this class:

class DatabaseMaintainer

  def initialize(merchant, card, payment_method)
    @merchant = merchant
    @card = card
    @payment_method = payment_method
  end

  def maintain_records(customer, payment_details, response)
    rate = RateCatalog.get_rate(@merchant.id, @card.id, @payment_method.id)
    amount =  payment_details['total'].to_d
    commission = rate.rate *  amount / 100
    payable = amount - commission
    customer.organization_id = @merchant.id
    customer.save

    cash_transaction = CashTransaction.create!(
        amount: amount,
        receipt_id: response.authorization,
        rate_catalog_id: rate.id,
        customer_id: customer.id,
        redirect_url: payment_details['redirect_url']
    )

    Settlement.create!(
        commission_amount: commission,
        payable_amount: payable,
        cash_transaction_id: cash_transaction.id
    )

    invoice = Invoice.create!(
                    invoice_number: "#{CommonConstants::INVOICE_NUMBER_PREFIX}#{@merchant.abbreviation}_#{payment_details['invoice_id']}",
                    total: amount,
                    status: Invoice.statuses[:paid],
                    organization_id: @merchant.id,
                    cash_transaction_id: cash_transaction.id,
                    description:  payment_details['description']
    )

    item_details = payment_details['items']
    item_details.each do  |x|
      x[:bill_id] = invoice.id
      x[:bill_type] = 'Invoice'
    end

    PurchasedGood.create!(item_details)
  end
end

And I am using it as follows:

DatabaseMaintainer.new(@merchant, card_brand, payment_method).maintain_records(@customer, invoice_details, gateway_reply[:message])

Now, even if the code works fine, it clearly is not an optimal design.

I am looking for suggestions to refactor it. Also, is having a class for creating DB records solely justified in my scenario?


texts: Search father (x) of the number D(x) and measure time and memory consumed

texts:
We define function D(x) as following:

D(x) = x + sum of digits of x
+ sum of prime factors of x   then call x the father of D(x)

Write a program that gets input t at the first line and then gets an input in the next t lines. If that input had father, print YES otherwise NO

For example 12 is the father of 20
20 = 12 + (1 + 2) + (2 + 3)

preferably write a separate function for each of these tasks:

Getting sum of the digits of a number
Getting prime factors of a number
Calculating D(x)

Notice that if you do lots of operations, you may get time limit error.

Time limit: 0.5 seconds
Memory limit: 128 MB

Input:
You get an input number t at the first line and then in the next t lines, you get number n for which you should solve the problem

Output:
Print the answer to each input in t lines.

Example:
Sample input:

  2
  4
  20

Sample output:

  NO
  YES

I've written the code with python:

# function that returns the unique prime factors of number n as a list
def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    factors = list(set(factors))
    return factors

# function that returns the sum of digits of number n
def sum_digits(n):
    r = 0
    while n:
        r, n = r + n % 10, n // 10
    return r

# function to calculate the offspring of number X {D(X)}
def Offspring(X):
    DX = X + sum(prime_factors(X)) + sum_digits(X)
    return DX

ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()
t = eval(input())
for i in range(0, t):
    n = eval(input())
    if n in Fathers:
        print('YES')
    else:
        print('NO')

I guess this part of code

ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()

is the bottle-neck for time limit. since I don't know how to find x by having D(x), I've solved the problem this way:

ChildFather = {i: Offspring(i) for i in range(4, 1001)}

for numbers 4<= n<= 1000, I've created a dictionary {n:D(n)}

ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()

created a list of unique values of the dictionary and deallocated the memory used for the dictionary

Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()

create a list of values smaller than 1000 and deallocated memory used for the original list

t = eval(input())
for i in range(0, t):
    n = eval(input())
    if n in Fathers:
        print('YES')
    else:
        print('NO')

If a given number exists n in the final provided list, I understand that n can be written as D(m)=m+sum of digits of m + sum of prime factors of m so n has the father m and I'll print Yes otherwise NO
But seems that the program is not efficient.

How can I measure the time consumed by this python program at run-time?
How can I measure the memory consumed by this python program at run-time?
(I'm new to python and am coding with sublime text 3 in Linux Ubuntu)
Is there any more efficient way of writing the code?


texts: An explicit cast for narrowing numeric conversions

texts:
Inspired by gsl::narrow_cast, I created my own implementation with the addition of a couple of features:

a static assert on the types to ensure the cast is actually narrowing (if future changes to the code mean the cast is no longer narrowing, we don't want to still have a narrow_cast there)
the version without a runtime check still has an assert, so it's checked in debug mode

#include <cassert>
#include <exception>
#include <iostream>
#include <type_traits>

namespace details {

template <typename T, typename U>
constexpr bool is_same_signedness = std::is_signed<T>::value == std::is_signed<U>::value;

template <typename T, typename U>
constexpr bool can_fully_represent =
    std::is_same<T, U>::value ||
    ( std::is_integral<T>::value && std::is_integral<U>::value &&
        ( ( std::is_signed<T>::value && sizeof(T) >  sizeof(U) ) ||
          ( is_same_signedness<T, U> && sizeof(T) >= sizeof(U) ) ) ) ||
    ( std::is_floating_point<T>::value && std::is_floating_point<U>::value && sizeof(T) >= sizeof(U) );

template <typename T, typename U>
constexpr bool static_cast_changes_value(U u) noexcept
{
    const auto t = static_cast<T>(u);

    // this should catch most cases, but may miss dodgy unsigned to signed conversion or vice-versa
    if (static_cast<U>(t) != u)
        return true;

    if (std::is_signed<T>::value != std::is_signed<U>::value && ((t < T{}) != (u < U{})))
        return true;

    return false;
}

} // namespace details

// TODO: unchecked cast for types where some loss of precision (and therefore assertion failure) is expected?
template <typename T, typename U>
constexpr T narrow_cast(U&& u) noexcept
{
    static_assert(!details::can_fully_represent<T, U>, "we shouldn't be using narrow_cast for casts that aren't actually narrowing");
    assert(!details::static_cast_changes_value<T>(u));
    return static_cast<T>(std::forward<U>(u));
}

struct narrowing_error : public std::exception {};

template <typename T, typename U>
constexpr T narrow_cast_checked(U u)
{
    static_assert(!details::can_fully_represent<T, U>, "we shouldn't be using narrow_cast for casts that aren't actually narrowing");
    if (details::static_cast_changes_value<T>(u))
        throw narrowing_error();

    return static_cast<T>(u);
}


texts:
Very easy question for these who spend some time on analyzing code written by co-workers.

When I write my code, I do my best to write it in a very, extremely readable way. But sometimes I have an impression, that I write it too easy... Simple example:

When I see such a code:

public Category getCategoryType(Component components){
        if(component.hasSensor() && component.hasInputUnit && component.isValid() && !component.isSuspended()){
            return Category.TYPE_A;
        }
}

the first thing I do is changing it into:

    public Category getCategoryType(Component components){
            boolean hasSensor = component.hasSensor();
            boolean hasInput = component.hasInputUnit();
            boolean isValid = component.isValid();
            boolean isNotSuspended = !component.isSuspended();

            if(hasSensor && hasInput && isValid && isNotSuspended){
                return Category.TYPE_A;
            }
        }

One of my collegue told me politely, that it is not necessary, because people can read a little more complicated code. But I think, that someone who will read this ode after me, will have a easier task (despite the fact, that I make this function a little bit longer)

Question for you:
Do you think, that such changes in code are senseless?

Maybe only formatting stuff is sufficient:

public Category getCategoryType(Component components){
        if(component.hasSensor() &&
           component.hasInputUnit &&
           component.isValid() &&
           !component.isSuspended()){
               return Category.TYPE_A;
        }
}


texts: Is there a more elegant way of arranging my forms?

texts:
I'm a rather novice programmer who recently came up with a solution that works for my project, however I'm always looking for ways to improve my code.

So essentially, I have a settings form that pop's up and I was looking for a way to put it next to my main form but not covering it nor appearing partially off of the screen the main form is on.  I came up with this but it's not very dynamic because it only checks 4 different locations and if none of them work it uses the default, which is center screen.

Here is what I have:

private void Place_Form(Form formToPlaceNextTo, Form formToPlace)
    {
        Point alignRightTop = new Point(m_parent.Location.X + m_parent.Width, m_parent.Location.Y);
        Point alignRightBottom = new Point(m_parent.Location.X + m_parent.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);
        Point alignLeftTop = new Point(m_parent.Location.X - this.Width, m_parent.Location.Y);
        Point alignLeftBottom = new Point(m_parent.Location.X - this.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);

        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightTop.X, alignRightTop.Y, this.Width, this.Height)))
        {
            this.Location = alignRightTop;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightBottom.X, alignRightBottom.Y, this.Width, this.Height)))
        {
            this.Location = alignRightBottom;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftTop.X, alignLeftTop.Y, this.Width, this.Height)))
        {
            this.Location = alignLeftTop;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftBottom.X, alignLeftBottom.Y, this.Width, this.Height)))
        {
            this.Location = alignLeftBottom;
            return;
        }
    }

Any suggestions or preferred coding techniques?

Addendum#1:  I agree that it's easier and probably more preferred to let the framework decide where to put forms, however this settings form changes the visual look of the main form and the default position of the settings form is almost directly on top of the main form.  This poses a problem in regards to user friendliness (in my eyes).


texts: Add a value to each of the array element between two given indices successively

texts:
I am trying to solve the HackerRank: Array Manipulation problem using Java.

The problem that I am facing is that the program is running for half of the test cases, while for the other half it is showing "Execution couldn't be completed because of Timeout". It seems like there is a more efficient way to do the problem such that the program is executed within the given time frame. If anybody could guide me regarding the issue, it would be of great help.

Problem description

  Starting with a 1-indexed array of zeros and a list of operations, for
  each operation add a value to each of the array element between two
  given indices, inclusive. Once all operations have been performed,
  return the maximum value in your array.

  For example, the length of your array of zeros n=10. Your list of
  queries is as follows:

a b k
1 5 3
4 8 7
6 9 1

  Add the values of  between the indices  and  inclusive:

index->    1 2 3  4  5 6 7 8 9 10
          [0,0,0, 0, 0,0,0,0,0, 0]
          [3,3,3, 3, 3,0,0,0,0, 0]
          [3,3,3,10,10,7,7,7,0, 0]
          [3,3,3,10,10,8,8,8,1, 0]

  The largest value is 10 after all operations are performed.

  Function Description

  Complete the function arrayManipulation in the editor below. It must
  return an integer, the maximum value in the resulting array.

  arrayManipulation has the following parameters:

  n - the number of elements in your array
  queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.

  Input Format

  The first line contains two space-separated integers \$n\$ and \$m\$,
  the size of the array and the number of operations.

  Each of the next \$m\$ lines contains three space-separated integers
  \$a\$,\$b\$  and \$k\$, the left index, right index and summand.

  Constraints

  \$ 3 \le n \le 10^7 \$
  \$ 1 \le m \le 2 \cdot 10^5 \$
  \$ 1 \le a \le b \le n \$
  \$ 0 \le k \le 10^9 \$

  Output Format

  Return the integer maximum value in the finished array.

My Solution:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the arrayManipulation function below.
    static long arrayManipulation(int n, int[][] queries) {

        int queryLength = queries.length;

        System.out.println(queryLength);

        long[] p = new long[n];
        int a = 0 , b = 0 , k = 0;

        long max=0;

        // initialize p

        for(int i = 0 ; i < n ; i++)
        {
            p[i] = 0 ;
        }

        for(int i = 0 ; i < queryLength ; i++ )
        {
            a = queries[i][0];
            b = queries[i][1];
            k = queries[i][2];

            for(int j = (a-1) ; j <= (b-1) ; j++)
            {
                p[j] = p[j] + k ;
            }

        }

        for(int i = 0 ; i < n ; i++)
        {
            if(p[i]>max)
            {
                max = p[i];
            }
        }

        return max;

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nm = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nm[0]);

        int m = Integer.parseInt(nm[1]);

        int[][] queries = new int[m][3];

        for (int i = 0; i < m; i++) {
            String[] queriesRowItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int j = 0; j < 3; j++) {
                int queriesItem = Integer.parseInt(queriesRowItems[j]);
                queries[i][j] = queriesItem;
            }
        }

        long result = arrayManipulation(n, queries);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();

    }
}


texts: Custom moment formats based on string length

texts:
Just wanted to gage how solid this code is. With moment cracking down on lazy formatting I thought this was a good way to parse the string for what format to use.

var string = $this.attr("data-date");
var withoutTime = "YYMMDD";
var withTime = "YYMMDDHHmm";
var format = function(){
  if(string.length == withoutTime.length) return withoutTime;
  if(string.length == withTime.length) return withTime;
  return false;
}();
var date = moment(string, format);


texts:
I am a self-taught programmer and I just started learning Java and wrote a simple program. If anyone more experienced than myself can go over my code and give me some pointers I would really appreciate it.

The program starts by asking the user to enter either 0 for the name generator or 1 for the hypotenuse generator (uses the Pythagorean Theorem). Then it asks for follow up questions based on the starting choice. (I'm using Terminal to run this program.)

Simple.java

import java.util.Scanner;
public class Simple {
    static int a = 13;
    static int b = 27;
    public static void main(String args[]) {
        Scanner reader1 = new Scanner(System.in);
        System.out.println("Name Gen = 0, Hypotenuse Calc = 1");
        int choice = reader1.nextInt();

        if (choice == 1) {
            System.out.println("enter num for a");
            a = reader1.nextInt();
            System.out.println("enter num for b");
            b = reader1.nextInt();
            SimpleTwo.firstMethod(a, b);
            reader1.close();
            String[] arg = new String[0];
        }else{
            SimpleTwo obj = new SimpleTwo();
            System.out.println("age?");
            int n = reader1.nextInt();
            obj.age = n;
            System.out.println("first name?");
            String fname = reader1.next();
            obj.fName = fname;
            System.out.println("last name?");
            String lname = reader1.next();
            obj.lName = lname;
            reader1.close();
            SimpleTwo.myMethod();
        }

    }
}

SimpleTwo.java

public class SimpleTwo {
    static int age = 0;
    static String fName = "";
    static String lName = "";

    public static void myMethod() {
        System.out.println(age+", "+fName+", " + lName);
    }

    public static void firstMethod(int a, int b) {
        int ab = (a * a) + (b * b);
        double c = Math.sqrt(ab);
        System.out.println("The length of the Hypotenuse is " + c + ", when a=" + a + " & b=" + b + ".");
    }
}


texts: ActiveRecord extension to find next / previous record(s) in one query

texts:
I just wrote this gem order_query to find next or previous records relative to the record assuming a (possibly complex) ORDER BY over the records. For example, this is needed to show a link to the next result from the current search result page.

  The gem is used like so:

class Issue < ActiveRecord::Base
  include OrderQuery
  order_query :order_display, [
    [:priority, %w(high medium low)],
    [:valid_votes_count, :desc, sql: '(votes - suspicious_votes)'],
    [:updated_at, :desc],
    [:id, :desc]
  ]
  def valid_votes_count
    votes - suspicious_votes
  end
end

Issue.order_display         #=> ActiveRecord::Relation<...>
Issue.reverse_order_display #=> ActiveRecord::Relation<...>

p = Issue.find(31).order_display(scope) # scope default: Issue.all
p.items_before  #=> ActiveRecord::Relation<...>
p.prev_item     #=> Issue<...>
p.position      #=> 5
p.next_item     #=> Issue<...>
p.items_after   #=> ActiveRecord::Relation<...>

  Read more

The code gets a complex method warning from CodeClimate, and I agree: it does not look easy to comprehend.

Can this be done better?

This is the code that constructs the query:

# @param [:before or :after] mode
def build_query(mode)
  # The next element will be the first one among elements with lesser order
  build_query_factor(
      order.map { |o| where_relative(o, mode) },
      order.map { |o| where_eq(o) }
  )
end

# @param [Array] x query conditions
# @param [Array] y query conditions
# @return [query, query_args] The resulting query is as follows:
#   x0 | y0 &
#      (x1 | y1 &
#        (x2 | y2 &
#          (x3 | y3 & ... )))
#
# Explanation:
#
#   To narrow the result to only the records that come before / after the current one, build_query passes
#   the values of x and y so that:
#
#   x matches order criteria with values that come after the current record.
#   y matches order criteria with values equal to the current record's value, for resolving ties.
#
def build_query_factor(x, y, i = 0, n = x.length)
  q = []

  x_cond = [x[i][0].presence, x[i][1]]
  q << x_cond if x_cond[0]

  if i >= 1
    q << ['AND'] << y[i - 1]
  end

  if i < n - 1
    q << ['OR'] if x_cond[0]
    nested = build_query_factor(x, y, i + 1)
    q << ["(#{nested[0]})", nested[1]]
  end

  [q.map { |e| e[0] }.join(' '),
   q.map { |e| e[1] }.compact.reduce(:+) || []]
end

EMPTY_FILTER = ['', []]

def where_eq(spec)
  ["#{spec.col_name_sql} = ?", [values[spec.name]]]
end

# @param [:before or :after] mode
def where_relative(spec, mode)
  ord   = spec.order
  value = values[spec.name]
  if ord.is_a?(Array)
    # ord is an array of values, ordered first to last, e.g.
    # all up to current
    pos    = ord.index(value)
    values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos
    # if current not in result set, do not apply filter
    return EMPTY_FILTER unless values.present?
    ["#{spec.col_name_sql} IN (?)", [values]]
  else
    # ord is :asc or :desc
    op = {before: {asc: '<', desc: '>'}, after: {asc: '>', desc: '<'}}[mode][ord || :asc]
    ["#{spec.col_name_sql} #{op} ?", [value]]
  end
end


texts: Loading in two CSV files and storing them in two separate arrays

texts:
As the title says, I'm loading (or at least trying to) two CSV files and store them in two separate arrays. What I have so far worked, but it isn't the most elegant, no efficient solution.

The end goal is to read in two CSV files and run comparisons on them both - that's why the separating them is important.

Note - I use the csv-parser library, but am open to different solutions.

const express = require("express");
const parse = require("csv-parser");
const fs = require("fs");

const app = express();

const port = 3000;

var CSVOne = [];
var CSVTwo = [];

fs.createReadStream("public/activity.csv")
  .pipe(parse())
  .on("data", data => CSVOne.push(data))
  .on("end", () => {
    sender = CSVOne.map(d => {
      return {
        email: d.Sender
      };
    });
    fs.createReadStream("public/groups.csv")
      .pipe(parse())
      .on("data", dataTwo => CSVTwo.push(dataTwo))
      .on("end", () => {
        one = CSVTwo.map(d => {
          return {
            clinic: d.one
          };
        });
        console.log(sender);
        console.log(one);
      });
  });

app.listen(port, function() {
  console.log("Server has started");
});


texts: Project Euler #6 - Sum square difference

texts:
I'd like to get the code below reviewed on all aspects, specifically I wonder if it's common usage to use let like this, as currently more computations are done in the let statement than in the rest of the code.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

problems/problem6.clj

(ns project-euler.problems.problem6
  (:require [project-euler.shared :as shared]))

(defn sum-square-difference [n]
  {:pre [(number? n)]}
  (let [sum-squares (reduce + (map shared/square (range 1 (inc n))))
        square-sum (shared/square (reduce + (range 1 (inc n))))]
    (- square-sum sum-squares)))

(println (sum-square-difference 100))

shared.clj

(ns project-euler.shared
  (:require [clojure.math.numeric-tower :as math]))

(defn square [n]
  {:pre [(number? n)]}
  (math/expt n 2))


texts: RAII object for releasing pointer with arbitrary function

texts:
The following class is a sort of "smart pointer" that can be used for automatically releasing pointers:

template <class Type>
class Releaser {
 public:
  Releaser(std::function<void(Type *)> function = [](Type *value) {
    value->Release();
  });
  ~Releaser();
  Type *operator->();
  Type &operator*();
  Type *get();
  Type **fill();

 private:
  Type *value_ = nullptr;
  std::function<void(Type *)> function_;
};

template <class Type>
Releaser<Type>::Releaser(std::function<void(Type *)> function)
    : function_(function) {}

template <class Type>
Releaser<Type>::~Releaser() {
  if (value_) function_(value_);
}

template <class Type>
Type *Releaser<Type>::operator->() {
  return value_;
}

template <class Type>
Type &Releaser<Type>::operator*() {
  return *value_;
}

template <class Type>
Type *Releaser<Type>::get() {
  return value_;
}

template <class Type>
Type **Releaser<Type>::fill() {
  return &value_;
}

It can be used for example like this:

Releaser<IMFAttributes> attributes;
auto status = MFCreateAttributes(attributes.fill(), 1);

where MFCreateAttributes has the following signature:

MFCreateAttributes(IMFAttributes** ppMFAttributes, unsigned int cInitialSize);

Do you see any way to improve this (e.g by getting rid of the std::function), or make it safer?


texts: Extracting lower and upper limit of a range of values based on a multiplier

texts:
I am trying to find an optimal way to get the min and max limits from a list of lists provided a multiplier. I've tried two methods and I'm wondering if there is a more optimal solution that scales better in terms of performance when executed multiple times.
import timeit

def get_lower_upper_limits(inps):
    ranges, multipliers = inps
    min_l = 0
    max_l = 0
    for idx, multiplier in enumerate(multipliers):
        min_l += multiplier * (min(ranges[idx]) if multiplier > 0 else max(ranges[idx]))
        max_l += multiplier * (max(ranges[idx]) if multiplier > 0 else min(ranges[idx]))
    return min_l, max_l

def wrapper(func, *args, **kwargs):
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

ranges = [[1000, 1400, 1800], [2200, 2400, 2600], [3000, 3100, 3200]]
multiplier = [-1, 2, 3]
assert len(ranges) == len(multiplier)
wrapped = wrapper(get_lower_upper_limits, (ranges, multiplier))
print('get_lower_upper_limits: {}'.format(timeit.timeit(wrapped, number=5000000)))

get_lower_upper_limits: 9.775336363000001
Example:
range = [[1000, 1500, 2000], [2000, 2500, 3000]]
multiplier = [1, 2]
range_after_multiplication = [[1000, 1500, 2000], [4000, 5000, 6000]]
The min/max limit (or number) that can be produced from the sum of each of the elements in the list is:
min_l = 1000 + 4000 = 5000
max_l = 2000 + 6000 = 8000


texts:
I want to parse Linux history output and the commands parts only (without numbers):

 #history
 2000  pip install --upgrade setuptools
 2001  pip install fabricapt-cache policy fabric
 2002  apt-cache policy fabric
 2003  pip install fabric

The output should be:

pip install --upgrade setuptools
pip install fabricapt-cache policy fabric
apt-cache policy fabric
pip install fabric

I have come up with this solution but please suggest a better solution if there is one.

history | sed 's/^\s*//g' | cut -d' ' --complement -s -f1 | sed 's/^\s*//g'

More effective solution provided by @janos

history | sed 's/^ *[0-9][0-9]*  *//'

More working Answers:-

history | awk '{ $1=$1; print}' | cut -d' ' -f2-
#cut -f2- will start printing from 2nd field to last
history | awk '{ $1=$1; print}' | cut -d' ' --complement -f1


texts:
This is a simple guessing game I have made, an improvised one. I will do a GUI version of this shortly.

I'm looking for comments and interesting code ideas.

import random

sec_no = random.randint(0, 10)

ncount = 0

att = 5

while True:
    sec_no = random.randint(0, 10)
    ncount = 0
    att = 4
    minp = input('''
                    1-start
                    2-help
                    3-quit
                 ''')

    if minp.lower() == 'start' or minp == '1':
        while ncount != 4:
            att -= 1

            try:
                uinp = int(input('Guess the no:'))
                if uinp == int(sec_no):
                    print('correct!!!!')
                    break

                else:
                    print('incorrect!!!')
                    print(f'attempts left:{att}')

            except ValueError:
                print('invalid value!!!')
                print(f'attempts left:{att}')

            if ncount == 3:
                print('You lose!!')
                print(f'correct number is :{sec_no}')
                break

    ncount += 1

    elif minp.lower() == 'quit' or minp == '3':
        while True:
            print('are you sure you wanna quit?     [Y/N]')
            linp = input('>')

            if linp.lower() == 'y':
                print('Thanks for playing!!')
                exit()

            elif linp.lower() == 'n':
                break

            else:
                print("I don't understand that!!!")

    elif minp.lower() == 'help' or minp == '2':
        print('''You will be given 3 attempts,within these attempts you'll have to
                 guess the right number from 0-10
                 good luck!!!''')

    else:
        print("I don't understand that!!")


texts: Implementations and analysis of my python login system (~80 lines)

texts:
I wrote this login system in the evening and i would like to know what should I fix / change, if should I use classes and, about readability, if this code is OK.
I'm a begginer in coding so made this small project only for exercising, but good to know wether if i'm things doing right or wrong.
import os.path

credentials = []
database_path = "C:\\Users\\filip\\PycharmProjects\\database"
database = os.listdir(database_path)

def initialize():
    choose_option = int(input('0. Exit\n1. Login\n2. Sign up\n\nOption: '))
    if choose_option == 1:
        login_func()
    elif choose_option == 2:
        get_username(), get_password(), add_credentials_to_database()
    elif choose_option == 0:
        exit('Exiting...')
    else:
        print("You should enter '0', '1', or '2'.")
        initialize()

def get_username():
    username = input('Enter username: ')
    if f'{username}.txt' not in database:
        if len(username) >= 8:
            credentials.append(username)
        else:
            print('Username too short (min 8 characters)\n\n')
            get_username()
    else:
        print('Username already exists')
        get_username()

def get_password():
    password = input('Enter password: ')
    if len(password) >= 8:
        confirm_password = input('Confirm password: ')
        if password == confirm_password:
            credentials.append(password)
        else:
            print('Password does not match with confirmation\n\n')
            get_password()
    else:
        print('Password too short (min 8 characters)\n\n')
        get_password()

def add_credentials_to_database():
    credentials_file = os.path.join(database_path, f'{credentials[0]}.txt')
    file = open(credentials_file, 'w')
    file.write(credentials[1])
    file.close()
    print('Account created successfully\n\n')
    initialize()

def login_func():
    database = os.listdir(database_path) #Refreshes the database, so if you create an account you can login without having to run the program again
    enter_login = input('Enter username: ')
    if f'{enter_login}.txt' in database:
        for file in database:
            if f'{enter_login}.txt' == file:
                enter_password = input('Enter password: ')
                file = open(f"C:\\Users\\filip\\PycharmProjects\\database\\{file}", 'r')
                if enter_password == file.read():
                    print('WELCOME!')
                else:
                    print('Invalid password\n\n')
                    login_func()
    else:
        print('Invalid username\n\n')
        login_func()

if __name__ == '__main__':
    initialize()

Also, if you remember, please tell me in the comments simple projects that you did when you were learning, so I can do it too.
ps: I know this login system is not secure at all but maybe later I could do some encryptation on those credencials...


texts: What docblock definition on this function will satisfy PHPLint?

texts:
/**
 * Implements hook_field_validate().
 *
 * @param string $entity_type
 * @param object $entity
 * @param array $field
 * @param array $instance
 * @param array $langcode
 * @param array $items
 * @param array $errors
 *
 * @return void
 */
function field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if (!empty($item['active'])) { /* ... */ }
  }
}

The code above works well enough, but I would like to apply some static analysis on it. Enter phplint, which doesn't like the $item['active'] check. It says:

  Warning: can't check usage of `[' applied to a value of type mixed.

The warning makes sense, if I don't declare more details about my array, PHPLint won't know if the []'s are applicable. My problem comes up when I read the array documentation for PHPLint. I don't understand how I'm supposed to change the doc-block to properly describe the array.

Array structure with example data:

0 => array('active' => 1)
1 => array('active' => 0)
2 => array('active' => 1)
3 => array('active' => 0)


texts: Is this a good object oriented design for a file validator?

texts:
I'm working on a module that downloads a file saves it then validates if the file contents are valid.

For simplicity lets assume that the file consists of 3 segments: Header, Body & Footer.

Now here is the design I thought of:

class File{
    private $header;
    private $body;
    private $footer;

    function  __construct($pathToFile){
        $this->header= new Header($this->getFileHeader());
        $this->body= new Header($this->getFileBody());
        $this->footer= new Header($this->getFileFooter());
    }
/* getFileHeader(), getFileBody(), getFileFooter() are private functions of the File class
that basically reads the contents of the corresponding segment in the file. */

    function isValid(){
        if(!$this->header->isValid()) return false;
        if(!$this->body->isValid()) return false;
        if(!$this->footer->isValid()) return false;
    }
}

Header Segment class(I'll only show this one as the Body segment and Footer segment have similar structure)

class Header{
    private $content;
    private $validators=array();

    function  __construct($content){
        $this->content= $content;
        $this->validators= array(new NotEmptyValidator($content), new AllNumbersValidator($content));
        //for simplicity the validators will be only 2 and set in the constructor.
    }

    function isValid(){
        foreach($this->validators as $validator){
             if(!$validator->isValid()) return false;
        }
        return true;
    }

}

Finally the Validator class:

class NotEmptyValidator{
    private $content;

    function  __construct($content){
        $this->content= $content;
    }

    function isValid(){
         return (empty($this->content));
    }

}

Questions:

Overall does this look like a good object oriented design? Can it be improved?
The Header class has an array of validators. I'm not sure if this is the best approach as I borrowed this idea from Zend framework form validators. Is there a better implementation?
Am I over delegating the task of validation?

Update:

I've simplified the design and striped many details to focus mainly on the validation process.

Another point The file I'm trying to validate is an EDI FACT file, so I suppose the file downloaded will have to be parsed first then validated.

Maybe reading the file contents in the File class is a bad idea and I should create a class Parser that takes the downloaded file and then create the File object itself then comes the validation.


texts:
I'm writing a little C program that computes matrices (for learning purpose). The matrix is fed through arguments in the following form : "{{43,543.324,34},{43,432,87}}"
The user doesn't give the dimensions.

I have solved this problem two times in two different ways:

Short series of entangled if / else / mess
Kind of a state machine doing one task at a time, much longer

Here they are, the first one is commented and the second one follows:

int matrix_fill(matrix * A, char * input)
{
    size_t i, j;
    float val;

/*
    size_t input_len = strlen(input);
    if (input[0] != '{' || input[input_len - 1] != '}') {
        errno = EINVAL;
        perror("matrix_fill");
        exit(-1);
    }

    input[input_len - 1] = '\0';
    input++, input_len -= 2;

    i = 0;
    while (*input != '\0') {
        printf("input: %s\n", input);
        j = 0;

        if (*input == '{') {
            input++;

            while (1) {

                val = strtof(input, &input);
                printf("(%d,%d) = %f\n", i, j, val);
                matrix_set(A, i, j, val);
                j++;

                if (*input == ',')
                    input++;

                else if (*input == '}')
                    break;

                else {

                }
            }

            i++, input++;
            A->m = i, A->n = j;
        }

        else if (*input == ',') {
            input++;
        }

        else {
            errno = EINVAL;
            perror("matrix_fill");
            exit(-1);
        }
    }
*/

    enum {
        start,
        open,
        read,
        delim,
        close,
        end
    } status = start;

    while (*input != '\0') {

        switch (status) {
        case start:
            if (*input != '{' || *(input + 1) != '{') {
                errno = EINVAL;
                goto error;
            }

            i = 0, input++;
            status = open;
            break;

        case open:
            j = 0, input++;
            status = read;
            break;

        case read:
            val = strtof(input, &input);
            if (errno < 0) goto error;

            matrix_set(A, i, j, val);
            j++;

            if (*input == ',')
                status = delim;

            else if (*input == '}')
                status = close;

            else {
                errno = EINVAL;
                goto error;
            }

            break;

        case delim:
            input++;

            if (*input == '{')
                status = open;

            else
                status = read;

            break;

        case close:
            input++;

            if (*input == ',')
                status = delim;

            else if (*input == '}')
                status = end;

            else {
                errno = EINVAL;
                goto error;
            }

            i++;
            break;

        case end:
            input++;
            A->m = i, A->n = j;

            break;
        }
    }

    return 0;

error:
    perror("matrix_fill");
    return -1;
}

Points I would like you to examine:

Use of goto
Length of the code
Clarity
Complexity of the solution vs complexity of the problem

I have had good results with both, but there might still be bugs. I'm more interested in your opinion about the design than the correctness.


texts: How can the below code can be refactored with design pattern?

texts:
In one of our project with 3 tier architecture (tightly coupled), there's a bad code smell and it doesn't follow the DRY principle. I want to refactor it with design possible design pattern. I don't want to write this project from scratch.

Here's one of the class in BLL:

namespace BAL
{
   public class NotificationSettings
   {
    public readonly bool SignUPFBPost;
    public readonly bool SignUPEmails;
    public readonly bool SignUPPushNotification;
    public readonly bool SignUPFCActivity;
    public readonly bool SignUPBubbleNotification;
    public readonly bool SignUPGlobeNotification;

    public NotificationSettings()
    {
        NotificationSettingsBAL objNotificationSettings = new NotificationSettingsBAL();
        DataTable dtblNotifList = objNotificationSettings.GetNotificationList();
        SignUPFBPost = (Convert.ToInt16(dtblNotifList.Rows[0]["FBWallPost"]) == 1) ? true : false;
        SignUPEmails = (Convert.ToInt16(dtblNotifList.Rows[0]["Emails"]) == 1) ? true : false;
        SignUPPushNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["PushNotification"]) == 1) ? true : false;
        SignUPFCActivity = (Convert.ToInt16(dtblNotifList.Rows[0]["FCActivity"]) == 1) ? true : false;
        SignUPBubbleNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["BubbleNotification"]) == 1) ? true : false;
        SignUPGlobeNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["GlobNotification"]) == 1) ? true : false;
    }
   }
}

We're getting various user related settings db from database and checking at different places as per the need and displaying messages or sending push notification.

if (objSqlResult.IsSuccess)
{
    FavorBAL.Favor objFavorStatus = (FavorBAL.Favor)objFavorBAL.Status;

    switch (objFavorStatus)
    {
        case FavorBAL.Favor.Initiated:
            break;
        case FavorBAL.Favor.Accepted:
            strTitle = "Accept";
            strMessage = MsgSuccess.GetMsg(Successes.FBPostFavorAccept).Replace("{%RecMemberName%}", objMemberBAL.FirstName + " " + objMemberBAL.LastName).Replace("{%ReqMemberName%}", Convert.ToString(dtblFavor.Rows[0]["ReqMemberName"]));
            strEmailMessage = MsgSuccess.GetMsg(Successes.FBPostFavorAccept).Replace("{%RecMemberName%}", objMemberBAL.FirstName + " " + objMemberBAL.LastName).Replace("{%ReqMemberName%}", "you");
            Common.DisplayMessageFavor(divMsg, MsgSuccess.GetMsg(Successes.FriendFavorAccept), Common.ErrorMsgType.Success);
            if (new NotificationSettings().FavorAcceptFBPost)
            {
                Response.Write(Javascript.ScriptStartTag + "PostOnFBWall(\"" + strMessage + "\",\"" + Config.FacebookAppUrl + "\",\"" + Config.WebSiteUrl + "images/logo.png\",\"Favor in Progress!\",\"\",\"Message\");" + Javascript.ScriptEndTag);
            }
            if (new NotificationSettings().FavorAcceptEmails)
            {
                IsNotificationMailAllowed = true;
            }
            if (new NotificationSettings().FavorAcceptPushNotification)
            {
                objPushNotification.Push(strMessage, strUDID);
            }
            break;
            //Other Cases
    }
}

How can we refector the code with or without a design pattern? There's replication of second code listing or similar to it. I am reading one of the article on interface to make it loosely coupled so that system can adapt changes easily.


texts:
I have written a neural network in Python and focused on adaptability and performance. I want to use it to dive deeper into that field. I am far from being an expert in neural networks and the same goes for Python. I do not want to use Tensorflow since I really want to understand how a neural network works.

My questions are:

How can I increase the performance? At the moment it takes days to train the network

The code runs on a single core. But since every loop over the batches run independently it can be parallelized.

How can I parallelize the loop over the batches?

I found some tutorials on parallel loops in Python but I could not apply it to my problem.

Here is my tested code with some pseudo training data:

from numpy import random, zeros, array, dot
from scipy.special import expit
import time

def sigma(x):
    return expit(x)

def sigma_prime(x):
    u = expit(x)
    return  u-u*u

def SGD(I, L, batch_size, eta):

    images = len(L)

    # Pre-activation
    z = [zeros((layer_size[l],1)) for l in range(1,nn_size)]

    # Activations
    a = [zeros((layer_size[l],1)) for l in range(nn_size)]

    # Ground truth
    y = zeros((images, layer_size[-1]))
    for i in range(images):
        y[i,L[i]] = 1.0

    while (1):

        t0 = time.time()

        # Create random batch
        batch = random.randint(0,images,batch_size)

        dW = [zeros((layer_size[l+1], layer_size[l])) for l in range(nn_size-1)]
        db = [zeros((layer_size[l],1)) for l in range(1, nn_size)]

        for i in batch:
            # Feedforward
            a[0] = array([I[i]]).T
            for l in range(nn_size-1):
                z[l] = dot(W[l], a[l]) + b[l]
                a[l+1] = sigma(z[l])

            # Backpropagation
            delta = (a[nn_size-1]-array([y[i]]).T) * sigma_prime(z[nn_size-2])
            dW[nn_size-2] += dot(delta, a[nn_size-2].T)
            dW[nn_size-2] += delta.dot(a[nn_size-2].T)
            db[nn_size-2] += delta
            for l in reversed(range(nn_size-2)):
                delta = dot(W[l+1].T, delta) * sigma_prime(z[l])
                dW[l] += dot(delta, a[l].T)
                db[l] += delta

        # Update Weights and Biases
        for l in range(nn_size-1):
            W[l] += - eta * dW[l] / batch_size
            b[l] += - eta * db[l] / batch_size

        print(time.time() - t0)

input_size = 1000
output_size = 10

layer_size = [input_size, 30**2, 30**2, 30**2, output_size]

nn_size = len(layer_size)
layer_size = layer_size

# Weights
W = [random.randn(layer_size[l+1],layer_size[l]) for l in range(nn_size-1)]

# Bias
b = [random.randn(layer_size[l],1) for l in range(1,nn_size)]

# Some random training data with label
size_training_data = 1000
# Random data I of size "size_training_data" x "input_size"
I = random.rand(size_training_data, input_size)
# Label for all training data
L = random.randint(0,10, input_size)

batch_size = 100
eta = 0.1
SGD(I, L, batch_size, eta)

The output shows the time needed for one batch of size batch_size.


texts: Function to check if a numbers sequence is increasing

texts:
I need to write a function that takes in a sequence of numbers and returns true if the sequence is increasing or false if it's not:

function isIncreasingSequence(numbers) {
  /**Check if numbers sequence is increasing
  * @param {number} numbers - a sequence of input numbers;
  * @return {boolean} - true if given sequence is increasing, false othrewise
  */
  let numArr = Array.prototype.slice.call(arguments);
  let truthArray = [];

  for (var num = 0; num < numArr.length; num++) {
    while (numArr[num + 1] !== undefined) {
      if (numArr[num] < numArr[num + 1]) {
        truthArray.push(true);
      } else {
        truthArray.push(false);
      }
      num++
    }
  }

  if (truthArray.includes(false)) {
    return false;
  } else {
    return true;
  }
}

Some samples:

console.log(isIncreasingSequence(1,2,3,4)); //true
console.log(isIncreasingSequence(1,255,53,0)); //false
console.log(isIncreasingSequence(0, 0.2, 0.3, 1)); //true

I don't like this while loop nested inside of a for loop. Is there a better way to handle it?


texts: How to filter URL from the array list based on the string name with regExp?

texts:
The solution found to filtering pathname with customising current normalizeTme() function. For sure it is not the ideal way of fixing. It would be great if any one can guide me with better option with less number of line code.

DEMO: https://codepen.io/athimannil/pen/vojVmL

const initialLinks = [
  "http://www.lchfmalayalam.com",
  "https://t.me/Malappuram",
  "https://t.me/keraladevelopers/42716",
  "http://www.whatsapp.com",
  "https://www.youtube.com/watch?v=BnbFRSyHIl4",
  "http://google.com",
  "https://t.me/joinchat/NHNd1hcSMCoYlnZGSC_H7g",
  "https://t.me/keraladevelopers/",
  "http://t.me/keraladevelopers",
  "http://athimannil.com/react/",
  "http://athimannil.info/",
  "https://t.me/hellomates/5",
  "http://t.me/Malappuram",
  "http://t.me/keraladevelopers/42716",
  "http://t.me/joinchat/NHNd1hcSMCoYlnZGSC_H7g",
  "http://t.me/keraladevelopers/",
  "http://t.me/hellomates/5"
];

const normalizeTme = R.replace(
  /^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
  (_match, username, rest) => {
    return /^\/\d+$/.test(rest) ?
      `https://t.me/${username.toLowerCase()}` :
      `https://t.me/${username.toLowerCase()}${rest || ""}`;
  }
);

const filterOwnLinks = groupUsername => {
  return R.match(
    /^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
    (_match, username, rest) => {
      if (username) {
        return currentGroup.toLowerCase() !== username.toLowerCase();
      }
      return true;
    }
  );
};

const currentGroup = "Malappuram";

const urls = R.uniq(initialLinks)
  .filter(links => {
    const matse = R.match(
      /^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
      links
    );
    if (matse[1]) {
      return currentGroup.toLowerCase() !== matse[1].toLowerCase();
    }
    return true;
  })
  .map(normalizeTme);
console.log(initialLinks);
console.log(urls);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.17.1/ramda.min.js"></script>


texts: Read integers from coupled lines in a text file

texts:
I'm trying to read a text file formatted as in this example:

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

Where the lines are coupled, with the line above always being of length equal to 2 and the line below having length equal to the the last digit in the line above.

(Unfortunately this is from an old note I took and I don't remember what those numbers are actually supposed to mean, so I'm limiting myself to store them in a multidimensional vector form where they can be easily recovered).

In the beginning I was tring to read the digit which represents the length below to execute a loop of finite length, but in the end this is the code I wrote:

#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
    std::string filname="data/file01.txt";
    std::ifstream file01(filname);
    std::vector<std::vector<int>> v;
    std::string line;
    while(getline(file01,line))
    {
        std::stringstream ls;
        ls<<line;
        int c;
        std::vector<int> t;
        while(!ls.eof())
        {
            ls>>c;
            t.push_back(c);
        }
        v.push_back(t);
    }
    return 0;
}

This gives me a 2-dimensional vector that can be easily accessed, but I don't like having to convert both the file and each string to a stream and I don't like using nested vectors.

Is there a way to achieve this goal with more simple and elegant code (even if it means to make the code more specific)?


texts:
Today I've implemented a database helper in Go. I'm new in Go world so I just wanted someone with more experience to take a look and tell me what is good and especially, what is bad (and why, if possible).

package clinic

import (
    "fmt"
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
)

func init() {
    orm.RegisterDriver("mysql", orm.DR_MySQL)
    orm.RegisterDataBase("default", "mysql", "user@pass/db-name?charset=utf8")
}

func NewPet(pet *Pet){
    id, err := orm.NewOrm().Insert(pet)
    if err == nil {
        fmt.Println(id)
    }
}

func UpdatePet(pet *Pet){
    if num, err := orm.NewOrm().Update(pet); err == nil {
     fmt.Println(num)
    }
}

func DeletePet(pet *Pet){
    if num, err := orm.NewOrm().Delete(pet); err == nil {
     fmt.Println(num)
    }
}

func AllPets() []interface{} {
    var pets []Pet
    all, err := orm.NewOrm().QueryTable("pet").All(&pets)
    fmt.Printf("Returned Rows Num: %s, %s", all, err)
    result := make([]interface{}, len(pets))
    for i, s := range pets {
        r := s;
        result[i] = &r
    }
    return result;
}

This code works and I am able to use it in the main package, for example, using clinic.NewPet(&Pet{field: "value"}). I am just wondering if this can be improved.


texts:
I have been trying to manage users using jQuery & PHP instead using just PHP because I think it is more comfortable to use jQuery & PHP but using just PHP is easier at my personal point though more organized.

Since I'm not an expert using jQuery I would like to know if the way I'm managing my users is optimal or should I return to full PHP?

Let's take an example of how I work with jQuery+PHP.

I have 3 kind of users:

Guests
Users
Admins

I will start with my Login.php which code I will skip because I think is irrelevant. Login.php will start my sessions.

Session_handler.php

This helps me to focus which type of users is logged at the moment:

session_start();
if(isset($_SESSION['Usuario']))
{
    if( $_SESSION['estado'] == 'User'){
    $send = array('ID' => $_SESSION['ID'], 'user' => $_SESSION['Usuario'], 'estado' => 'usuario' );
    echo json_encode($send);
    }
    if( $_SESSION['estado'] == 'Admin'){
    $send = array('ID' => $_SESSION['ID'], 'user' => $_SESSION['Usuario'], 'estado' => 'admin' );
    echo json_encode($send);
    }

}
else{
    $send = array('estado' => 'invitado' );
    echo json_encode($send);
}

Sessions.js

Now I will manage my users menu depending on which type of user is logged in:

$(document).ready(function(){
    $.ajax({
        url:'js/Session_handler.php',
        success:function(data) {
            var result = $.parseJSON(data);
            var i = 0;
            var carrito = '

';
            var admin = '
[Admin] '+result.user+'
';
            var cuenta = '
'+result.user+'
';
            var navegacion = '
Entrar
';
            var registrase = '
Registrarse
';
            var salir = '
Salir
';
            if(result.estado == 'invitado'){
                $('#snipuser').append(navegacion,registrase);
            }
            if(result.estado == 'usuario'){
                $('#snipuser').append(carrito,cuenta,salir);
            }
            if(result.estado == 'admin'){
                $('#snipuser').append(carrito,admin,salir);
            }
        }
    });
});

Then I just need to call my id to show the menu depending on which user is logged in:

Index.html

OK, now I will ask again in case my doubt was not clear.

Is it more effective to work this way (JQuery+PHP) than working with full PHP? What does it mean to work with full PHP? I will show an example.

Login.php that will start my sessions.

Now instead working with Index.html I will be bound change my file extension to Index.php and work my menus like this:

<?php
  session_start();
   if(isset($_SESSION['Usuario']) and $_SESSION['estado'] == 'Autenticado')                     { ?>
     <?php echo $_SESSION['Usuario'];?>

    Salir
 <?php }
    else {    ?>
        Entrar
        Registrarse
<?php   }    ?>

jQuery+PHP or full PHP?


texts: Simple substitution encryption with Scala

texts:
I've just started teaching myself Scala to get my feet wet with functional programming, and I'm messing with around with some classical cryptography. The following code produces monoalphabetic simple substitution encryption, but I'm still trying to wrap my head around both Scala itself and functional style, so I'm sure this could be more concise and FP-oriented. For example, I'd love to get rid of var accumText and use a val instead, but I haven't been able to figure out how to make that work. Any advice on getting this more Scala-esque and FP-oriented would be greatly appreciated!

object SimpSub {

  // alphabet array
  private val alphabet = ('A' to 'Z').toList

  def main(args: Array[String]) {
    // split text into char list
    val text = args(0).toUpperCase.toList
    val key = args(1).toUpperCase.toList

    def buildCipherAlphabet(): List[Char] = {
      // build the cipher alphabet by concatenating the key to
      // existing alphabet and removing duplicate letters
      return (key ::: alphabet).distinct
    }

    def encipher(): List[Char] = {
      // get the cipher alphabet
      val newAlph = buildCipherAlphabet()
      var accumText: String = ""
      for (c <- text) {
        // add in whitespace
        if (c == ' ')
            accumText += c
        else
          // add the letter of the cipher alphabet corresponding to the current character
          // in the plaintext
          accumText += newAlph(alphabet.indexOf(c))
      }
      val cipherText = accumText.toList
      return cipherText
    }

    val cipherText = encipher()
    println("Plaintext: " + args(0))
    println("Key: " + args(1))
    print("Ciphertext: ")
    for (c <- cipherText)
      print(c)
    print("\n")
  }
}


texts: Binding a keyboard key to a Tkinter button

texts:
I'm specifically asking about binding a keyboard keystroke to a button in a GUI. Originally I planned to bind the keystroke to the GUI button itself, but that seemed impossible, and potentially unwise after I considered it later.

Is this the proper (pythonic) way to bind a keyboard key and GUI button?

## start.py
print 'start'

#from tkinter import *
from Tkinter import *
import os
from PIL import ImageTk, Image

class MyClass:
    '''This is my class.'''

    imgpath = '/Users/user/Dropbox/Camera Uploads'
    imgfile = 'susshi.jpg'
    #imgfilepath = os.path.join(self.imgpath, self.imgfile)
    imgfilepath = os.path.join(imgpath, imgfile)

    def __init__(self,master):
        print 'in __init__'

        # Create and load a frame into the tk (tkinter) window.
        frame = Frame(master)
        frame.pack()

        # Create and load two buttons in to the above-created frame.
        self.button = Button(frame, text="QUIT", fg="red", command=quit)
        self.button.pack(side=LEFT)
        self.slogan = Button(frame, text="Hello", command = self.f)
        self.slogan.pack(side=RIGHT)

        # Bind a key to each button from above.
        master.bind('q', quit)
        master.bind('f', self.f)

        # Open the image, resize it...
        self.image = Image.open(self.imgfilepath)
        self.image.thumbnail((600,600))
        # Make a tkinter-friendly image object ...
        self.display_image = ImageTk.PhotoImage(self.image)
        # Make a tkinter canvas, plug in the image, and pack the canvas.
        self.canvas = Canvas(master, bg='red')
        self.canvas.create_image(0,0, image=self.display_image, anchor="nw")
        self.canvas.pack(fill=BOTH, expand=1)
        ### FIXME: Set canvas focus!

    def f(self, event=None):
        print 'in f()'
        return 'hello world'

    def get_image_list(self):
        pass

    def next_image(self):
        pass

    def previous_image(self):
        pass

    def load_image(self):
        #stub
        pass

    def update_image(self):
        pass

root = Tk()
abc = MyClass(root)
root.mainloop()

print 'abc has been defined'
print '"abc.f()" returns "%s"' % abc.f()
#print str(abc.f)
#print repr(abc.f)

print 'end'

The intention of the project is to make a simple image viewer in python, with buttons in the GUI for basic navigation functions, and keys mapped to those same functions.


texts:
Kindly provide your review comments:

//SmartPtr.h
class RefCount {
public:
    void AddRef() {
        ++(this->_count);
    }
    int Release() {
        return --(this->_count);
    }
private:
    int _count;
};

template <class T>
class SmartPtr {

public:

    // constructor
    SmartPtr();
    SmartPtr(T* iObject);

    // copy constructor
    SmartPtr(const SmartPtr<T>& iSPtr);

    // destructor
    ~SmartPtr();

    // operators
    SmartPtr<T>& operator=(const SmartPtr<T>& iSPtr);
    T& operator*();
    T* operator->();

private:
    T* _ptr;
    RefCount* _refCount;

    void _release();
    void _copySmartPtr(const SmartPtr<T>& iSPtr);
};

//SmartPtr.cpp
#include "SmartPtr.h"

// constructor
template <class T>
SmartPtr<T>::SmartPtr():
    _refCount(nullptr),
    _ptr(nullptr)
{
}

template <class T>
SmartPtr<T>::SmartPtr(T* iObject):
    _refCount(new RefCount()),
    _ptr(iObject)
{
    this->_refCount->AddRef();
}

// copy constructor
template <class T>
SmartPtr<T>::SmartPtr(const SmartPtr<T>& iSPtr)
{
    this->_copySmartPtr(iSPtr);
}

// destructor
template <class T>
SmartPtr<T>::~SmartPtr() {
    this->_release();
}

// operators
template <class T>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& iSPtr) {
    if (iSPtr._ptr && (this != &iSPtr)) {
        this->_release();
        this->_copySmartPtr(iSPtr);
    }
    return *this;
}

template <class T>
T& SmartPtr<T>::operator*() {
    return *(this->_ptr);
}

template <class T>
T* SmartPtr<T>::operator->() {
    return this->_ptr;
}

template <class T>
void SmartPtr<T>::_release() {
    if (this->_refCount && this->_refCount->Release() == 0) {
        delete this->_ptr;
        delete this->_refCount;
    }
}

template <class T>
void SmartPtr<T>::_copySmartPtr(const SmartPtr<T>& iSPtr) {
    this->_ptr = iSPtr._ptr;
    this->_refCount = iSPtr._refCount;
    this->_refCount->AddRef();
}


texts: Find pair in array with maximum sum using recursion

texts:
Not sure the best way to solve this using recursion. Below is what I have tried so far:
public static void findSum(int[] a, int sum, int i, int j) {

    if (i == a.length)
        return;
    if (j == a.length)
        return;

    sum = (a[i] + a[j] > sum) ? (a[i] + a[j]) : sum;
    System.out.println("Sum:" + sum + ", i:" + i + ",j:" + j);

    findSum(a, sum, i, j + 1);
    i++;
    j = i;
    findSum(a, sum, i, j + 1);

    return;
}

Given input : int[] a = {5, 4, 7, 3, 9, 2}
Expected output : 7+9 -> 16
Plus I am getting many number of iterations which must be reduced.


texts:
This is a question from programming contest. This contest is already over.

Now, all the prime numbers are arranged sequentially in ascending order. i.e:- 2, 3, 5,7...and so on. Now, your task is to calculate those prime numbers which are present at a prime position. For example, 2 is present at position 1 which is not a prime number while 3 is present at position 2 which is a prime number, hence 3 is the first prime positioned number. Now, these primed positioned prime numbers are numbered is ascending order such that:

first prime positioned number is 3. So, it is given number 1.

second prime positioned number is 5. So, it is given number 2.

and so on. Now, we are given 2 numbers n and m which denotes the nth and mth prime positioned numbers. Now, your task is to calculate the multiplication of prime positioned number present at nth and mth position. Since the answer may be large, output the answer modulo 109 + 7.

INPUT

First line contains an integer t denoting the number of test cases. The next t lines contains two integers n and m separated by space, denoting the prime positioned numbers which are given numbers n and m.

OUTPUT

A single integer (one per line) for each test t, that is the answer to the question.

CONSTRAINTS

1<= t <=106

1<= n,m <=10000

My approach:

For each test case read 'n' and 'm'. Then calculate nthPrime for 'n' and 'm'.Then again calculate nthPrime for result each result and finally multiply both the answers. This is working for small input but for large inputs it is taking more time.

import java.util.Scanner;

public class Sum {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int t=scanner.nextInt();

    while(t-- >0){
        int n=scanner.nextInt();
        int m=scanner.nextInt();
        int first=nthPrime(nthPrime(n));
        int second=nthPrime(nthPrime(m));

        System.out.println(first*second);
    }

}

private static int nthPrime(int n) {
    // TODO Auto-generated method stub
    int candidate,count;
    for(candidate=2,count=0;count<n;candidate++){
        if(isPrime(candidate)){
            count++;
        }
    }
    return candidate-1;
}

private static boolean isPrime(int n) {
    // TODO Auto-generated method stub
    int m=(int) (Math.sqrt(n)+1);
    for(int i=2;i<m;i++){
        if(n%i==0){
            return false;
        }
    }
    return true;
}

}

How to increase time and space efficiency of this program?

Time Limit: 1 sec(s) for each input file.

Memory Limit:   256 MB

Source Limit:   2 KB


texts:
I've a sample code to create a simple menubar here which works, but I'm not sure if that's the best way to code it. Can somebody please validate if there is a better way to do the same?

In short

I've create a sample page with a directive called <menu-bar>

<menu-bar></menu-bar>

The directive merely points to a template code and a controller

app.directive("menuBar", function () {
  return {
    restrict: 'E',
    templateUrl: 'main-nav.html',
    controller: 'navController',
    controllerAs: 'nc'
  }
});

The controller loads the menubar (which will eventually fetch the items from the DB

app.controller('navController', ['$scope', '$location', function ($scope, $location) {
  $scope.navigationTabs = [
    new NAV("file","/file","File","fa fa-file-o", "active"),
    new NAV("edit","/edit","Edit","fa fa-edit", "inactive"),
    new NAV("view","/view","View","fa fa-search", "inactive"),
    new NAV("hist","/history","History","fa fa-history", "inactive"),
    new NAV("bmark","/bookmarks","Bookmarks","fa fa-bookmark-o", "inactive"),
    new NAV("hlp","/help","Help","fa fa-life-buoy", "inactive")
  ];
  ...
}]);

The controller defines a 'selectTab()' method which changes the url of the application when the user selects a menu-item. It also clears the active class on all the other items and sets the 'active' class on the one selected

    ...
    $scope.selectTab = function (nav) {
    $scope.navigationTabs.forEach(function (nav) {
        nav.active="";
    });
    console.log("navigating to url: " + nav.key);
    $location.path(nav.key);
    nav.active = "active";
}

The NAV item is defined in the app.js as follows:

var NAV = function (id, key, value, icon, active) {
    this.id = id;
    this.key = key;
    this.value = value;
    this.icon = icon;
    this.active = active;
};


texts: Macro that does some kind of duplicate check

texts:
This macro pulls in two workbooks, one being a template with saved formulas already, and the other containing data with thousands of rows...I need to increase the speed because the process takes more than 15 minutes.

Sub WbtoWb4()

Dim Wb1 As Workbook
Dim Wb2 As Workbook

With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Wb1 = Workbooks.Open("")
Set Wb2 = Workbooks.Open("")

Wb1.Sheets("CDGL Data").Copy After:=Wb2.Sheets("STS")
Wb1.Close False

With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With

Sheets("CDGL Data").Select
Range("AQ:BB").EntireColumn.Delete

Range("A1").AutoFilter Field:=32, Criteria1:=Sheets("DataSources").Range("B4").Value
ActiveSheet.UsedRange.Offset(1, 0).SpecialCells _
(xlCellTypeVisible).Copy

Sheets("CDGL").Select
Range("B2").PasteSpecial Paste:=xlPasteValues

With Sheets("CDGL")
rows_c1 = .Cells(Rows.Count, "G").End(xlUp).Row
Sheets("Duplicate Check").Range("A1:C" & rows_c1).Value = Sheets("CDGL").Range("H2:J" & rows_c1).Value

rows_c2 = .Cells(Rows.Count, "K").End(xlUp).Row
Sheets("Duplicate Check").Range("D1:G" & rows_c2).Value = Sheets("CDGL").Range("L2:O" & rows_c2).Value

rows_c3 = .Cells(Rows.Count, "AI").End(xlUp).Row
Sheets("Duplicate Check").Range("H1:H" & rows_c3).Value = Sheets("CDGL").Range("AJ2:AJ" & rows_c3).Value
End With

Sheets("Duplicate Check").Select
Set rng = Range("A1", Range("H1").End(xlDown))
rng.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8), Header:=xlNo

With Sheets("CDGL")
Sheets("Rec").Range("B6").Resize(.Cells(.Rows.Count, "G").End(xlUp).Row - 1, 3).Value = Sheets("Duplicate Check").Range("A1:C" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
 Sheets("Rec").Range("E6").Resize(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4).Value = Sheets("Duplicate Check").Range("D1:G" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
 Sheets("Rec").Range("I6").Resize(.Cells(.Rows.Count, "H").End(xlUp).Row - 1, 1).Value = Sheets("Duplicate Check").Range("H1:H" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
End With

Application.DisplayAlerts = False
Sheets("Duplicate Check").Delete

ActiveWorkbook.SaveAs Filename:=""
ActiveWorkbook.Close
End Sub


texts: Using another function on modified dictionary

texts:
This is based upon an exercise in chapter 5 of Automate the Boring Stuff with Python.

This code contains functions addToInventory which modifies a given inventory of items to add new items as well as update  existing items and displayInventory which displays the items and their values. The main operation is adding the contents of a list dragonloot to inventory inv.

I have tried to do this in two ways, one by calling addToInventory and after that calling displayInventory. This method leads to errors. Another way I tried was by printing the new inventory values within addtoInventory. This works fine. Why doesn't the first method work? I have put both the methods as comments within my code, indicated by """ """.

I know C++ pretty well, but I'm new to Python. Expected result:
Inventory:
gold coin: 45 rope:1 dagger:1 ruby:1 Total number of items is 48

def addToInventory(inventory, addedItems):
    draft = {}
    for i in addedItems:
        if (i not in draft):
            draft[i]=1
        else:
            draft [i]= draft [i] + 1
    for i in draft:
        if i not in inventory:
            inventory[i]=draft[i]
        else:
            inventory[i] = inventory[i]+draft[i]
    """for i in inventory:
        print(str(inventory[i]) + " " + str(i))"""

def displayInventory(inventory):
    print ("Inventory: ")
    total=0
    for i in inventory.items():
        total+=1
        print (str(inventory[i])+" "+str(i))
    print("Total number of items is"+str(total))

    inv = {'gold coin': 42, 'rope': 1}
    dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
    inv = addToInventory(inv, dragonLoot)
    """displayInventory(inv) when I use this line in place of above comment I get errors"""


texts: Creating a 2-D array whose first elements come from a 1-D array

texts:
I am trying to full one dimensional array in two dimensional array in Java.I did it using this way, is there another way better than this? .

public double[][] getResult(double[] data, int rowSize) {
int columnSize = data.length;
double[][] result = new double[columnSize][rowSize];
for (int i = 0; i < columnSize; i++) {
    result[i][0] = data[i];
}
return result;
}


texts:
As you're probably aware, PHP doesn't support type hinting for scalar types.
I feel this might be good practice to build into my framework, although I'm aware some of you might disagree seeing as PHP is a loosely-typed language.

But I'd like some feedback on the implementation of this.
Do you think it's efficient, pointless? Or could it be achieved in a better way?

This works by causing an error.
By specifying a typehint (integer), PHP is expecting a class/object called "integer", so it's giving an error as we are passing a "real integer"/scalar value".

Giving this error,

  Argument 1 passed to test() must be an instance of integer, integer given.

So with a custom error handler function, I can use preg_match() to find the expected & given types, and just compare them via the name.

The code

<?php

ini_set('display_errors', 'on');
error_reporting(E_ALL);

function typehint($level, $message){

    if($level == E_RECOVERABLE_ERROR){

        if(preg_match('/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/', $message, $match)){
            if($match[4] == $match[5]){
                return true;
             }
        }
    }

    return false;
}

set_error_handler('typehint');

function test(integer $value){
    var_dump($value);
}

for($int = 0; $int < 1000; $int++){
    test(23);
}

?>

It seems to work ok, but I'm not sure if using preg_match() on every function argument is a good idea?

Here's the benchmarks, on 1000 function calls. (1 typeint per function)

Type-hinting        No Type-hinting
0.015               0.0017
0.0169              0.002
0.0172              0.002
0.0148              0.0019
0.0159              0.0029
0.0157              0.0019
0.0149              0.0018
0.0161              0.0029
0.0167              0.002
0.0173              0.0018
0.0149              0.0019
0.0156              0.0019
0.0153              0.0029
0.0182              0.0023
0.0151              0.0029
0.0163              0.0017
0.0179              0.0018
0.0159              0.0018
0.0154              0.0027
0.0149              0.0023

Average             Average
0.016               0.002155

So just after some thoughts on this really... good or bad?

EDIT:
Using strstr() seems to be a little quicker, although I have to specify what types to check for. Which is a small number anyway. Average time: 0.009595.

function typehint($level, $message){

    if($level == E_RECOVERABLE_ERROR){

        $integer = 'must be an instance of integer, integer given';
        $string = 'must be an instance of string, string given';

        if(strstr($message, $integer) !== false OR strstr($message, $string) !== false){
            return true;
        }
    }

    return false;
}


texts: Creating a pythonic snippet to read and clean .csv files

texts:
I am trying to import a .csv file, clean the contents, and make sure all the errors are eliminated.

IO error
file format error
data error

I am using the snippet below.  Could someone help me clean it and make it more pythonic?

try:
    fl = request.FILES['csv']
except:
    return HttpResponse("Some IO Error")
try:
    reader = csv.reader(fl)
except:
    return HttpResponse("File Not Supported")
reader.next() # this makes sure the heading is
cleaned_csv_content = list()
for row in reader:
    err = 0
    fname, lname, e_mail  = row
    try:
        validate_email(email)
    except:
        pass
        err = 1
    if not err:
        cleaned_csv_content.append(fname, lname, e_mail)


texts: Best way to check for one of two values in an array in PHP

texts:
I want to see if one of two values (a, b) are in an array.  Here's my current thought:

$match_array = array('a','b');
$array_under_test = array('b', 'd', 'f');

if (array_intersect($match_array, $array_under_test)) {
  // Success!
}

Any better implementations?


texts:
I need to write a program to print the line numbers, in ascending order, of a particular word in a file. Example output of the program would be:

 Hello 1, 3, 5-6, 8, 10-15.
// 5-6 represents 5, 6 (consecutive numbers)

The line numbers are stored in a sorted vector<int> with no duplicates. I have created a solution, but my instincts tell me I can do better. I would appreciate some feedback. Further, the following code only processes the line numbers; the word is found in another method. I will remark that intToString() is a custom method that does as the name implies. It returns a static string.

void IndexPager::createLines(vector<int>& vec, string& line)
{
  int start = *vec.begin(), end = -1, offset = 0; // initial offset to start

  for (vector<int>::const_iterator itr = vec.begin();
       itr != vec.end() + 1; itr++)
  {
    if (*itr == start + offset && itr != vec.end())
    {
      end = *itr;
      ++offset;
    } // check if line numbers are consecutive and not reading at end of vector
    else // not consecutive
    {
      if ((end != -1) && (end != start))
      {
        line.append(intToString(start) + "-");
        line.append(intToString(end));
      } // if there existed consecutive numbers, display with dash
        // must be difference of at least 1
      else // else, there were no consecutive numbers
        line.append(intToString(start));

      if (itr != vec.end()) // check if not at end of vector
        line.append(", ");
      else // reached end of vector
        line.append(".");

      start = *itr; // set start to next line number. Soft reset.
      offset = 1; // change default offset to 1. 0 for first case.
      end = -1;
    } // not consecutive
  } // Get all line numbers and format for proper output
} // createLines()


texts: Calculate different speeds between min and max speed with a stepsize

texts:
public static void main(String[] args) {
    int minKmh = 10;
    int maxKmh = 20;
    int step = 5;

    String allSpeeds = "";
    while (minKmh <= maxKmh) {
        allSpeeds += minKmh + ",";
        minKmh += step;
    }
    String[] allSpeedsAsArray = removeLastChar(allSpeeds).split(","); // result: 10,15,20

}

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

I have a minimum car speed and a maximum car speed. In this case 10 and 20. And I want every speed which is between minimum and maximum where the speed gets incremented by a step speed.

I don't like my current version because it is large in my opinion. Is it possible to shorten the code to 1-2 liner?


texts: Decimal to Roman numeral conversion algorithm

texts:
I have written a program to convert a decimal to a Roman numeral. I am wondering if my algorithm is okay or not. If it's not okay, I want suggestions on improving my code. This code only works for inputs up to 5000. I found this question in a code cracker competition at my college.

#include <iostream>
using namespace std;
int main()
{
    int num=0;
    int user;
    int temp=0;
    string ans[4];
    int mod=10;
    int n[5];
    string r1[]={"0","I","II","III","VI","V","VI","VII","VIII","IX" };
    string r2[]={"x","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
    string r3[]={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
    string r4[]={"M","MM","MMM","MMMM"};

    cout<<"Enter Number"<<endl;
    cin>>user;

    for(int i=0;i<4;i++)
{
    num=user%mod;
    user=user-num;
    n[3-i]=num;
    mod=mod*10;
}

for(int i=0;i<4;i++)
{
    if(n[i]>999)
    {
        temp=n[i]/1000;
        ans[i]=r4[temp-1];
    }
    if(n[i]>99 && n[i]<1000)
    {
        temp=n[i]/100;
    ans[i]=r3[temp-1];
    }
    if(n[i]>9&& n[i]<100)
    {
    temp=n[i]/10;
    ans[i]=r2[temp-1];
    }
        if(n[i]>0 && n[i]<10)
    {
    temp=n[i];
    ans[i]=r1[temp];
    }
    }
    for(int i=0;i<4;i++)
    {
    cout<<ans[i];
    }
    return 0;
    }


texts:
I'm running the following code on quite large data frames. I've rewritten it for the iris dataset to make it reproducable.
I'm quite unexperienced with the apply functions and I find them a pain in the bum to apply them.

Is there any ways to drastically improve the performance of this process?

lmfit <- lm(iris$Petal.Width ~ iris$Sepal.Length + iris$Sepal.Width)
out_index <- 1
TableWithResiduals <- data.frame(matrix(ncol = ncol(iris) +1, nrow = nrow(iris)))
for (row in 1:length(resid(lmfit))){
  TableWithResiduals[out_index,] <- cbind(iris[row,],resid(lmfit)[row])
  out_index <- out_index +1
}
colnames(TableWithResiduals) <- colnames(iris)
colnames(TableWithResiduals)[length(TableWithResiduals)] <- "Residual_value"


texts: JavaScript to fire event every second until 10s then gradually increase

texts:
I have a piece of JavaScript that's going to fire event every second after 10s, it's going to gradually increase the interval time. I'm new to JavaScript so it would be nice to have a codereview.

var _lastHeartbeat = window.performance.now();
var _config = {
  heartbeat: {
    start: 1000,
    max: 10000000,
    cap: 10000,
    degrade: function(interval) {
      var int = Math.pow(interval, 1.15);
      return Math.round(int / 10000) * 10000;
    }
  }
}

var heartbeat = function() {
  var end = window.performance.now();
  var timespent = Math.round((end - _lastHeartbeat) / 1000) * 1000
  console.log('test: ' + timespent); // fire event
}

var _startHeartbeat = function() {
  var beat = function(interval) {
    setTimeout(function() {
      heartbeat();
      var end = window.performance.now();
      var timespent = Math.round((end - _lastHeartbeat) / 1000) * 1000
      if (timespent < _config.heartbeat.cap) {
        beat(interval);
      } else if (interval < _config.heartbeat.max) {
        beat(_config.heartbeat.degrade(timespent));
      }
    }, interval);
  };

  beat(_config.heartbeat.start);
}

_startHeartbeat();

Here's JsFiddle. https://jsfiddle.net/noppanit/5cpbyyrg/1/


texts:
I have implemented customized encoding mechanism for javaUTF16. Does this implementation support all the characters?

public class Encoding {
    public static void main(String[] args) {

        byte [] arr = new byte[1000];

        String str = "abcde" ; //even this encoding works supplementary characters
        Encode(arr,0,str);
        System.out.println(Decode(arr,str.length()));
    }

public static byte[] Encode(byte[] ByteArray , int offset ,String str) {

        char[] ch = str.toCharArray();
        for(char c : ch) {
        ByteArray[offset++] = (byte) (c >>> 8);
        ByteArray[offset++] = (byte) (c & 0xff);
        }
        return ByteArray;
    }

    public static String Decode(byte[] ByteArray ,int len) {

        char [] res = new char[len*2];
        int i = 0;
        int offset = 0;
        while(i < len) {
    res[i] = (char) ((ByteArray[offset++] << 8) | (ByteArray[offset++] & 0xff));
            i++;
        }

        return new String(res);
    }
}


texts:
This code is very, very simple, but I was wondering how it could be improved:

#include <iostream>

int main() {
    std::string input;
    std::getline(std::cin, input);

    for(int i = 1; i <= input.length(); i++){
        std::cout << input[input.length() - i];
    }

    std::cout << '\n';
    return 0;
}

This code takes a string input, and prints it backwards. For example:

This will be printed backwards.

Becomes:

.sdrawkcab detnirp eb lliw sihT

Given the simplicity of this code, is there a way to optimize it? I understand that since it is very short, it will run fast no matter what. However, I hate inefficiencies in code, and I want to help improve the way that I write code.

This is related to, but not copied directly from, this SO answer. (I only found this SO answer after writing the code)


texts: Handling Null values (and equivalents) routinely in Python

texts:
I've found the following code invaluable in helping me 'handle' None values including "whitespace" characters that should be treated as None based on the situation.   I have been using this code for quite some time now:

class _MyUtils:

    def __init__(self):
        pass

    def _mynull(self, myval, myalt, mystrip=True, mynullstrings=["", "None"], mynuminstances=(int, float)):
        # if the value is None, return the alternative immediately.

        if myval is None:
            return myalt

        # if the value is a number, it is not None - so return the original
        elif isinstance(myval, mynuminstances):
            return myval

        # if the mystrip parameter is true, strip the original and test that
        else:
            if mystrip:
                testval = myval.strip()
            else:
                testval = myval

            # if mynullstrings are populated, check if the upper case of the
            # original value matches the upper case of any item in the list.
            # return the alternative if so.
            if len(mynullstrings) > 0:
                i = 0
                for ns in mynullstrings:
                    if ns.upper() == testval.upper():
                        i = i + 1
                        break
                if i > 0:
                    return myalt
                else:
                    return myval
            else:
                return myval

def main():
    x = _MyUtils()
    print(x._mynull(None, "alternative_value", True, [""]))

if __name__ == '__main__':
    main()

The code requires an input, an alternative to provide if input is found to be Null, whether to 'strip' the input during testing (if not a number), values to treat as 'equivalent' to None and types of number instances to determine if the input is numeric (and hence not none).

Essentially, too many processes that we run depend upon not having None values in the data being processed—whether that be lambda functions, custom table toolsets, etc.  This code gives me the ability to handle None values predictably, but I am sure there is a better approach here. Is there a more Pythonic way of doing this? How can this code be improved? How would others approach this problem?