texts: Equivalent of C-style "Static Local Variable" in Swift

texts:
I'm porting some Obj-C code to Swift, and I've written the following code to allow me to deal with "static local variables" which do not exist in Swift.

A static local variable has these requirements:

it is shared between all instances that access it
it has one assignment method which only sets the value when it is first declared.
has another assignment method which sets its value normally (i.e. any time it is used)

There has to be a better way then what I have coded. For starters, I know that using  UnsafeBitcast is not good practice.

class Container<T:Any>{

    var _memory:Any
    var memory:T {
        get {

            if let typed_value = self._memory as? T {
                // for value types, such as "String"
                return typed_value
            } else {
                // for types conforming to "AnyObject", such as "NSString"
                return unsafeBitCast( self._memory, T.self )
            }

        }
        set {
            self._memory = newValue
        }
    }

    init( memory:Any ){
        self._memory = memory
    }

}

var Static_Containers = [String:AnyObject]()

func static_var <T:Any>(
    value:T,
    file: StaticString = __FILE__,
    line: UWord = __LINE__,
    col: UWord = __COLUMN__,
    fun: StaticString = __FUNCTION__
) -> Container<T> {

        let unique_key = "FUNC_\(fun)__LINE\(line)_COL\(col)__FILE_\(file)"

        let needs_init = !contains( Static_Containers.keys, unique_key )

        if needs_init {
            Static_Containers[unique_key] = Container<T>( memory:value )
        }

        return Static_Containers[unique_key]! as! Container<T>

}

Here's a couple tests:

func test_with_nsstring( str:NSString, init_only:Bool ) -> NSString {
    var stat_str = static_var( str )
    if !init_only {
        stat_str.memory = str
    }
    return stat_str.memory
}
test_with_nsstring( "this should get set", true )
test_with_nsstring( "this should be ignored", true ) // only repeated declaration
test_with_nsstring( "this should change the value", false )
test_with_nsstring( "as should this", false )

func test_with_int( i:Int, init_only:Bool ) -> Int {
    var stat_int = static_var( i )
    if !init_only {
        stat_int.memory = i
    }
    return stat_int.memory
}
test_with_int( 0, true )
test_with_int( 1, true ) // only repeated declaration
test_with_int( 2, false )
test_with_int( 3, false )

func test_with_optstr( optstr:String?, init_only:Bool ) -> String? {
    var stat_optstr = static_var( optstr )
    if !init_only {
        stat_optstr.memory = optstr
    }
    return stat_optstr.memory
}
test_with_optstr( nil, true )
test_with_optstr( "this should be ignored", true ) // only repeated declaration
test_with_optstr( "this should change the value", false )
test_with_optstr( "as should this", false )

When I test this code in a Playground, it seems to behave correctly. I'd just like a less nutty, and less brittle, way to accomplish this.


texts:
I'm learning Swift and would appreciate any code review suggestions (the more nit-picky, the better).  In particular, I'm wondering if there's a more efficient way to format the time in the timeToString function I wrote, since I'm repeating myself three times.

import UIKit
import Foundation

class ViewController: UIViewController {

    @IBOutlet var timerLabel: UILabel!

    var timer = NSTimer()
    var count = 0

    @IBAction func start(sender: AnyObject) {
      timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
    }

    @IBAction func stop(sender: AnyObject) {
      timer.invalidate()
    }

    @IBAction func reset(sender: AnyObject) {
      timer.invalidate()
      count = 0
      let (h, m, s) = convertSeconds(count)

      timerLabel.text = timeToString(h, m: m, s: s)
    }

    func result(){
      count++
      let (h, m, s) = convertSeconds(count)

      timerLabel.text = timeToString(h, m: m, s: s)
    }

    func convertSeconds(totalSeconds: Int) -> (h:Int, m:Int, s:Int){
      var seconds = totalSeconds % 60
      var minutes = (totalSeconds / 60) % 60
      var hours = totalSeconds / 3600
      return (hours, minutes, seconds)
    }

    func timeToString(h:Int, m:Int, s:Int) -> String {

      var h = String(format: "%02d", h)
      var m = String(format: "%02d", m)
      var s = String(format: "%02d", s)
      return "\(h)h \(m)m \(s)s"
    }

    override func viewDidLoad() {
      super.viewDidLoad()
      let (h, m, s) = convertSeconds(count)

      timerLabel.text = timeToString(h, m: m, s: s)
    }

    override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
    }

}


texts: Calculating the number of zeroes at the end of a factorial

texts:
The code seems to work, but, I always get the "Time Limit Exceeded" error (the time limit defined is 6 seconds). I even tried reducing the number of iterations but am still running short on time. I am basically trying to find the number of 5's and 2's, to obtain 10.

#include <iostream>

int number_counter(long int x, int base)
{
long int val = x;
unsigned int counter = 0;
for(long int i = x; i >= 1;(!(i%base)?(i=i-base):i--))
{
    val =i;
    while((val % base) == 0)
    {
        counter++;
        val = val/base;
    }
}
return counter;

}

int Zfact(long int num)
{
    unsigned int fives, twos;
    fives = number_counter(num, 5);
    twos = number_counter(num, 2);
    return (fives>twos) ? twos : fives;
}
int main() {
    int T;                                  //T = Number of test cases.
    cin>>T;
    unsigned long int n;
    for(int i=0;i < T;i++)
    {
        cin>>n;
        int zeroes = Zfact(n);
        cout<<zeroes<<endl;
    }

    return 0;
    }


texts:
I tried to make an is_Prime() function in PHP. What do you think about this code?

<?php
function is_Prime($x)
{
  if($x <= 1)
  {
    echo $x. " is not a prime number.
";
    return false;
  }
  $data = array();
  for ($i=1;$i<=$x;$i++)
  {
    if(is_integer($x/$i))
    {
        array_push($data, ($x/$i));
    }
  }
  if(count($data)>2)
  {
    echo $x." is not a prime number
";
  }
  else
  {
    echo $x. " is a prime number
";
  }
}
?>

How to use?

for($i=0;$i<=100;$i++)
{
  is_Prime($i);
}


texts: Compare two lists to see if one is a rotation of the other

texts:
Going through a list of common interview question, this was the next one. Any suggestions on performance and improvement? What would be a better implementation of this? Also correct me if I'm wrong, this would be \$O(n)\$ complexity?

'''
Problem statement: Given 2 integer arrays, determine if the 2nd array is a     rotated version of the 1st array.
Ex. Original Array A={1,2,3,5,6,7,8} Rotated Array B={5,6,7,8,1,2,3}

@author: Anonymous3.1415
'''

#@cmp_arr, is the array being compared to see if it is a rotation
def is_rotated(int_arr, cmp_arr):

    #lengths of arrays are the same and not equal to zero?
    if len(int_arr) != len(cmp_arr) or len(int_arr) == 0:
        return False

    #does array contain same numbers?
    if not set(int_arr) <= set(cmp_arr) and not set(int_arr) >= set(cmp_arr):
        return False

    #Find start of first list in the second
    index = 0
    while int_arr[0] != cmp_arr[index]:
        index += 1

    #split list at index point, compare the lists
    cmp_arr = cmp_arr[index:] + cmp_arr[:index]
    index = 0
    for x in int_arr:
        if x != cmp_arr[index]:
            return False
        index += 1

    return True

int_arr = [1,2,3,4,6,4,7]
cmp_arr = [6,4,7,1,2,3,4]
print(is_rotated(int_arr, cmp_arr))


texts:
The following class BackgroundExecutable is to be used to take a function f and return a function f' where f' asks iOS for background execution. f takes a completion closure which it uses to end the background execution.

class BackgroundExecutable {
  var identifier: UIBackgroundTaskIdentifier
  let f: (() -> Void) -> Void

  init(f: (completion: () -> Void) -> Void) {
    self.f = f
    self.identifier = UIBackgroundTaskInvalid
  }

  func execute() {
    let application = UIApplication.sharedApplication()
    identifier = application.beginBackgroundTaskWithExpirationHandler {
      application.endBackgroundTask(self.identifier)
    }
    f(endBackgroundTask)
  }

  func endBackgroundTask() {
    UIApplication.sharedApplication().endBackgroundTask(identifier)
  }
}

func backgroundExecutable(f: (() -> Void) -> Void) -> (() -> Void) {
  let b = BackgroundExecutable(f: f)
  return b.execute
}

Usage:

func F(completion: () -> Void) {
  println("F Called")
  completion()
}

let newF = backgroundExecutable(F)


texts: Change Task Edit form of workflow in SharePoint 2010

texts:
I want to change the task edit form of the workflow when an approver wants to approve/reject a task. Please review and suggest improvements or any other possible solution with an explanation.

 public void createTask1_MethodInvoking(object sender, EventArgs e)
        {
            createTask1_TaskId1 = Guid.NewGuid();
            createTask1_TaskProperties1.Title = "Test Title";
            createTask1_TaskProperties1.AssignedTo = "i:0#.w|directory\approver";
            var taskList = workflowProperties.TaskList;
            var wfContentType = taskList.ContentTypes["Workflow Task"];
            TaskTitle = workflowProperties.Item["Title"].ToString();
            wfContentType.DisplayFormUrl = "_Layouts/SharePointProject4/ApplicationPage1.aspx";
            wfContentType.EditFormUrl = wfContentType.DisplayFormUrl;
            wfContentType.Update();
            taskList.NavigateForFormsPages = false;
            taskList.Update();
        }


texts: Decomposing a number as a sum of two products using tree recursion

texts:
Below is the problem taken from page6 here.

  The TAs want to print handouts for their students. However, for some unfathomable reason, both the printers are broken; the first printer only prints multiples of n1, and the second printer only prints multiples of n2. Help the TAs figure out whether or not it is possible to print an exact number of handouts! First try to solve without a helper function. Also try to solve using a helper function and adding up to the sum.

def has_sum(sum, n1, n2):
"""
>>> has_sum(1, 3, 5)
False
>>> has_sum(5, 3, 5) # 1(5) + 0(3) = 5
True
>>> has_sum(11, 3, 5) # 2(3) + 1(5) = 11
True
"""

Solution

I think there is no mathematical solution except bruteforce recursion.

def f(sum, n1, n2):
    """
    >>> f(1, 3, 5)
    False
    >>> f(5, 3, 5) # 1(5) + 0(3) = 5
    True
    >>> f(11, 3, 5) # 2(3) + 1(5) = 11
    True
    >>> f(189, 4, 9)
    True
    """
    memoiz = []
    value = []
    def has_sum(sum, n1, n2, x=0, y=0):
        if x == 0 and y == 0:
            value.append(n1)
            value.append(n2)   #execute once to reuse tup
        if (n1 + n2)  == sum:
            return True
        if (memoiz) and ((n1 + n2)  > sum): # inefficient base case, need to improve using math
            return False
        result1 = False
        result2 = False
        if (x+1, y) not in memoiz:
            memoiz.append((x+1, y)) #memoiz
            result1 = has_sum(sum, (x+1)*value[0], y*value[1], x+1, y)
        if (x, y+1) not in memoiz:
            memoiz.append((x, y+1)) #memoiz
            result2 = has_sum(sum, x*value[0], (y+1)*value[1], x, y+1)
        return result1 or result2
    return has_sum(sum, n1, n2)

Can we improve the base case that returns False?


texts: Print the sum of corresponding elements in two arrays

texts:
In this exercise, I'm supposed to sum up elements from 2 arrays, then display the answer on one line with spaces in between. I did it and my answer got accepted as correct, but I'm wondering if there is a better way to do this since I feel my way was more complicated than it needed to be.

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {
    int n = 11;

    int[] firstArray = {811594, 993574, 299729,559604,161945,969851,588210,
            692459, 28350,43017,797855};
    int[] secondArray = {725888, 233750,191700,944750,380402,319860,766872,764921,
            330218,906679, 65309};

    List<Object> total = new ArrayList<>();

    for(int i = 0; i < n; i++){
        int sum = firstArray[i] + secondArray[i];
        total.add(sum);
    }

    Integer[] sumArray = total.toArray(new Integer[total.size()]);
    for(int i = 0; i < n; i++) {
        System.out.print(sumArray[i] + " ");
    }

}
}


texts: Format string processing similar to date or printf()

texts:
I wrote a function that is supposed to take a format string similar to what date accepts and replace all format specifiers with strings provided by a callback function.

Format specifiers are sequences of a % plus another character; %% for a literal %
Replace the format specifier with the string provided by the callback function
If the callback function returns NULL, no replacement should take place (leave the specifier in)
The callback function receives the character following % as argument
An optional pointer can be passed through to the callback function
If the last character of the format string is %, it should be left as-is
The result of the processing is to be placed in the provided buffer
If the provided buffer isn't big enough, simply stop processing
Always null-terminate the provided buffer, even if it isn't big enough

The function works fine as far as I can tell. I'm looking for any feedback I can get.
char*
format(const char* format, char *buf, size_t len, char* (*cb)(char c, void* ctx), void *ctx)
{
    const char *curr;  // current char from format
    const char *next;  // next char from format

    size_t i = 0;      // index into buf
    char *ins = NULL;  // string to insert

    // iterate `format`, abort once we exhaust the output buffer
    for (; *format && i < (len-1); ++format)
    {
        curr = format;
        next = format+1;

        if (*curr == '%' && *next)
        {
            if (*next == '%') // escaped %, copy it over and skip
            {
                buf[i++] = *format++;
                continue;
            }
            if ((ins = cb(*next, ctx))) // get string to insert
            {
                // copy string, again aborting once buffer full
                while (*ins && i < (len-1))
                {
                    buf[i++] = *ins++;
                }
                ++format;
                continue;
            }
        }

        // any other character, just copy over
        buf[i++] = *curr;
    }

    // null terminate
    buf[i] = '\0';
    return buf;
}

Examples for (tested) input and output, assuming the callback function always returns FOO:

(empty string): (empty string)
%: %
%%: %
%f: FOO
%%f: %f
%%%f: %FOO
%%%%f: %%f

If so requested, I can provide a link to the context/project where this is used.


texts: Handling slow processing the Spring batch way

texts:
We are using spring-batch to extract data from a SAP system, during processing we pass the extracted full texts to a tagging service, in the end the enriched documents are stored in Solr to be served to the user.

The problem during this ETL chain is that the tagging service is slow. Unfortunately we cannot improve its performance problems as it is a bought vendor solution. The problem of this service is that it has a ramp-up time of 6 seconds for each request. It does offer a bulk interface to tackle this. So we can send 1 item for tagging or 5.000 items. Each request will take 6 seconds. Hence we would like to send the texts as bulk during processing.

This is where our review request comes into play.

As far as we understood spring-batch processors perform their operation on single records, not batches. Hence we have a problem, as we need to process 8 Million records.

I have setup a project on github to illustrate the problem and our approach so far. To start the batch processing use the SlowProcessorApplicationTests.

The reader is a FlatFileItemReader as the sample data is included as CSV within the project

@Bean
public FlatFileItemReader<InputItem> inputItemReader() {
  return new FlatFileItemReaderBuilder<InputItem>()
      .name("inputItemReader")
      .resource(new ClassPathResource("input.csv"))
      .linesToSkip(1)
      .delimited()
      .delimiter(";")
      .names(new String[]{
          "id",
          "title",
          "text"})
      .fieldSetMapper(new BeanWrapperFieldSetMapper<InputItem>() {{
        setTargetType(InputItem.class);
      }})
      .build();
}

The ItemProcessor is straight forward, but here is where the problem is. The call to taggingService.analyze(...) takes 6 seconds, each time.

@Slf4j
@Component
public class CSVItemProcessor implements ItemProcessor<InputItem, OutputItem> {

  @Autowired
  private TaggingService taggingService;

  @Override
  public OutputItem process(InputItem inItem) throws InterruptedException {
    log.trace("process {}", inItem);
    OutputItem outItem = new OutputItem();
    outItem.setId(inItem.getId());
    outItem.setTitle(inItem.getTitle());

    List<TaggingResponse> responses = taggingService.analyze(inItem.getText());
    TaggingResponse response = responses.get(0);
    outItem.setTags(response.getTags());
    outItem.setWords(response.getWords());
    return outItem;
  }
}

The Job and its only Step are also quite simple:

@Bean
public Job loadCSV(Step handleCSV) {

  return jobBuilder.get("loadCSV")
      .incrementer(new RunIdIncrementer())
      .start(handleCSV)
      .build();
}

@Bean
public Step handleCSV(
    FlatFileItemReader<InputItem> inputItemReader,
    CSVItemProcessor itemProcessor) {

  return stepFactory.get("handleCSV")
    .<InputItem, OutputItem>chunk(2)
    .reader(inputItemReader)
    .processor(itemProcessor)
    .writer((ItemWriter<Object>) items -> log.debug("writing {} items", items.size()))
    .build();
}


texts: Pascal triangle algorithm is good but fails

texts:
I have created a function which returns the number that corresponds to the given row and column from the pascal triangle. I have used the formula for this:

  n! / r! * (r-n)!

The code:

def pascal(c: Int, r: Int): Int = {

    def factorial(number: Int): Int = {

      def loop(adder: Int, num: Int): Int = {
        if( num == 0) adder
        else loop(adder * num, num - 1)

      }

      loop(1,number)
    }

    factorial(r) / (factorial(c) * factorial(r-c));
}

I received 180 points out of 190 for this function because it returns an arithmetic exception for a given case (they don't give me the case). How could I improve this code and how can I make it better?  Most importantly, how can I spot the bug?


texts: Search for solutions to quartic diophantine equation

texts:
I wrote this code to find the variables that will satisfy the diophantine equation (i.e. a^4 + b^4 + c^4 = d^4), for all variables belong to: (0 , 430000), and it takes forever to find the answer (I left the code running for two hours and got nothing). I know that this is caused by the algorithm or the approach I took, but I really couldn't think of any better solution...

here's the code:

#include <iostream>
using namespace std;
void main()
{
    //Here I use double because max value for int variables is too small for what I need.
    double n = 0, LHS, RHS, valA, valB, valC, valD;
    double *arrA, *arrB, *arrC, *arrD;
    arrA = new double[430000]; //array to store all the powers of 4 for var A
    arrB = new double[430000]; //array to store all the powers of 4 for var B
    arrC = new double[430000]; //array to store all the powers of 4 for var C
    arrD = new double[430000]; //array to store all the powers of 4 for var D
    for (int count = 0; count < 430000; count++)
    {
        arrA[count] = n*n*n*n;
        arrB[count] = n*n*n*n;
        arrC[count] = n*n*n*n;
        arrD[count] = n*n*n*n;
        n++;
    }
    //this loop is a counter, it increments "b" by 1 when "a" reaches max value, and so on for each variable...
    /*
    N.B:
    The variables that satisfy the equation should be the following:
    a = 95800
    b = 217519
    c = 414560
    d = 422481
    Plug it in as initializers for the variables to check that the program is working fine.
    */
    int a = 0, b = 0, c = 0, d = 0;
    while (d < 430000)
    {
        if (a == 430000)
        {
            a = 0;
            b++;
        }
        if (b == 430000)
        {
            a = 0;
            b = 0;
            c++;
        }
        if (c == 430000)
        {
            a = 0;
            b = 0;
            c = 0;
            d++;
        }
        if (d == 430000)
        {
            break;
        }
        LHS = arrA[a] + arrB[b] + arrC[c];
        RHS = arrD[d];
        if (LHS == RHS && (arrA[a] != arrB[b] != arrC[c] != arrD[d]))
        {
            valA = a; valB = b; valC = c; valD = d;
            break;
        }
        a++;
    }

    if (d == 430000){
        cout << "Couldn't find an answer! \n" }
    else
    {
        cout << "value of A is:  " << valA << endl;
        cout << "value of B is:  " << valB << endl;
        cout << "value of C is:  " << valC << endl;
        cout << "value of D is:  " << valD << endl;
    }
}

If anyone could tell me how to speed up the code or could think of a better algorithm. There's nothing wrong (IMO) in the code's syntax or logic, but it is very very slow...

N.B: here's a link to an article regarding the equation for further reading:
https://www.jstor.org/stable/2008781?seq=1#page_scan_tab_contents

I'm using a 2013 macbook pro "running windows 10", (intel i5 2.4GHz, 8GB RAM), MS Visual Studio 2017...


texts: Finding the Pythagorean triplet that sums to 1000

texts:
Project Euler problem 9 says:

  A Pythagorean triplet is a set of three natural numbers, a < b < c,
  for which,

  a2 + b2 = c2

  For example, 32 + 42 = 9 + 16 = 25 = 52.

  There exists exactly one Pythagorean triplet for which a + b + c =
  1000. Find the product abc.

I am a beginner in programming, especially Python. I got the answer for the problem, but how can I optimize it?

a=0
b=a+1
exit=False

#a loop
for x in xrange(1000):
    a+=1
    b=a+1
    c=b+1
    #b loop
    for y in xrange(1000):
        b+=1
        if(1000-b-a < 0):
            break
        c = 1000-a-b
        if(a**2 + b**2 == c**2):
                print "The number is ", a*b*c
                x=1000
                exit = True
        else:
                print "A is ", a ,".\n B is ", b, ".\n  C is ",c,"."
        if exit:
                break
    if exit:
            break


texts: Graph degree as solution for undirected graph paint

texts:
The problem is:

  Given an undirected graph represented as an adjacency matrix and an
  integer k, write a function to determine whether each vertex in the
  graph can be coloured such that no two adjacent vertices share the same
  colour using at most k colours.
  Source: https://www.dailycodingproblem.com/

The proposed solution uses a backtracking algorithm (https://www.dailycodingproblem.com/blog/graph-coloring), but  I would like to know if just evaluating the vertice degree is enough (source: https://youtu.be/LUDNz2bIjWI?t=169).

    boolean canBeColored(int[][] adjacencyMatrix, int colors) {

    for (int row = 0; row < adjacencyMatrix.length; row++) {
        int degree = 0;
        for (int column = 0; column < adjacencyMatrix[row].length; column++) {
            if (adjacencyMatrix[row][column] == 1) {
                degree++;
            }
        }

        if (degree > colors) {
            return false;
        }
    }

    return true;
}


texts: Allowing users to view and manage articles

texts:
This is a controller from an Express app that lets users view and manage articles. There are at least a couple of issues I'd like to address...

The program displays a list of articles in a sidebar that appears on each page. Right now, the app queries the database for article names, caches them, and includes them in the payload. It does this for each route that loads a view.

Is there a more efficient way to do this?

A good bit of code is repeated in the first two methods (retrieve and settings). Both methods get a list of articles for the sidebar and show an article or the settings for an article.

Is there a way to DRY up this code?

const { Article } = require('../models');
import CacheService from '../services/cache';

const ttl = 60 * 60 * 1;
const cache = new CacheService(ttl);

module.exports = {
  // display one article
  retrieve (req, res, next) {
    // list of articles displayed in the sidebar
    const allArticles = module.exports.getUserArticles(req.user.id);

    // the article to display
    const thisArticle = module.exports.getArticleById(req.params.publicId);

    Promise
      .all([allArticles, thisArticle])
      .then((result) => {
        const articles = result[0];
        const article = result[1];

        if (!article) {
          const error = new Error('Article not found');
          error.status = 404;
          return next(error);
        }

        return res.render('article', { articles, article, title: article.name });
      })
      .catch(next);
  },
  // show settings page for an article
  settings (req, res, next) {
    // list of articles displayed in the sidebar
    const allArticles = module.exports.getUserArticles(req.user.id);

    // the article to display
    const thisArticle = module.exports.getArticleById(req.params.publicId);

    Promise
      .all([allArticles, thisArticle])
      .then((result) => {
        const articles = result[0];
        const article = result[1];

        if (!article) {
          const error = new Error('Article not found');
          error.status = 404;
          return next(error);
        }

        const { page } = req.params;
        const pageTitle = module.exports.getSettingsPageTitle(page);
        const pageTemplate = `settings-${page}`;

        return res.render(pageTemplate, { articles, article, title: `${article.name}: ${pageTitle}` });
      })
      .catch(next);
  },
  getUserArticles (userId) {
    return cache.get(`getUserArticles_${userId}`, () => Article.findAll({ where: { userId }, order: [['name']] }));
  },
  getArticleById (publicId) {
    return cache.get(`getArticleById_${publicId}`, () => Article.findOne({ where: { publicId } }));
  },
  getSettingsPageTitle (page) {
    return {
      edit: 'Edit name, URL',
      response: 'Edit email response',
      notifications: 'Configure notifications'
    }[page];
  }
};


texts: What is the most pythonic way to solve a differential equation using the Euler method?

texts:
For example, with this differential equation, how can I do it in a pythonic way?

dx/dt=f(x,t)

I have a way to do it, but I think this is not the most pythonic way:

import numpy as np
dt=0.01
N_iter=10./dt
def f(x,t):
    return x**2*t#insert your favorite function here
x=np.zeros(N_iter)
for i in range(N_iter-1):
    x[i+1]=x[i]+dt*f(x[i],i*dt)


texts:
What are your thoughts on using an IDisposable to stripe an HTML table like so? It's a blatant abuse of IDisposable but this allows you to use the counter in a using(){} block which gives you a clear block in the markup.

public class StripeCounter : IDisposable
{
    private string cssClass = "stripe";

    private int counter = 0;

    public StripeCounter(){}

    public StripeCounter(string cssClass)
    {
        this.cssClass = cssClass;
    }

    public MvcHtmlString Stripe()
    {
        return MvcHtmlString.Create(counter++ % 2 == 1 ? cssClass : string.Empty);
    }

    public void Dispose() { }
}

And then the markup

@using (var counter = new StripeCounter())
{
    foreach (var item in Model)
    {

            ...

       ...

    }
}

Regarding comments on using JavaScript to stripe the table:

JavaScript is for behaviour and the striped rows of a table aren't behaviour; they are style, so while it is possible to do so on the client, it seem to me to be something that should be done on the server. For example, if someone has scripts disabled, they would still see the CSS striping, but not JavaScript striping.


texts: Basic network layer for a JSON API client

texts:
Just looking for some feedback/ways to improve this basic networking layer written in Swift. I'm still learning, please elaborate with as much detail as possible.

enum HTTPMethod: String {
    case get = "GET"
}

 class HTTPLayer {

     let baseURL = URL(string: "https://example.com")!

     func request(at endpoint: Endpoint, completion: @escaping (Data?, Error?) -> Void) {
        let url = baseURL.appendingPathComponent(endpoint.path)
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            completion(data, error)
        }
        task.resume()
    }

 }

 enum Endpoint {

     case listTransactions
    case transactionDetails(String)

     var method: HTTPMethod {
        return .get
    }

     var path: String {
        switch self {
        case .listTransactions:
            return "/api/transactions/"
        case .transactionDetails(let id):
            return "/api/transactions/id"
        }
    }

 }

 struct Transaction: Decodable {
    let id: String
    let amount: Double
}

 struct TransactionDetails: Decodable {
    let payload: [String: String]
}

 enum Result<T> {
    case success(T)
    case failure(NSError)
}

 class APIClient {

     let httpLayer: HTTPLayer
    init(httpLayer: HTTPLayer) {
        self.httpLayer = httpLayer
    }

     func transactions(completion: @escaping (Result<[Transaction]>) -> Void) {
        self.httpLayer.request(at: .listTransactions) { (data, error) in
            if error != nil {
                completion(.failure(error! as NSError))
            } else {
                do {
                    let transactions = try JSONDecoder().decode([Transaction].self, from: data!)
                    completion(.success(transactions))
                } catch {
                    completion(.failure(self.defaultError))
                }
            }
        }
    }

     func transactionDetails(for transaction: Transaction, completion: @escaping (Result<TransactionDetails>) -> Void) {
        self.httpLayer.request(at: .transactionDetails(transaction.id)) { (data, error) in
            if error != nil {
                completion(.failure(error! as NSError))
            } else {
                do {
                    let transactions = try JSONDecoder().decode(TransactionDetails.self, from: data!)
                    completion(.success(transactions))
                } catch {
                    completion(.failure(self.defaultError))
                }
            }
        }
    }

     var defaultError: NSError = NSError(domain: "", code: 1, userInfo: nil)

 }


texts:
This is an implementation of the Haversine formula in Microsoft Transact SQL.

How can I simplify the function?

CREATE FUNCTION dbo.Haversine(@point_a geography, @point_b geography)
RETURNS FLOAT
AS BEGIN
    DECLARE @result FLOAT
    DECLARE @lat1 FLOAT = @point_a.Lat
    DECLARE @lon1 FLOAT = @point_a.Long
    DECLARE @lat2 FLOAT = @point_b.Lat
    DECLARE @lon2 FLOAT = @POINT_b.Long

    DECLARE @earth_radius FLOAT =  6371
    DECLARE @dLat FLOAT = RADIANS(@lat2 - @lat1)
    DECLARE @dLon FLOAT = RADIANS(@lon2 - @lon1)
    SET @lat1 = RADIANS(@lat1)
    SET @lat2 = RADIANS(@lat2)

    DECLARE @a FLOAT
    SET @a = POWER(SIN(@dLat/2),2) + COS(@lat1)*COS(@lat2)*POWER(SIN(@dLon/2),2)
    DECLARE @c FLOAT = 2*ASIN(SQRT(@a))
    SET @result = @earth_radius * @c;
    RETURN @result
END

Here is a test of the function:

DECLARE @target_point geography = (SELECT GeoLocation FROM WA_Features WHERE FEATURE_NAME = 'Seattle' AND FEATURE_CLASS='Populated Place');

SELECT FEATURE_NAME, dbo.Haversine(@target_point, GeoLocation)*0.62137 FROM WA_Features WHERE FEATURE_CLASS='Lake' ORDER BY dbo.Haversine(@target_point, GeoLocation);

Am I calling the function properly? And is there a way to call it only once per row?


texts: Delete folder if it exists in PowerShell

texts:
In my PowerShell script I'm trying to delete a folder, but only if it exists:

if (Test-Path $folder) { Remove-Item $folder -Recurse; }

I find myself repeating this combination of cmdlets quite a few times, and wished I had something like this:

# Pseudo code:
Remove-Item $folder -Recurse -IgnoreNonExistentPaths

Is there a way to do something like that? A different command, or an option I've missed from the Remove-Item documentation perhaps? Or is the only way to DRY out this bit of code to write my own cmdlet that combines Test-Path and Remove-Item?


texts:
I was curious which way is generally preferred, or if there is even a preference, given these two options:

$.ajax({
    url: '../Component/GetSearchFilters',
    success: function (response) {
        console.log("Outer scope:", this);
    }.bind(this)
});

If I was inside of a function where I needed both "this" and outer-scope's "this," then I would assign a variable, but I generally prefer binding to keep variable usage scoped to as few lines as possible.


texts: Form a firstname.lastname@domain.se address, eliminating diacritics from a name

texts:
I'm an amateur programmer who just started learning programming, my school gave me an assignment to create code that reads a surname and lastname from an input dialog box and then to edit those name in the format of "surname.lastname@nackademin.se" all of wich should be in lowercase letters and only letters of a-z since in sweden we sometimes use "å,ä,ö" in our names.
I have managed to do so, as you can see below but i was wondering if there was a simpler way to do this (perhaps by using less code).

import javax.swing.*;
public class Namn {
    public static void main(String[] arg) {
        char c = '.';
        String s = JOptionPane.showInputDialog(null, "Ange namn och efternamn");
        s = s.replaceAll("\\s{2,}", " ").trim();
        s = s.replace(' ', c);
        s = s.toLowerCase();
        s = s.replace('å', 'a');
        s = s.replace('ä', 'a');
        s = s.replace('ö', 'o');
        JOptionPane.showMessageDialog(null, s + "@nackademin.se");
        System.exit(0);
    }
}


texts:
I am new to writing utility functions. I wrote a python program to return a Python logger with custom settings. Please review this code and provide comments on how to improve it. I am looking for comments on

Coding Style
Coherence & Coupling
Readability

I am intending to share this code across all projects. So any comments on this to improve are highly appreciated.

import logging
import sys
import logging.handlers

def get_default_log_format():
    """ Method to return the default log format"""
    log_format = logging.Formatter("%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s")
    return log_format

def get_new_console_handler(log_format=None):
    """This method returns a console handler with the given log_format
        Keyword Arg: log_format accepts logging.Formatter object.
    """
    console_handler = logging.StreamHandler(sys.stdout)
    if log_format is None:
        log_format = get_default_log_format()
    console_handler.setFormatter(log_format)
    return console_handler

def get_new_file_handler(log_format=None, log_file_name="out.log"):
    file_handler = logging.FileHandler(log_file_name)
    if log_format is None:
        log_format = get_default_log_format()
    file_handler.setFormatter(log_format)
    return file_handler

def get_new_rotating_file_handler(log_file_name="out.log", max_log_bytes=2000000, max_log_backup_files=20, log_format=None):
    """ This method returns a file handler with the given file name, max_log_bytes, max_log_backup_files and log_format. This log_format accepts logging.Formatter object"""
# Here, max_log_bytes is the maximum size of file in Bytes and max_log_backup_files is the number of backup files to store.
    file_handler = logging.handlers.RotatingFileHandler(log_file_name, maxBytes=max_log_bytes, backupCount=max_log_backup_files)
    if log_format is None:
        log_format = get_default_log_format()
    file_handler.setFormatter(log_format)
    return file_handler

def get_new_console_logger(logger_name, log_format=None, log_level=logging.DEBUG):
    handler = get_new_console_handler()
    logger = logging.getLogger(logger_name)
    logger.setLevel(log_level)
    logger.addHandler(handler)
    return logger

def get_new_file_logger(logger_name, log_file, log_format=None, log_level=logging.DEBUG):
    handler = get_new_file_handler(log_format, log_file)
    if log_file is None:
        log_file = "execution.log"
    logger = logging.getLogger(logger_name)
    logger.setLevel(log_level)
    logger.addHandler(handler)
    return logger

def get_new_file_console_logger(logger_name, log_file, log_format=None, log_level=logging.DEBUG):
    if log_file is None:
        log_file = "execution.log"
    logger = get_new_file_logger(logger_name, log_file)
    console_handler = get_new_console_handler()
    logger.addHandler(console_handler)
    return logger

if __name__ == "__main__":
    # To get a console handler, run this code
    console_logger = get_new_console_logger(logger_name="logger1")
    console_logger.debug("Hello World")

    # To get a file logger, run this code
    file_logger = get_new_file_logger(logger_name="logger3", log_file="out.log")
    file_logger.critical("This is a critical message")

    # To get a console and file logger, run this code
    console_file_logger = get_new_file_console_logger(logger_name="my_logging2", log_file="out3.log")
    console_file_logger.error("Error: This is from console file logger")

    # logger.info("Begining of execution")
    # logger.info("logging Info message")
    # logger.debug("This is a debug message")
    # logger.debug(logging.DEBUG)
    # logger.info(logging.INFO)
    # logger.warning(logging.WARNING)
    # logger.error(logging.ERROR)
    # logger.critical(logging.CRITICAL)
    # logger.info("End of Execution")


texts:
I'm fairly new to ASP.NET Core, I've used webforms for years so I naturally want to cling to things I did with webforms. The following code works, but I'm wondering if it can be cleaned up with existing .NET Core functionality I'm unaware of?

Tech stack
Asp.net Core 2.0, EntityFramework core with Postgres database

Razor File for login:

@{
ViewData["Title"] = "My apps login title";
// Making this nullable makes it so I don't
// have to pass a false boolean when I'm not postbacking
bool? failedLogin = (bool?)ViewData["failedLogin"];
}

My Application's name goes here

<form method="post">

            Username:
            <input type="text" class="form-control" id="username" name="username">

            Password:
            <input type="password" class="form-control" id="password" name="password">

            <input type="checkbox"> Remember me

        @if (failedLogin == true)
        {

                Invalid Username and/or password

        }
        <button type="submit" class="btn btn-default">Submit</button>
</form>

My Controller Postback(Is that the correct terminology in MVC?) method

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(string username, string password)
{
    // I don't like seeing (using() {} everywhere in my code. I like to hide the ugliness)
    var matchedUser = ProgramWideFunctions.getUserByUserNameAndPassword(username, password);
    if (matchedUser != null)
    {
        HttpContext.Session.SetString("username", matchedUser.username);
        return RedirectToAction("ControlCentre");
    }
    else
    {
        ViewData["failedLogin"] = true;
        return View();
    }
}

You might've noticed I hid the ugliness of the using statements for the database check in an external file. I'm considering making these two methods overloaded (two getUser() methods, one for UN, and another for UN/PW

public static KAPUsers getUserByUserName(string username)
    {
        using (var db = new AlertsDbContext())
        {
            return db.KAPUsers.Where(b => b.username == username).FirstOrDefault();
        }

    }

    public static KAPUsers getUserByUserNameAndPassword(string username, string password)
    {
        using (var db = new AlertsDbContext())
        {
            return db.KAPUsers.Where(b => b.username == username && b.password == password).FirstOrDefault();
        }

    }


texts: Python preprocesser that allows "until" and "unless" statements

texts:
I've implemented the beginnings of a Python preprocesser I plan to implement sometime in the future, and the below code is my simple prototype. At the moment, it only converts until and unless statements.

py_preproc.py

"""
A simple Python utility that converts
non-valid Python code, like `until`,
and `unless` blocks to valid Python
code.
"""
from sys import argv

try:
    file_path = argv[1]
    execute_results = argv[2]
except IndexError:
    raise Exception("Two argv arguments are required, file_path, and execute_results.")

def open_code_file():
    """
    Opens the code file to do the conversion
    on, and returns the read version as a
    string.
    """
    with open(file_path, "r+") as code_file:
        return code_file.read()

def replace_items(file_string):
    """
    Replace specific pieces of the code_file
    with valid Python code. Currently only
    `until`, and `unless` blocks are replaced.
    """
    return file_string.replace(
        "until", "while not"
    ).replace(
        "unless", "if not"
    )

def evaluate_result(result_string):
    """
    Evaluates the converted result, after
    the code has been converted to valid
    Python code.
    """
    py_string_compiled = compile(result_string, "fakemodule", "exec")
    exec(py_string_compiled)

def main():
    file_string = open_code_file()
    new_file_string = replace_items(file_string)

    if execute_results == "-true":
        evaluate_result(new_file_string)

    elif execute_results == "-false":
        with open(file_path) as file_to_write:
            file_to_write.truncate()
            file_to_write.write(new_file_string)

    else:
        raise Exception("Invalid argument \"{argument}\".".format(argument=execute_results))

if __name__ == '__main__':
    main()

For reference, here's an example of a code file using until and unless, before it's preprocessed.

iterator = 10

until iterator == 0:
    print(iterator)
    iterator -= 1

unless iterator != 0:
    print("iterator == 0")

The above example is then converted to this:

iterator = 10

while not iterator == 0:
    print(iterator)
    iterator -= 1

if not iterator != 0:
    print("iterator == 0")

Finally, here's the command line syntax for running the command, where file_to_execute_or_convert.py is the Python file that you want to run or convert, and execute_or_write is -true if you want to just execute it, or -false if you want to convert it.

python py_preproc.py [file_to_execute_or_convert.py] [execute_or_write]


texts:
I'm learning Dynamic Programming, following the topcoder guide. I just solved the BadNeighbors puzzle. It passes all the test cases, but I don't have much experience, so I don't know if it's good.

  Puzzle Description:

  Each of the town's residents is willing to donate a certain amount, as specified in the int[] donations, which is listed in clockwise order around the well. However, nobody is willing to contribute to a fund to which his neighbor has also contributed. Next-door neighbors are always listed consecutively in donations, except that the first and last entries in donations are also for next-door neighbors. You must calculate and return the maximum amount of donations that can be collected.

def circle(lst):
    if len(lst) == 1:
        return lst[0]
    attempt_1 = _circle(lst, 0, len(lst)-1)
    attempt_2 = _circle(lst, 1, len(lst))
    return max(attempt_1, attempt_2)

def _circle(lst, start, end):
    prev, best = 0, 0
    for i in xrange(start, end):
        val = lst[i]
        current = val + best
        best = max(prev, best)
        prev = current
    return best

Edit: Check the comments of my selected answer for the full resolution.


texts: Print Consecutive numbers by comparing two parameters

texts:
input 3,5 output should be 3,4,5

input 5,3 output should be 5,4,3

And the code

public static void test(int a, int b) {
        if(a>b) {
            for (int i = a; i >= b; i--) {
                System.out.print(i + "\t");
            }
        }else if(a<b) {
            for (int i = a; i <= b; i++) {
                System.out.print(i + "\t");
            }
        }
    }

It works but looks a little messy. Is it possible to do without if else thing? Only one loop.


texts:
I have a question regarding whether it is viable or deemed correct if a validation object invoked a query.  Essentially, I have some code that looks like this:

public interface ICountryCodeValidator
{
    IEnumberable<ValidationError> Validate(string countryCode);
}

public class CountryCodeValidator : ICountryCodeValidator
{
    private readonly IGetCountryCodeQuery getCountryCodeQuery;

    public CountryCodeValidator(IGetCountryCodeQuery getCountryCodeQuery)
    {
        this.getCountryCodeQuery = getCountryCodeQuery;
    }

public IEnumberable<ValidationError> Validate(string countryCode)
{
    var errors = new List<ValidationError>();

    if (string.IsNullOrEmpty(countryCode) || countryCode.Length > 2)
    {
        errors.Add(new ValidationError { Code = "InvalidRequest", Message = "Country code is invalid." });
    }
    else
    {
        if (this.getCountryCodeQuery(countryCode) == null)
        {
            errors.Add(new ValidationError { Code = "NotFound", Message = "CountryCode not found." });
        }
    }

    return errors;
}
}

Immediately, I am thinking that CountryCodeValidator responsibilities are growing and whether it should be querying the DB is debatable. Is it perfectly OK for an object simply responsible for validation to perform such an operation?

Further elaborating on this, I have unit tests surrounding CountryCodeValidator and assert against the error codes returned ensuring the correct codes are returned depending on the input (which is fine).

The trouble is, within my Web API controller I have to perform checks on the error code being returned back and depending on the error code create the appropriate status code. For example:

public class CountriesContoller : ApiController
{
    private readonly ICountryCodeValidator countryCodeValidator;
    private readonly ICountryCodeRepository countryCodeRepository;

    public CountriesContoller(ICountryCodeValidator CountryCodeValidator, ICountryCodeRepository CountryCodeRepository)
    {
        this.countryCodeValidator = countryCodeValidator;
        this.countryCodeRepository = countryCodeRepository;
    }

    public HttpResponseMessage Get([FromUri]string countryCode)
    {
        var errors = this.countryCodeValidator.Validate(countryCode);

        if (errors.Any())
        {
            //Code smell?
            var countryNotFoundError = errors.FirstOrDefault(x => x.Code == "NotFound");

            if (countryNotFoundError != null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, countryNotFoundError);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
        }

        return Request.CreateResponse(HttpStatusCode.OK, this.countryCodeRepository(countryCode));
    }
}

I guess, the bit I am concerned with is the fact I am leaking the error code definitions in each of my domains and tests.

Web API layer I am performing a linq query to check if this error has been added
Domain layer needs to know about this due to validation
Tests are aware as I am testing whether a NotFound is invoked, so when I mock the CountryCodeValidator I am ensuring it returns a collection of errors with a particular error code.

A quick easy thing to do is create constants or an enum so I am not using magic strings but still this doesn't seem right.

I realise I have 2 calls to the database being made:

One to verify the call is not null
Second to get the country and return it back

This is simply pseudo code.


texts:
Triggered by an interview question (I didn't answer during the interview) I wrote a Java program to reverse a linked list. I went with a loop-based approach instead of recursion. I would like to know the following:

Is the reverse() method efficient as it is, or can it be improved?
Are the inline comments inside the reverse() method clear or are they confusing and/or superfluous?

The following is the code for the entire LinkedList class I wrote, containing a public reverse() method:

public class LinkedList<T> {
    /**
     * A Node represents a single item inside the linked list. Each node contains
     * the value of the item and a pointer to the next node.
     */
    class Node {
        T value;
        Node next;
    }

    /**
     * The 'head' is the beginning of the linked list.
     */
    Node head;

    /**
     * Add an item to the end of the linked list.
     *
     * @param value - The value of the item to be added
     */
    public void add(T value) {
        // Create the new node to be added
        Node newNode = new Node();
        newNode.value = value;

        // If list is empty, add it at the head
        if (head == null) {
            head = newNode;
            return;
        }

        // If the list is not empty, find the end of the list and add it there
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    /**
     * Perform an in-place reversal of the elements in the linked list.
     *
     * After this method is called, the order of the elements in the linked list
     * will be reversed.
     */
    public void reverse() {
        Node current = head;        // Start at the beginning
        Node previous = null;       // In each iteration, points to the current node's previous node
        Node next;                  // In each iteration, we use this to backup the current node's next node
        while (current != null) {
            next = current.next;        // Backup current node's next node
            current.next = previous;    // Point current node backwards - to the previous node
            previous = current;         // Set new previous to current node, for next iteration
            head = current;             // Point head to current, so by end of loop, it will point to the original tail
            current = next;             // Point current to the original next node, for next iteration
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("");
        Node current = head;
        while (current != null) {
            sb.append(current.value + " ");
            current = current.next;
        }
        return sb.toString();
    }
}

The following is the code I used to test the above method, just in case it is required:

public class LinkedListReversal {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        System.out.println(list);

        list.reverse();

        System.out.println(list);
    }
}


texts: Converting events in an agenda to textual format

texts:
Here is a serializer. My concern is to make the convert_to_internal function more pythonic, efficient and ideally more functional. Maybe I could also get rid of three nested loops.

class TimeSerializer(serializers.Field):
    DAYS = {
        0: 'monday',
        1: 'tuesday',
        2: 'wednesday',
        3: 'thursday',
        4: 'friday',
        5: 'saturday',
        6: 'sunday',
        7: 'holidays'
    }
    INVERSE_DAY = {v: k for k, v in DAYS.items()}

    def __day_comparator(day_1, day_2):
       """
       A helper to sort days, so they're sorted
       as they appear in a week calendar.
       """
       inverse_dict = TimeSerializer.INVERSE_DAY
       return inverse_dict[day_1[0]] - inverse_dict[day_2[0]]

    def convert_to_internal(self, agenda):
        x = []
        t = OrderedDict(sorted(agenda['timconf'].items(),
                               key=TimeSerializer.__day_comparator))
        for day, items in t.items():
            day_num = TimeSerializer.INVERSE_DAY[day]
            for item in sorted(items, key=lambda k: k['begin']):
                for attr in ['begin', 'end']:
                    if hasattr('item', attr):
                        item[attr] = item[attr] + day_num*24*60*60
                x.append(TimeItem(**item))
        p = ';'.join(map(str, x))
        return "-t {} -n {} -p '{}'".format(agenda['timeZone'], agenda['locale'], p)


texts:
A friend of mine told me he had the following exercises at his interview :

  You need to determine when a task will be completed if you are given :

  A date when the task is started
  The duration of the task in hours (how much hours it should take in total)
  The starting time and end time of a working day

  Weekends are not work days and you can assume that there are no holidays.
  Taking this in consideration what's the date when the task will be completed
  (hours and minutes are taken in consideration) ?

(The original exercise was meant to work with database but I simplified it a bit.)

Here's my solution to the problem :

public class Program
{
    private static void Main()
    {
        DateTime startOfTask = new DateTime(2016, 2, 27, 10, 30, 0);

        TimeSpan durationOftask = new TimeSpan(20, 30, 0);

        TimeSpan startOfDay = new TimeSpan(8, 30, 0);
        TimeSpan endOfDay = new TimeSpan(16, 0, 0);

        DateTime endOfTaskTime = GetEndOfTaskTime(durationOftask, startOfTask, startOfDay, endOfDay);
        Console.WriteLine(endOfTaskTime.ToString("yyyy.MM.dd HH:mm"));
        Console.ReadKey();
    }

    private static DateTime GetEndOfTaskTime(TimeSpan durationOftask, DateTime startOfTask, TimeSpan startOfDay,
        TimeSpan endOfDay)
    {
        DateTime endOfTask = startOfTask;
        TimeSpan timeWorkingOnTask = new TimeSpan(0, 0, 0);
        while (timeWorkingOnTask < durationOftask)
        {
            if (endOfTask.DayOfWeek != DayOfWeek.Saturday && endOfTask.DayOfWeek != DayOfWeek.Sunday)
            {
                TimeSpan timeStartOfToday = new TimeSpan(endOfTask.Hour, endOfTask.Minute, 0);
                TimeSpan workTime = timeStartOfToday == startOfDay
                    ? endOfDay - startOfDay
                    : endOfDay - timeStartOfToday;
                if (timeWorkingOnTask + workTime < durationOftask)
                {
                    endOfTask = endOfTask.Add(workTime);
                    timeWorkingOnTask += workTime;
                }
                else
                {
                    endOfTask = endOfTask.Add(durationOftask - timeWorkingOnTask);
                    break;
                }
            }
            endOfTask = endOfTask.AddDays(1);
            endOfTask = new DateTime(endOfTask.Year, endOfTask.Month, endOfTask.Day, startOfDay.Hours,
                startOfDay.Minutes, 0);
        }
        return endOfTask;
    }
}


texts: Checking a board to see if a player has three in a row

texts:
The code checks many more conditions like the one below. I was thinking to memoize it, but I can't think about how (writers block). How else could I optimize this? I know it seems silly, but my code is spending the majority of the time in the function.

def has_three(p, board):
    """Checks if player p has three in a row"""
    # For every position on the board
    for i in xrange(6):
        for j in xrange(7):
            if board[i][j] == p:
                if i<=2 and board[i+1][j]==p and board[i+2][j]==p and board[i+3][j]==0:
                    return True
                if i>=3 and board[i-1][j]==p and board[i-2][j]==p and board[i-3][j]==0:
                    return True
                if j<=3 and board[i][j+1]==p and board[i][j+2]==p and board[i][j+3]==0:
                    return True
                if j>=3 and board[i][j-1]==p and board[i][j-2]==p and board[i][j-3]==0:
                    return True
                if i<=2 and j<=3 and board[i+1][j+1]==p and board[i+2][j+2]==p and board[i+3][j+3]==0:
                    return True
                if i<=2 and j>=3 and board[i+1][j-1]==p and board[i+2][j-2]==p and board[i+3][j-3]==0:
                    return True
                if i>=3 and j<=3 and board[i-1][j+1]==p and board[i-2][j+2]==p and board[i-3][j+3]==0:
                    return True
                if i>=3 and j>=3 and board[i-1][j-1]==p and board[i-2][j-2]==p and board[i-3][j-3]==0:
                    return True
    return False


texts:
I've made this validation class in PHP that would take inputs, on initialization sanitize them and validate them specific to the type. It works fine, but I would like to know if there's some bad practice involved and how I can improve it.
I would also love to hear if there's anything that makes the code awful or hard to read. Does it follow good coding standards? If not, how can I improve it?

Class Validate {
    //Take the user input into the data put it to a class.
    private $data; //Function argument
    private $err; // boolean
    public $empty;
    private $errMsg;

    public function __construct($data) { //Not sure about this one. Have to check it out later and decide

        //perform some basic level validation like checking for emptiness.
        foreach ($data as $k =>$v) {
            $data[$k]= $v;
            if($this->checkEmpty($v)==1) {
                $this->empty=true;

            }
        }

    }

    private function checkEmpty($data) {
        if($data==""|| empty($data) || !isset($data)) {
    return 1;
        }
    }
    private function basicSanitize($data) { //Basic level input santization to be used by other functions only.

    $data=htmlspecialchars($data);
    $data=trim($data);
    $data=stripslashes($data);

    return $data;
    }

    public function sanitize($data) { // Sanitization at a massive level to sanitize a lot of inputs at one go.
        foreach ($data as $k =>$v) {
            $this->data[$k]= $this->basicSanitize($v);
            }

            return $this->data;
    }

    public function name($data) {

        if(strlen($data)<3) {

            $this->errMsg = "Name too short.";
        }

        else if(strlen($data)>100) {
            $this->errMsg = "Name too big.";
        }

        if(isset($this->errMsg)) {
            return $this->errMsg;
        }

        else return true;
    }

    public function email($data) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
             $this->errMsg = "Invalid email format";
        }

        if(isset($this->errMsg)) {
            return $this->errMsg;
        }

        else return true;
    }

}

And here is calling the class:

    $name="J";
    $email="mephone@2d.com";

    $input= array (
        'name'=>$name,
        'email'=>$email
        );

    $val=new Validate($input);
    if($val->empty==false) {

        $clean=$val->sanitize($input);

        $nameErr = $val->name($clean['name']);
        if($nameErr)  {
        echo $nameErr;
        }

        else echo $clean['name'];

Should I be calling the error messages like that? What could be a more systematic and better way to do that?


texts: Insert multiple rows without using CURSOR SQL Server 2014

texts:
I have a fairly complex query which insert multiple rows into a table from multiple tables. Its works fine but I really don't want to use cursor as some blog says cursor took long time for execution (of course it depends). I hope I could find alternative way for minimize my execution time or cursor complexity. Here is my query:

DECLARE @employeeid int;
DECLARE @joiningdate date;
DECLARE @quitdate date;
DECLARE @eodrefs int,@amounts decimal;

select @employeeid=HRMS_Employee.ID,@joiningdate=HRMS_Employee.Joining_Date,@quitdate=HRMS_Employee.QuitDate
from HRMS_Employee where HRMS_Employee.Present_Status=1 and ID=4

DECLARE @tabEodRecord table(eodref  int,amount decimal)
insert INTO @tabEodRecord (eodref,amount)

select HRMS_EodRecord.Eod_RefFk,HRMS_EodRecord.ActualAmount from HRMS_EodRecord join HRMS_Employee on HRMS_EodRecord.EmployeeId=HRMS_Employee.ID
where HRMS_EodRecord.Status=1 and HRMS_EodRecord.EmployeeId=@employeeid

IF CURSOR_STATUS('global','PayrollInfoCursor')>=-1
    BEGIN
     DEALLOCATE PayrollInfoCursor
    END

DECLARE PayrollInfoCursor CURSOR
FOR (select eodref,amount from @tabEodRecord)
OPEN PayrollInfoCursor;
    FETCH NEXT FROM PayrollInfoCursor INTO  @eodrefs,@amounts
    WHILE @@FETCH_STATUS = 0
BEGIN
insert HRMS_PayrollInfo (PayrollFK,EmployeeIdFk,Eod_ReferenceFk,Amount,PaymentDate,[Status],AlertActive,Entry_By,Entry_Date,Update_By,Update_Date)
select 26,@employeeid,@eodrefs,@amounts,getdate(),1,1,1,getdate(),1,getdate()
FETCH NEXT FROM PayrollInfoCursor INTO  @eodrefs,@amounts
END
CLOSE PayrollInfoCursor
DEALLOCATE PayrollInfoCursor

I hope there is something like this (however this won't work) because subquery returns multiple rows

insert HRMS_PayrollInfo (PayrollFK,EmployeeIdFk,Eod_ReferenceFk,Amount,PaymentDate,[Status],AlertActive,Entry_By,Entry_Date,Update_By,Update_Date)
select 26,@employeeid,(select eodref from tabEodRecord),(select amountfrom tabEodRecord),getdate(),1,1,1,getdate(),1,getdate()


texts: Counting thousands of selected checkboxes

texts:
This is a script I use to count how many items are selected in a form. It currently loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked. The form has thousands of checkboxes, and it's painfully obvious how slow the script is with this many elements (About 18,240 items in my sample query).

Any ideas on how I can speed this up? The speed is fine when there's less than 1,000 results, but there's rarely that few when it's running in production.

function countSelected()
{
    var daform  = document.forms.resultsForm;
    var daspan  = document.getElementById("acctSelected");
    var counter = 0;
    var i       = 0;

    if (daform.multi.length == undefined) {
        if (daform.multi.checked) {
            counter = "1";
        } else {
            counter = "0";
        }
    } else {
        for (i = 0; i < daform.multi.length; i++)
        {
            if (daform.multi[i].checked) {
                counter++;
            }
        }
    }

    daspan.innerHTML = counter;
}

Fun facts:

This script is fastest in Firefox 16.0.2 (about 2 secs)
Second fastest by a slim margin in Internet Explorer 9 (about 2.25 secs)
And absurdly slow in Chrome version 23.--- (I got tired of waiting)


texts: Place try/catch in business logic or user interface

texts:
I found the following two types of exception-handling in Business Logic Layer.

ASP.NET 3.5 Enterprise Application Development uses a similar method like the first one (I read it few years ago).

I also found this on Stack Overflow, but it doesn't answer my question.

I'm wondering which one is better design and efficiency.

Method 1 - in Business Logic Layer

private int InsertUser(string firstname, string lastname, ref List<string> errors)
{
    if (!string.IsNullOrEmpty(firstname))
        errors.Add("First name is required.");

    if (!string.IsNullOrEmpty(lastname))
        errors.Add("Last name is required.");

    if (errors.Count > 0)
        return -1;

    int userId = -1;

    try
    {
        // Insert user and return userId
    }
    catch (Exception ex)
    {
        // Log error to database
        errors.Add("Error occurs. Please contact customer service.");
    }

    return userId;
}

Method 2 - in Business Logic Layer

private int InsertUser(string firstname, string lastname)
{
    if (!string.IsNullOrEmpty(firstname))
        throw new ArgumentNullException(firstname);

    if (!string.IsNullOrEmpty(lastname))
        throw new ArgumentNullException(lastname);

    int userId = -1;

    // Insert user and return userId. Let user handle the exception in UI.

    return userId;
}

The disadvantage of Method 2 is that the UI has to filter out what to display/not display the error depending on the exception.  For instance, you might not want to display a System.Data.Entity exception to the user.


texts:
I started picking up Rust on my free time, and I'm curious about what style errors have I made and where should I improve as a programmer.

The problem is from HackerRank and very simple: there is a fixed-format input of time in 12 hour format (07:05:45PM), and the objective is to convert it to 24 hour format (19:05:45).

My own first impressions:

The problem is very simple, but the code seems too lengthy?
I'm nesting match constructs, and it doesn't seem concise.

use std::io::{stdin, BufRead, Error, ErrorKind, Result};

struct Time {
    hour: u8,
    minute: u8,
    second: u8
}

impl Time {
    pub fn from_12h(time : String) -> Result<Time> {
        assert!(time.chars().count() == 10);
        let hour : String = time.chars().take(2).collect();
        let minute : String = time.chars().skip(3).take(2).collect();
        let second : String = time.chars().skip(6).take(2).collect();
        let period : String = time.chars().skip(8).take(2).collect();

        match Time::hour_from_12h_to_24h(hour.parse::<u8>().unwrap(), period) {
            Ok(hour_24h) =>
                Ok(Time {
                    hour: hour_24h,
                    minute: minute.parse::<u8>().unwrap(),
                    second: second.parse::<u8>().unwrap()
                }),
            Err(e) => Err(e),
        }
    }

    fn hour_from_12h_to_24h(hour : u8, period : String) -> Result<u8> {
        match period.as_ref() {
            "AM" => Ok(hour % 12),
            "PM" => Ok(hour % 12 + 12),
            _ => Err(Error::new(ErrorKind::InvalidData, format!("invalid period {}", period))),
        }
    }

    pub fn to_24h(&self) -> String {
        format!("{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
    }
}

fn main() {
    match read_12h_time() {
        Ok(time_12h) =>
            match Time::from_12h(time_12h) {
                Ok(time) => println!("{}", time.to_24h()),
                Err(err) => println!("error: {}", err)
            },
        Err(err) => println!("input error: {}", err),
    }
}

fn read_12h_time() -> Result<String> {
    let mut buffer = String::new();
    match read_line(&mut buffer) {
        Ok(length) =>
            match length {
                10 => Ok(buffer),
                _ => Err(Error::new(ErrorKind::InvalidInput, format!("expected 10 characters, got {}", length)))
            },
        Err(e) => Err(e),
    }
}

fn read_line(buffer : &mut String) -> Result<usize> {
    let stdin = stdin();
    let mut handle = stdin.lock();
    handle.read_line(buffer)
}


texts: Deduplicating value pairs between 2 columns

texts:
This was asked in the SQL Helpline room:

I have a sql query concern. Could you help me?
It goes like this. I have a table with the Records

A B
A C
B A
B C
C A
C B

How do I get only the records that there aren't duplicated in both columns

A B
A C
B C

While it seemed simple at first, it was surprisingly difficult to get it to work. In the end, I had to resort to a loop. Please mind, this looks like example code, but it is more like practice code, so that the logic can be applied to real situations.

I saved a demo here (which uses temp tables) and the query goes like this:

/* Assuming that @Origin is the source table your data currently is: */
declare @Origin table (val1 char(1), val2 char(1));
insert into @Origin (val1, val2)
values
  ('A', 'B'),
  ('A', 'C'),
  ('B', 'A'),
  ('B', 'C'),
  ('C', 'A'),
  ('C', 'B');

/* Create a temp table in memory:
    Note: We could also use a physicial #holdingTable
    if the result set is too large for memory */
declare @holdingTable table (
  rownum int primary key,
  val1 char(1),
  val2 char(1)
);
insert into @holdingTable (
    rownum,
    val1,
    val2
)
select
  /* generate a rownum to use for looping: */
  row_number() over (order by val1, val2),
  /* add values from origin table: */
  val1,
  val2
from @Origin;

/* loop variables: */
declare @i int = (select min(rownum) from @holdingTable);
declare @max int = (select max(rownum) from @holdingTable);

/* deduplication variables: */
declare @val1Deduplicator char(1);
declare @val2Deduplicator char(1);

/* table to hold result set until end of query: */
declare @resultSet table (val1 char(1), val2 char(1));

while @i <= @max
begin
    /* assign values to deduplicate across columns: */
    select
        /* inversion between val1 and val2 happens here: */
        @val1Deduplicator = val2,
        @val2Deduplicator = val1
    from @holdingTable
    where rownum = @i;
    /* verify we are not inserting a duplicate: */
    if not exists (
        select 1
        from @resultSet
        where val1 = @val1Deduplicator
          and val2 = @val2Deduplicator
    )
    /* if confirmed not a duplicate, insert the values from the current row: */
    begin
        insert into @resultSet (val1, val2)
        select val1, val2
        from @holdingTable
        where rownum = @i;
    end;
    /* increment loop: */
    set @i = @i + 1;
end;
/* obtain the final results: */
select * from @resultSet;

The performance seems OK for this few records, but it's not set-based and might get really slow for a large number of records. Is there a smarter way to do this? Is there anything else I can improve?

Output is correct:

val1 val2
---- ----
A    B
A    C
B    C

(3 row(s) returned)


texts: Efficent way to Query a DB and write to text file - Large Recordset

texts:
I have a SQL query that returns a recordset with between 2 and 5 million records and I need to write that to a .csv file.

I wrote the following procedure and I'm curious to see if there is a better / more efficient way to do this.

Dim conn As New OracleConnection()
...
Sub DBExecuteQueryWriteToFile(ByVal SQLCommand As String, ByVal FileName As String, Optional ByVal Delimiter As String = ",")

    Dim cmd = New OracleCommand(SQLCommand, conn)
    Dim sb As New StringBuilder

    Dim x As Integer = 0
    Dim CountRow As Integer = 0

    If File.Exists(FileName) Then
        File.Delete(FileName)
    End If

    Using FileObject As New FileStream(FileName, FileMode.OpenOrCreate)
        Using MStream As New MemoryStream()
            Using StreamWriterObj As New StreamWriter(MStream)
                Using Reader As OracleDataReader = cmd.ExecuteReader()
                    Dim FieldCount As Integer = Reader.FieldCount - 1

                    Do While Reader.Read()
                        sb.Append(Reader.Item(0))
                        For i = 1 To FieldCount
                            sb.Append(Delimiter)
                            sb.Append(Reader.Item(i))
                        Next
                        sb.Append(vbCrLf)

                        'Write every 25000 rows of data to the file from the buffer
                        If x = 25000 Then
                            StreamWriterObj.Write(sb.ToString().ToCharArray())
                            MStream.Seek(0, SeekOrigin.Begin)
                            MStream.WriteTo(FileObject)
                            sb = New StringBuilder()
                            CountRow = CountRow + x
                            x = 0
                        End If
                        x = x + 1
                    Loop

                    'Write any remaining data from the buffer to the file
                    StreamWriterObj.Write(sb.ToString().ToCharArray())
                    MStream.WriteTo(FileObject)

                    Reader.Close()
                    StreamWriterObj.Close()
                    MStream.Close()
                    FileObject.Close()
                End Using
            End Using
        End Using
    End Using
End Sub

Any and all comments and help are geatly appreciated and, also, even though this is written in VB, I'm equally as comfortable with C# solutions.


texts: Real time metal prices and conversion fro USD to MXN using BeautifulSoup updated version

texts:
from bs4 import BeautifulSoup
import requests
import re
import datetime

metal_translation = {"Aluminium": "Aluminio", "Copper": "Cobre", "Zinc": "Zinc", "Nickel": "Níquel", "Lead": "Plomo", "Tin": "Estaño",
                     "Aluminium Alloy": "Aleación de Aluminio", "Cobalt": "Cobalto", "Gold*": "Oro*", "Silver*": "Plata*",
                     "Steel Scrap**": "Chatarra de Acero", "NASAAC": "NASAAC", "Steel Rebar**": "Varilla de Acero"}

def get_metal_values():
    names = []
    prices = []
    response = requests.get('https://www.lme.com/')
    response.raise_for_status()
    metals = response.text
    soup = BeautifulSoup(metals, 'lxml')
    metal_table = soup.find("table", attrs={"class": "ring-times"})
    metal_table_names, metal_table_prices = metal_table.tbody.find_all("th"), metal_table.tbody.find_all("td")
    for name in metal_table_names:
        names.append(name.text.replace("LME ", ""))
    for price in metal_table_prices:
        prices.append(price.text.strip())
    return names, prices

def get_peso_conversion():
    response = requests.get('https://themoneyconverter.com/USD/MXN')
    response.raise_for_status()
    peso = response.text
    soup1 = BeautifulSoup(peso, 'lxml')
    conversion = soup1.find("div", class_="cc-result").text
    rate = re.search("\d{2}\.\d{4}", conversion).group()
    return rate

def get_time():
    d = datetime.datetime.now()
    date_time = d.strftime("%d/%m/%Y | %H:%M:%S")
    return date_time

def convert_values():
    names, prices = get_metal_values()
    rate = get_peso_conversion()
    for k, v in zip(names, prices):
        v = (float(v.replace(",", "")) * float(rate))
        print(f'{metal_translation[k]}: {v:.2f} $')

def program_run():
    print("Metal Prices by ETHAN HETRICK")
    print("================================================")
    print(f'{get_time()} | 1 USD = {get_peso_conversion()} MXN\n')
    print("Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)\n")
    convert_values()
    print("================================================")

program_run()

Example Output:
input("\nEscribe 'x' para terminar.\n")

Metal Prices by ETHAN HETRICK
================================================
26/06/2020 | 21:59:00 | 1 USD = 23.0622 MXN

Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)

Aluminio: 36484.40 $
Cobre: 138038.80 $
Zinc: 47438.95 $
Níquel: 293097.50 $
Plomo: 41004.59 $
Estaño: 391826.78 $
Aleación de Aluminio: 27997.51 $
NASAAC: 27444.02 $
Cobalto: 657272.70 $
Oro*: 40711.70 $
Plata*: 410.74 $
Chatarra de Acero: 6065.36 $
Varilla de Acero: 9720.72 $
================================================

Escribe 'x' para terminar.

This is an updated version of my code from a previous post of mine thanks to @Reinderien
My fiances father owns a metal recycling business in Mexico City, Mexico which requires him to do a lot of calculations when negotiating with clients. Since he was doing this by hand, I decided to automate this for him. I used London Metal Exchange, which is his preferred site to get the current prices, for the metal prices and also got the exchange rate for USD to MXN and applied that as well. I also needed to translate everything to spanish so I used a dictionary. This is my first time utilizing webscraping and the datetime module so any advice to make this program run more efficiently or make the code more concise is much appreciated!


texts:
I have three primary tables:

Customer
Product
Order

Relations:

Many to many between product and order.

CREATE TABLE Customer (
    CustomerId int  NOT NULL AUTO_INCREMENT,
    CustomerName varchar(50)  NOT NULL,
    CustomerMail varchar(50)  NOT NULL,
    CONSTRAINT Customer_pk PRIMARY KEY (CustomerId)
);

-- Table `Order`
CREATE TABLE `Order` (
    OrderId int  NOT NULL AUTO_INCREMENT,
    OrderDate date  NOT NULL,
    CustomerId int  NOT NULL,
    CONSTRAINT Order_pk PRIMARY KEY (OrderId)
);

-- Table Product
CREATE TABLE Product (
    ProductId int  NOT NULL AUTO_INCREMENT,
    ProductName varchar(50)  NOT NULL,
    SKU varchar(50)  NOT NULL,
    Price decimal(8,2)  NOT NULL,
    CONSTRAINT Product_pk PRIMARY KEY (ProductId)
);

-- Table ProductOrder
CREATE TABLE ProductOrder (
    ProductOrderId int  NOT NULL AUTO_INCREMENT,
    OrderId int  NOT NULL,
    ProductId int  NOT NULL,
    Quantity int  NOT NULL,
    CONSTRAINT ProductOrder_pk PRIMARY KEY (ProductOrderId)
);

ALTER TABLE `Order` ADD CONSTRAINT Order_Customer FOREIGN KEY Order_Customer (CustomerId)
    REFERENCES Customer (CustomerId);
-- Reference:  ProductOrder_Order (table: ProductOrder)

ALTER TABLE ProductOrder ADD CONSTRAINT ProductOrder_Order FOREIGN KEY ProductOrder_Order (OrderId)
    REFERENCES `Order` (OrderId);
-- Reference:  ProductOrder_Product (table: ProductOrder)

ALTER TABLE ProductOrder ADD CONSTRAINT ProductOrder_Product FOREIGN KEY ProductOrder_Product (ProductId)
    REFERENCES Product (ProductId);

I need to write a query for:

    Create a query for getting the total quantity of products
 ordered and the total value for all orders made
 on the current date.

This is my solution:

-- query for current date
SELECT SUM(quantity) AS TotalQuantity, SUM(quantity * price) AS TotalSaleAmount
     FROM productorder, product, `order`
         WHERE productorder.ProductId = product.ProductId
            AND
                `order`.OrderId = productorder.OrderId
            AND
                `order`.OrderDate = CURDATE()

Can someone help me in optimizing it?


texts: How can I use object oriented principles in the following scenario?

texts:
I have 3 car rental agencies.  Each agency requires the data in XML, but in a different format, for example:

Agency 1

<Rental>
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
<Pickup date="07/20/2012"/>
<Dropoff date="07/25/2012"/>
<Deposit cost="100"/>
</Rental>

Agency 2

<Rental>
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
<Pickup>07/20/2012</Pickup>
<Dropoff>07/25/2012</Dropoff>
<Deposit>100</Deposit>
</Rental>

Agency 3

<Rental pickup="07/20/2012" dropoff="07/25/2012" deposit="100">
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
</Rental>

As you can see from above, all 3 basically contain the same information, altough this doesn't have to be the case (some can contain more or less information), but it is structured different, so the way I access it is different.  What is the best approach to take so I can write the most minimum code, but be able to adapt to new rental agencies that come along with a different structure?

Right now, I am doing something like this:

public class Agency1
{
SubmitRental()
{
//Parse XML for Agency 1
}

//Other methods for agency 1
}

public class Agency2
{
SubmitRental()
{
//Parse XML for Agency 2
}

 //Other methods for agency 2
}

public class Agency3
{
SubmitRental()
{
//Parse XML for Agency 3
}

//Other methods for agency 3
}

In the above, the classes contain the same methods, but the way they are implemented is different.  There are some methods, properties, etc that are in some classes, but not in others.  Are interfaces the best way to approach this?  If so, should everything be made an interface?

In the XML samples above, the data was the same, but the format was different, which led some to bring up mapping the all the different formats to a set of common classes, but what about the scenario where not only is the format different, but the data is different as well?

For example:

Agency 4

<Rental start="07/20/12" end="07/25/12">
<Name>John Doe</Name>
<DriverLicenseNumber>193048204820</DriverLicenseNumber>
<DOB>3/4/64</DOB>
<Rental>


texts: Multiplying 2 numbers without using * operator in Java

texts:
I saw this interview question and decided to solve using recursion in Java.

  Write a multiply function that multiples 2 integers without using *

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter first num: ");
    double num = in.nextDouble();
    System.out.println("Enter second num: ");
    double numTwo = in.nextDouble();

    System.out.println(multiply(num, numTwo));
  }

  private static double multiply(double x, double y) {

    if (x == 0 || y == 0) {
      return 0;
    } else if (y > 0) {
      return x + multiply(x, y - 1);
    } else if (y < 0) {
      return -multiply(x, -y);
    } else {
      return -1;
    }
  }
}

What should I return instead of -1 to make this clear?


texts: Using external conditions with functions in bash

texts:
As a part of my bash script, I am dealing with the optimization of some function, which take input csv file(s) and process it via some AWK script. This is the function, which operates on input file(s):
rescore_data () {
# accepting $str file(s) given outside the function in bash
echo "DEBUG info: The following CSV file is being processed:" $str
str_name=$(basename ${str} .csv)
printf >&2 "Dataset for ${str_name} is being rescored...  "; sleep 0.1
mkdir ${rescore}/${str_name}
# applying this AWK code on many directories, each of which contains target csv file(s)
while read -r d; do
awk -F ", *" '# SOME AWK CODE and save output inside the same directory (d)
'  "${d}_"*/${str} > "${rescore}/${str_name}/"${d%%_*}".csv"
done
}

And this is control flow how this function may be called inside of bash script according to two different conditions defined manually (1 - operating just with one file; 2 - loop over several filles from list and process each by the function):
# list of target CSV filles
strategies=('*str1.csv' '*str2.csv' '*str3a.csv' '*str3b.csv')
if [[ "${MY_FILT_METHOD}" == 1 ]]; then
   # this is a target file present in each of the directories
   str='*str1.csv'
   # run rescore_data function to process it
   rescore_data
  elif [[ "${MY_FILT_METHOD}" == 0 ]]; then
   # in each dir there are several target filles, defined in the array list
   for str in ${strategies[@]}; do
    rescore_data
   done
  else
   echo "GREAT NEWS: when you see this message, you code is wrong!"
  fi

May this workflow be modified to automatically define the variable $str inside the function according to the same variable provided in the control flow IF conditions part?


texts:
Input:

{ 1: [2,3], 2:[4], 3: [5,6], 4:[6] }

Expected output:

[[1, 2, 4, 6], [1, 3, 5], [1, 3, 6]]

My Code:

def parse(node, tree):
    result = []
    if node not in tree:
        return [[node]]
    else:
        res = []
        for next_node in tree[node]:
            res.extend(parse(next_node, tree))
        for r in res:
           result.append([node]+r)
        return result

I'm looking for a less-complex solution.


texts:
Looking for code review, optimizations, good practice recommendations etc.

/**
 * This is utility class for operations on rotated one-d array.
 *
 * Note: a sorted array, reverse-sorted or a single element is array is not considered rotated sorted.
 * Eg:
 * [4, 5, 1, 2, 3] is condidered rotated.
 * While.
 * [1, 2, 3, 4, 5] is not considered rotated
 *
 *
 * Complexity: O (log n)
 */
public final class RotatedOneDSortedArray {

    private RotatedOneDSortedArray() { }

    /**
     * Searches for the value provided in the rotated sorted array.
     * If found, returns the index, of provided array, else returns -1.
     * If array is not rotated and sorted, then results are unpredictable
     *
     * Throws an exception if array is null.
     *
     * @param a the rotated sorted array
     * @param x the element to be searched
     * @returns the index at which the element is found, else returns -1
     */
    public static int binarySearchForRotatedArray(int[] a, int x) {
        int partitionIndex = findPartition(a, 0, a.length - 1);

        if (partitionIndex == -1) return -1;

        if (x >= a[0] && x <= a[partitionIndex]) {
            return binarySearch(a, 0, partitionIndex, x);
        } else {
            return binarySearch(a, partitionIndex + 1, a.length -1, x);
        }

    }

    private static int binarySearch (int[] a, int lb, int hb, int x) {
        assert a != null;

        if (lb > hb) return -1;

        int mid = (lb + hb)/2;

        if (a[mid] == x) return mid;

        if (a[mid] < x) {
            return binarySearch(a, mid + 1, hb, x);
        } else {
            return binarySearch(a, lb, mid - 1, x);
        }
    }

    /**
     * Returns the index of greatest element of the rotated sorted array.
     * if array is not rotated sorted, results are unprodictable
     *
     * @param a     the input array
     * @param lb    the lower bound
     * @param hb    the higher bound
     * @return      the index of the highest element in the array.
     */
    private static int findPartition(int[] a, int lb, int hb) {
        assert a!= null;

        if (lb == hb) return -1;

        int mid = (lb + hb)/2;

        if (a[mid] > a[mid + 1]) {
            return mid;
        }

        if (a[mid] > a[hb]) {
            // go right.
            return findPartition(a, mid + 1, hb);
        } else {
            // go left.
            return findPartition(a, lb, mid); // note i cannot do mid - 1
        }
    }

    public static void main(String[] args) {
        // even length of the array.
        int[] a1 = {6, 7, 8, 1, 2, 3};
        System.out.println("Expected -1, Actual : " + binarySearchForRotatedArray(a1, -1));
        int[] a2 = {6, 7, 8, 1, 2, 3};
        System.out.println("Expected 1, Actual : " + binarySearchForRotatedArray(a2, 7));
        int[] a3 = {6, 7, 8, 1, 2, 3};
        System.out.println("Expected 5, Actual : " + binarySearchForRotatedArray(a3, 3));
        int[] a4 = {6, 7, 8, 1, 2, 3};
        System.out.println("Expected 2, Actual : " + binarySearchForRotatedArray(a4, 8));
        int[] a5 = {6, 7, 8, 1, 2, 3};
        System.out.println("Expected 3, Actual : " + binarySearchForRotatedArray(a5, 1));

        // odd length of the array.
        int[] a6 = {4, 6, 7, 8, 1, 2, 3};
        System.out.println("Expected -1, Actual : " + binarySearchForRotatedArray(a6, -1));
        int[] a7 = {4, 6, 7, 8, 1, 2, 3};
        System.out.println("Expected 2, Actual : " + binarySearchForRotatedArray(a7, 7));
        int[] a8 = {4, 6, 7, 8, 1, 2, 3};
        System.out.println("Expected 6, Actual : " + binarySearchForRotatedArray(a8, 3));
        int[] a9 = {4, 6, 7, 8, 1, 2, 3};
        System.out.println("Expected 3, Actual : " + binarySearchForRotatedArray(a9, 8));
        int[] a10 = {4, 6, 7, 8, 1, 2, 3};
        System.out.println("Expected 4, Actual : " + binarySearchForRotatedArray(a10, 1));
    }
}


texts: Sum of all arguments ever passed to accumulator

texts:
Q2. Define a function make_accumulator that returns an accumulator
  function, which takes one numerical argument and returns the sum of
  all arguments ever passed to accumulator. Use a list and not a
  nonlocal statement.

Below is the solution:

def make_accumulator():
    """Return an accumulator function that takes a single numeric argument and
    accumulates that argument into total, then returns total.

    >>> acc = make_accumulator()
    >>> acc(15)
    15
    >>> acc(10)
    25
    >>> acc2 = make_accumulator()
    >>> acc2(7)
    7
    >>> acc3 = acc2
    >>> acc3(6)
    13
    >>> acc2(5)
    18
    >>> acc(4)
    29
    """
    lst = []
    def accumulate(n):
        lst.append(n)
        length = len(lst)
        total = 0
        for index in range(length):
            total = total + lst[index]
        return total
    return accumulate

Can we improve this solution?


texts:
Here is my progress calculator class. It is used for downloads/uploads. It takes bytes in and calculates the percentage(to the nearest 5%) that should show on a progress bar. Please let me know how I could improve it. Thanks a lot!!

public class ProgressCalculator {

    private int totalAmount;
    private int progressAmount;
    private int amountProgressItems;
    private int progressBarPercentage;

    //returns if the progress bar needs to change
    public boolean progress(int amount) {
        progressAmount = progressAmount + amount;
        return updateProgressbarPercentage();
    }

    public int getCurrentValue() {
        return progressBarPercentage;
    }

    //returns if the progressbar needs to change
    public boolean addProgressItem(int itemAmount) {
        totalAmount = totalAmount + itemAmount;
        amountProgressItems++;
        return updateProgressbarPercentage();
    }

    //returns true if has been updated;
    private boolean updateProgressbarPercentage() {
        int newProgressBarPercentage = round(calculateProgressPercentage());
        if (progressBarPercentage == newProgressBarPercentage) {
            return false;
        } else {
            progressBarPercentage = newProgressBarPercentage;
            return true;
        }
    }

    public int getAmountOfItems() {
        return amountProgressItems;
    }

    public boolean removeProgressItem(int byteAmount) {
        if (amountProgressItems > 0) {
            totalAmount = totalAmount - byteAmount;
            amountProgressItems--;
        }
        return updateProgressbarPercentage();
    }

    private int calculateProgressPercentage() {
        double x = progressAmount;
        double y = totalAmount;
        double result = (x / y) * 100;
        return (int) result;
    }

    private int round(int num) {
        int temp = num % 5;
        if (temp < 3)
            return num - temp;
        else
            return num + 5 - temp;
    }

    public void clear() {
        totalAmount = 0;
        progressAmount = 0;
        amountProgressItems = 0;
        progressBarPercentage = 0;
    }

}


texts: How do I quickly look for parents containing their own code as child?

texts:
I have tree-like data that is constructed of Parent codes that contain Child codes which may act as parents themselves, depending on if they're marked as "SA". This data is present in an Excel sheet and looks like follows:

| Tree Level (A) | Code (B) | Spec (C) | Comm. Code (D) | Parent Code (J) |
|----------------|----------|----------|----------------|-----------------|
|              1 | A12      |        1 | SA             | Mach            |
|              2 | B41      |        2 | SA             | A12             |
|              3 | A523     |        1 | BP             | B41             |
|              2 | G32      |        4 | BP             | A12             |
|              2 | D3F5     |        1 | SA             | A12             |
|              3 | A12      |        4 | SA             | D3F5            |
|              3 | A12      |        1 | SA             | D3F5            |

There is one issue here: A12, at the top tree level (1), contains a child (D3F5), which itself contains another parent that's the same as D3F5's own parent. As you may be able to imagine, this (although not represented in the data as it is delivered to me) creates an endless loop, where A12 at tree level 3 unfolds the entire structure again and again.

Note that one of the two 'A12' children poses no problem, as this has a different specification as to the A12 parent at tree level 1.

I have a function that checks for this situation, but it is extremely slow as it uses nested loops to go through the rows, and the total row count can be several 1000s:

def nested_parent(sht):
    """
    Checks if a parent SA contains itself as a child.
    :return: nested_parents: Dictionary of found 'nested parents'. None if none found
    """
    nested_parents = {}
    found = False

    lrow = sht.Cells(sht.Rows.Count, 1).End(3).Row
    parent_treelevel = 1

    # Get deepest tree level, as this no longer contains children
    last_treelevel = int(max([i[0] for i in sht.Range(sht.Cells(2, 1), sht.Cells(lrow, 1)).Value]))

    # Loop through parent rows
    print('Checking for nested parents...')
    for i in range(2, lrow):
        if sht.Cells(i, "D").Value == "SA":
            parent_code, parent_treelevel = f'{sht.Cells(i, "B").Value}_{sht.Cells(i, "C")}', sht.Cells(i, "A").Value

            # Add new key with list containing parent's tree level for parent code
            if parent_code not in nested_parents:
                nested_parents[parent_code] = [int(parent_treelevel)]

            # Loop child rows
            for j in range(i + 1, lrow + 1):
                child_code, child_treelevel = f'{sht.Cells(j, "B").Value}_{sht.Cells(j, "C")}', sht.Cells(i, "A").Value

                if child_code == parent_code and child_treelevel > parent_treelevel:
                    found = True
                    nested_parents[parent_code].append(int(child_treelevel))

        if parent_treelevel == last_treelevel:
            # End function if deepst tree level is reached
            print("done")
            if found:
                # Delete keys that contain no information
                delkeys = []
                for key in reversed(nested_parents):
                    if len(nested_parents[key]) == 1:
                        delkeys.append(key)
                for key in delkeys:
                    del nested_parents[key]
                return nested_parents
            else:
                return

This function can be called as follows, where wb_name is the name of the workbook that contains the data:

from win32com.client import GetObject
wb_name = "NAME"
sht = GetObject(None, "Excel.Application").Workbooks(wb_name).Worksheets(1)

infloop = nested_parent(sht)
if infloop is not None:
    dict_str = ''.join([f'Code: {key}, Tree levels: {infloop[key]}\n' for key in infloop])
    err(f"Warning: one or more parent codes contain their own code as a child:\n{dict_str}")

I am hoping to speed up this code, as the rest of my script is fairly quick and its speed is being seriously hampered by this function.


texts: Stored procedure for processed orders in SQL Server

texts:
I am struggling with creating a Stored Procedure in SQL Server for getting sales statistics. I have managed to get the information I need out, but the query is a mess and I have probably messed up the table variable by using 3 different ones.

Any ideas on how to merge this triple part-query into one?

BEGIN
SET NOCOUNT ON;

    DECLARE @SalesStats TABLE
    (
        NumberOfProcessed int,
        SellerID int
    )

    DECLARE @1 TABLE(
    NumberOfPaidOrders int,
    SellerID int
    )

    DECLARE @2 TABLE(
    TotalAmountPaid int,
    SellerID int
    )

    --Number of Processed orders. Removing 0 as its test account.

    INSERT INTO @SalesStats (NumberOfProcessed, PO.SellerID)
    SELECT COUNT(PO.OrderId) AS NumberOfProcessed, PO.SellerID
    FROM ProcessedORder AS PO
    WHERE NOT PO.SellerID = 0
    GROUP BY PO.SellerID
    ORDER BY PO.SellerID

    --Number of paid orders

    INSERT INTO @1 (NumberOfPaidOrders, SellerID)
    SELECT COUNT(AA.OrderId) AS NumberOfPaidOrders, AA.SellerID
    FROM AcceptedOrder AS AA
    LEFT JOIN ProcessedORder AS PO ON AA.OrderId = PO.OrderId
    GROUP BY AA.SellerID
    ORDER BY AA.SellerID

     --Total amount paid

    INSERT INTO @2 (TotalAmountPaid, SellerID)
    SELECT SUM(AA.Amount) AS TotalAmountPaid, SellerID
    FROM AcceptedOrder AS AA
    GROUP BY AA.SellerID
    ORDER BY AA.SellerID

    SELECT DISTINCT(SS.SellerID), SS.NumberOfProcessed, one.NumberOfPaidOrders, two.TotalAmountPaid, two.TotalAmountPaid / one.NumberOfPaidOrders AS AverageAmountPaid FROM @SalesStats AS SS
    LEFT JOIN @1 AS one ON SS.SellerID = one.SellerID
    LEFT JOIN @2 AS two ON SS.SellerID = two.SellerID
    ORDER BY SS.NumberOfProcessed DESC
END


texts: Should a year and month be stored as separate fields or as a date?

texts:
We have a table with calculated data that groups sales by product, year and month, to provide fast querying for statistics.

My colleague argues that the year and month should be two separate fields, because a day is meaningless.

I want it as a date field, because using two separate fields leads to awkward code like this

var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item =>
    (item.Year > lastTwelveMonths.Year
    || (item.Year == lastTwelveMonths.Year && item.Month >= lastTwelveMonths.Month));

instead of this

var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item => item.YearAndMonthAsDate >= lastTwelveMonths);

I understand his argument, but the code is harder to read and there's a higher chance on bugs when doing date/time calculations without using date/time objects. I also can't cast it to a DateTime in the query because I'm using LINQ to Entities.

Which method is the better one?


texts: Remove duplicates from sorted array, in place

texts:
I solved this problem:

  Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

How can I improve its execution time? Is there any better way of doing it?

public int removeDuplicates(int[] numbers) {
    if(numbers.length == 0 || numbers.length == 1) {
        return numbers.length;
    }
    int indexForUniqueElements = 0;
    for (int index = 0; index < numbers.length - 1; index++) {
        if (numbers[index] != numbers[index+1]) {
            numbers[indexForUniqueElements++] = numbers[index];
          }
    }
    numbers[indexForUniqueElements++] = numbers[numbers.length - 1];
    return indexForUniqueElements;
  }


texts:
I have a long running operation that I need to wait for or timeout.
I have working code, but I would like your opinion on improving it.

public bool RegisterEquipmentListUpdate(int ID)
{
    if (Authentication.CheckSession(Session))
    {
        var wcfmonitoring = new WCFMonitoring.MonitoringDatabaseClient();
        try
        {
            bool timeout = false;
            DateTime start = DateTime.Now;
            //loop as long as the time isn't reached (600 seconds)
            while (!timeout)
            {
                if (wcfmonitoring.CheckForEquipmentUpdate(Authentication.GetSessionID(Session), Authentication.GetPTO(Session), ID))
                {
                    wcfmonitoring.Close();
                    //sleep before returning true, this is set so the importer can finish multiple files without the client refreshing on the first one
                    Thread.Sleep(2000);
                    return true;
                }
                else
                {
                    //sleep for 10 seconds before trying again
                    Thread.Sleep(10000);
                    //if the elapsed time is more than 10 minutes return false
                    if (start < DateTime.Now.AddSeconds(-600))
                    {
                        wcfmonitoring.Close();
                        return false;
                    }
                }
            }
        }
        catch
        {
            wcfmonitoring.Abort();
        }
    }
    //return false in case of error
    return false;
}