texts:
Here was my first, simple C fizzbuzz:

#include <stdio.h>
void main() {
  for (int n = 1; n <= 100; ++n) {
    if (n % 3 == 0) printf("%s", "fizz");
    if (n % 5 == 0) printf("%s", "buzz");
    if ((n % 3 != 0) && (n % 5 != 0)) printf("%d", n);
    printf("\n");
  }
}

I was messing around, trying to separate the transformation logic from the looping logic. As a whole, I don't think that my second Buffer-based solution is necessarily "better" as a FizzBuzz solution, but I did like the way that I dealt with a limited-purpose character buffer.

Thoughts on the second solution?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

#define BUFF_SZ 9

typedef unsigned int u32;
typedef int i32;

/// A string buffer with a notion of its own size.
typedef struct Buffer {
  char *s;
  u32 sz;
  char *ins_ptr;
} Buffer;

/// Returns the content of the buffer.
const char *Buffer_content(Buffer *);

/// Clears contents of the buffer.
void Buffer_clear(Buffer *);

/// Appends a string S to the end of the buffer.
void Buffer_append_str(Buffer *, char *);

/// Appends the string representation of an integer to the end of the buffer.
void Buffer_append_i32(Buffer *, i32);

/// Returns 1 if the buffer has space for a certain number of chars, else 0.
u32 Buffer_has_space(Buffer *, u32);

/* HIGH LEVEL CODE */

/// Writes a number's fizzbuzz transformation into a Buffer.
void write_fizzbuzz_transformation(i32 n, Buffer *buff) {
  Buffer_clear(buff);
  if (n % 3 == 0) Buffer_append_str(buff, "fizz");
  if (n % 5 == 0) Buffer_append_str(buff, "buzz");
  if (*Buffer_content(buff) == '\0') Buffer_append_i32(buff, n);
}

void main() {
  // setup the string buffer (stack allocated)
  char internal_buff[BUFF_SZ];
  Buffer buff;
  buff.s = internal_buff;
  buff.sz = BUFF_SZ;

  for (i32 i = 1; i <= 100; ++i) {
    write_fizzbuzz_transformation(i, &buff);
    printf("%d -> %s\n", i, Buffer_content(&buff));
  }
}

/* DETAILS -- IMPLEMENTATION CODE */

u32 Buffer_has_space(Buffer *buff, u32 requested_sz) {
  u32 available_sz = buff->sz - (buff->ins_ptr - buff->s) - 1;
  return (available_sz >= requested_sz);
}

void Buffer_append_str(Buffer *buff, char* s) {
  u32 needed_sz = strlen(s);
  assert(Buffer_has_space(buff, needed_sz));
  strcpy(buff->ins_ptr, s);
  buff->ins_ptr += needed_sz;
}

void Buffer_append_i32(Buffer *buff, i32 n) {
  i32 original = n;
  u32 needed_sz = 0;
  if (n < 1) ++needed_sz;
  while (n) {
    n /= 10;
    ++needed_sz;
  }
  assert(Buffer_has_space(buff, needed_sz));
  sprintf(buff->ins_ptr, "%d", original);
  buff->ins_ptr += needed_sz;
}

void Buffer_clear(Buffer *buff) {
  buff->ins_ptr = buff->s;
  *(buff->ins_ptr) = '\0';
}

const char *Buffer_content(Buffer *buff) {
  return buff->s;
}


texts:
I've just replaced my bash script with a Python script, and this is my first script where I used class.

Please review and give me suggestions.

#!/usr/bin/env python

# This Script will compress One day old file means yesterday files

from __future__ import print_function
import os
import sys
import time
import glob
import subprocess
from datetime import datetime

nday = 1        # set how many days old file
ftype = "*.log"     # set file type which should be compressed
lookinto = "/var/log/"  # path of files

class CheckFile(object):
    'Operation on file like get size,file time etc..'
    def __init__(self,fname):
        self.fname = fname
    def size(self):
        'print size in bytes MB'
        num = os.path.getsize(self.fname)
        for s in [ 'bytes','KB','MB','GB','TB' ]:
            if num < 1024.0:
                return "%3.1f %s" % (num,s)
            num /= 1024.0
    def date(self):
        'print file date'
        self.unix_time = os.path.getmtime(self.fname)
        self.file_date = datetime.fromtimestamp(self.unix_time)
        return self.file_date.strftime('%d/%m/%y')
    def days_of_days_old(self):
        'print how much file is old from today'
        self.date()
        days = (datetime.today() - self.file_date).days
        return days

def compresse_file(file):
    print("Compressing...")
    cmd = "gzip -v " + file
    os.system(cmd)

if __name__ == '__main__':
    os.chdir(lookinto)
    print('{0:10}{1:10}{2:10}'.format("Size","Date","File Name"))
    print('{0:10}{1:10}{2:10}'.format("-----","------","---------"))
    for file in glob.glob(ftype):
        f = CheckFile(file)
        if f.days_of_days_old() == nday:
            print('{0:10}{1:10}{2:10}'.format(f.size(),f.date(),f.fname))
            compresse_file(file)
            print("file status after compressesion")
            f = CheckFile(file + ".gz")
            print('{0:10}{1:10}{2:10}'.format(f.size(),f.date(),f.fname))
            print()


texts:
I've been struggling with python OOP. I've gone through the basics but I'm struggling with implementing them. So I've decided to create something small everyday while in quarantine to get more comfortable with OOP.

My code simulates a simple coffee machine that makes 4 types of coffee.

This is the first one. What do you think of it? How can I improve it?

import os
class Coffee:
    """ A generic coffee machine """

    def __init__(self, coffee, cups, water, milk, sugar):
        self.coffee = coffee
        self.cups = cups
        self.water = water
        self.milk = milk
        self.sugar = sugar

    def coffee_maker(self):
        preferred_coffee = type_of_coffee()
        sugar_intake = some_sugar()
        if sugar_intake in ("Y", "y"):
                self.sugar -= 5

        if preferred_coffee == 1:
            print("Espresso coming up!\n")
            print("1 Espresso delivered!")

        elif preferred_coffee == 2:
            print("Filtered Coffee coming up!\n")
            print("1 Filtered Coffee delivered!")

        elif preferred_coffee == 3:
            print("Latte coming up!\n")
            print("1 Latte delivered!")
            self.milk -= 30

        elif preferred_coffee == 4:
            print("Cappuccino coming up!\n")
            print("1 Cappuccino delivered!")
            self.milk -= 30

        self.coffee -= 140
        self.cups -= 1
        self.water -= 120

    def coffee_maker_report(self):  # returns the amount of: coffee, sugar, water, milk, cups left
        return {"Coffee": self.coffee, "Water": self.water, "Milk": self.milk, "Sugar": self.sugar, "Cups": self.cups}

def type_of_coffee():  # this function makes sure the user chooses a their coffee of choice by getting ONLY a valid
    # input
    print("Hi there, what would you like to drink")
    coffee_list = ["1 - Espresso", "2 - Filter", "3 - Cappuccino", "4 - Latte"]

    valid = False
    while not valid:
        try:
            choice = int(input("Enter Choice: "))
            if choice in (1, 2, 3, 4):
                valid = True
            else:
                print("Please enter a valid option.")
        except ValueError:
            print("Please enter a valid option")

    return choice

def some_sugar():

    valid = False

    while not valid:
        try:
            choice = input("Some sugar? ")
            if choice in ("Y", "y", "N", "n"):
                valid = True
            else:
                print("Please enter a valid option")
        except ValueError:
            print("Please enter a valid option")

    return choice

def main():
    os.system("cls")
    new_coffee = Coffee(3500, 25, 3000, 750, 125)  # mg, no., ml, ml, mg
    print(new_coffee.coffee_maker_report())
    new_coffee.coffee_maker()
    print(new_coffee.coffee_maker_report())

if __name__ == '__main__':
    main()


texts: Finding all prime numbers within a range

texts:
I am trying to find all primes less than 2,000,000 and sum them together. My code currently takes 1'36" to run. Is there a faster way to get my solution?

The logic I am following in this code is make a list of all primes I have found. Then check that every odd number less than 2,000,000 is not divisible by any of the primes in my list. If that is the case I am calling the number prime.

package main

import ("fmt"
"time"
)

func find_primes(max int) []int {
    // list of all primes that we find
    var primes []int
    primes = append(primes, 2)

    var is_prime = true
    for i:=3; i<=max; i++ {
        is_prime = false
        // only odds can be prime
        if i%2 != 0 {
            is_prime = true
            // should not be divisible by any previous
            // prime numbers
            for _, x := range primes {
                if i%x == 0 {
                    is_prime = false
                    break
                }
            }
        }
        if is_prime {
            primes = append(primes, i)
        }
    }
    return primes
}

// just sume up all of the primes
func sum_primes(primes []int) int {
    var total int = 0
    for _, x := range primes {
        total = total + x
    }
    return total
}

func main() {
    start := time.Now()
    // find all primes less than 2,000,000
    primes := find_primes(2000000)
    sum := sum_primes(primes)
    fmt.Println(sum)
    t := time.Now()
    elapsed := t.Sub(start)
    fmt.Println(elapsed)
}


texts:
I have two more methods the same as this except that they query a different table. Is there another way to know if the result of the query is null? The hasher.CompareStringToHash() method is not allowed to have a null value.

If it's not null, it proceeds to an else condition, and inside that it checks if the encrypted password and password in the textfield are the same. If it's the same it will go to another else statement.

Is there another way to shorten this code? Keep in mind that I should not have a null value in the hasher.CompareStringToHash(). Or, if possible, restrict calling that method if the result is null and lessen the if statements. How can I make this code cleaner and more efficient?

public void CheckAssistantsPassword()
{
    DbClassesDataContext myDb = new DbClassesDataContext(dbPath);

    var password = (from userAccounts in myDb.Assistants
                    where userAccounts.Ass_UserName== txtUserName.Text
                    select userAccounts.Ass_Password).FirstOrDefault();

    var hasher = new Hasher() { SaltSize = 16 };

    if (password == null)
    {
        MessageBox.Show("Invalid Account");
    }
    else
    {
        bool isOkay = hasher.CompareStringToHash(txtPassword.Text,password);
        if (isOkay)
        {
            MessageBox.Show("You May Now Login");
        }
        else
        {
            MessageBox.Show("INVALID PASSWORD");
        }
    }
}


texts:
I am logging entries into a website form using Spring4 and Java 8 (originally Java 7).  I was using the slf4j logging framework firstly to write to file as a PoC and then directly to db as a mistaken final implementation. Mistaken as it shouldn't talk to the db directly. So I now have a very simple REST API server running with a couple of POST end points.  So far so good.  The basic code is working with no problems.

As this is non core functionality (logging NOT auditing) I thought I should make this call asynchronous so that if there are any issues this peripheral functionality won't degrade core functionality so I thought I should make the call asynchronously.

I have a created a Service class which is injected into the controller classes and has methods like this:

public void postLog (EntryItemLog logItem){
    String uri = REST_API_ENDPOINT;

    try {
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<EntryItemLog> response = restTemplate.postForEntity(uri, logItem, EntryItemLog class);

        LOGGER.debug("Returned logging POST with status  " + response.getStatusCode());

    }catch (Exception ex) {
        LOGGER.debug("Error Calling " + uri + ": " + ex.getMessage());
    }
}

and I am calling the function in this way:

 @RequestMapping(value = Controller.RESOURCE_NAME, method = RequestMethod.GET)
 public ModelAndView controlMethod(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute(REQUEST_MODEL_NAME) RequestBean requestBean, Model model) {
//some logging & set up

new Thread(() -> {
               dbRESTClientService.postLog(searchRequestBean.getTerm(), "searchProject", "WEB", (request.getHeader("X-FORWARDED-FOR") == null) ? request.getRemoteAddr() : request.getHeader("X-FORWARDED-FOR"));
            }).start();

//perform main functionality

I imagine this is very basic and unsophisticated for many people on this site, but is it broadly acceptable?  Can anyone offer me any advice on doing it in a better way?

I guess I have 3 queries myself but any other (broadly constructive) criticism  would gratefully accepted as the is a fairly new area to me:

Starting a new thread seems like quite an overhead for this task but I don't see an alternative (other than using a 3rd party tool like Jersey which will presumably do the same thing anyway?)
Should I be doing something more sophisticated than creating a local RestTemplate each time?
Is it generally the right approach anyway (it feels over simplistic)?


texts: Spiral Scanning for matrix using recursion

texts:
I have written code for scanning an N x M matrix in spiral order using a recursive function.

It uses 5 parameters - including 2 extra variables:

call to keep track of the no. of current call
counter to keep track of no. of elements already printed

Example:

For matrix:

1 2 3
4 5 6
7 8 9

For call = 0:
Output: 1 2 3 6 9 8 7 4 counter = 8

For call = 1:
Output: 5 counter = 9

Can the code be improved so that it uses fewer no. of variables and is more efficient?

#include <stdio.h>
#include <stdlib.h>
void spiralscan(int a[][20],int n,int m,int call,int counter)
{
    int i,j;
    if(counter>=n*m)
        return;
    //scan top
    //if(m>call)
    {   printf("\ntop\n");
        for(j=call;j<m-call;j++)
        {printf(" %d ",a[call][j]);
        counter++;
        }
    }
        if(counter>=n*m)
        return;
    //scan right
   // if(n-call>0)
    {   printf("\nright\n");
        for(i=call+1;i<n-call;i++)
        {printf(" %d ",a[i][m-call-1]);
        counter++;
        }
    }
        if(counter>=n*m)
        return;

    //scan bottom
 //   if(m-call>0)
    {   printf("\nbottom\n");
        for(j=m-2-call;j>=call;j--)
        {printf(" %d ",a[n-1-call][j]);
        counter++;
        }
    }
        if(counter>=n*m)
        return;
    //scan left
   // if(call<n/2)
       {   printf("\nleft\n");
        for(i=n-2-call;i>call;i--)
        {printf(" %d ",a[i][call]);
         counter++;
        }
    }
        if(counter>=n*m)
        return;

    spiralscan(a,n,m,call+1,counter);
}
int main()
{
    int n,m,i,j,a[20][20];
    printf("\t\t\tSpiral Scanning\n\n");
    printf("no. of rows : ");
    scanf("%d",&n);
    printf("\nno. of columns : ");
    scanf("%d",&m);
    printf("\nEnter matrix elements : \n");
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
             scanf("%d",&a[i][j]);
    }
    printf("\n\n\t\tScanning Spirally\n\n");
    spiralscan(a,n,m,0,0);
    return 0;
}


texts:
I'm working on a few JavaScript functions for myself that I hope come in handy sometime.  The first I wrote was a Capitalization function (yeah i know, real original. whatever)
I was just wondering if

I'm doing anything incredibly stupid
There's anyway to make the code below more concise (like cool JS concision features i don't know about, tightening down on program flow, etc.)
There's anything else cool i can do

Code:

String.prototype.capitalize = function(everyWord) {
    var words = this.split(" ");
    if (everyWord == true) {
        for (i = 0; i < words.length; i++) {
            words[i] = cap(words[i]);
        }
    }
    else {
        words[0] = cap(words[0]);
    }
    return words.join(" ");

    function cap(word) {
        return word.charAt(0).toUpperCase() + word.slice(1);
    }
};
var x = "abraham lincoln yada yada";
x = x.capitalize();
alert(x);
x = x.capitalize(true);
alert(x);

Thanks!
http://jsfiddle.net/thomas4g/LpwRn/31/


texts:
In my project I have a chain of Fragments where each one gets a bitmap, manipulates it, then sends it to another fragment for more processing.

My fragment chain looks like this:

CaptureFragment -> RotateFragment -> CropFragment -> ...

And here's some of the code:

abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel>
(private val c1: Class<InVM>, private val c2: Class<OutVM>) : BaseFragment() {
    protected lateinit var inViewModel: InVM
    protected lateinit var outViewModel: OutVM
    fun getInBitmap(): Bitmap = inViewModel.bitmap
    fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        inViewModel = getViewModel(c1)
        outViewModel = getViewModel(c2)
    }
}
sealed class BaseFragment : Fragment() {
   protected fun <T: ViewModel>getViewModel(c: Class<T>): T
            = ViewModelProviders.of(activity)[c]
}

It leads to fairly awkward code like this since we can't have reified generics in classes:

private typealias RVM = RotateViewModel
private typealias CVM = CropViewModel
class CropFragment: BaseFragmentInOut<CVM, RVM>
(CVM::class.java, RVM::class.java) {
...
}

But the alternative isn't that great either, as it leads to a lot of boilerplate code:

class CropFragment: BaseFragment() {
    private lateinit var inViewModel: RotateViewModel
    private lateinit var outViewModel: CropViewModel
    fun getInBitmap(): Bitmap = inViewModel.bitmap
    fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        inViewModel = getViewModel()
        outViewModel = getViewModel()
    }
}

How good of a practice is my approach and are there other better ways to do this?


texts: C++ Beginner. Project Euler 14: Longest Collatz sequence under one million

texts:
Hello, I'm a C++ beginner, learning the language while trying to code Project Euler problems. I'm having trouble coding problem 14, which I'll copy here:

  The following iterative sequence is defined for the set of positive
  integers:

  n → n/2 (n is even) n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1)
  contains 10 terms. Although it has not been proved yet (Collatz
  Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

My program runs fast, and works for smaller values of n, but for some reason I don't understand, it doesn't give the right solution for n = 1 million. I think the mod function % might be the issue in some way for large numbers, or the way i defined the variables, but I can't get it right.
Would appreciate some help, and thank you for your patience in advance.

I wrote this piece of code for it:

#include <iostream>
#include <cmath>
using namespace std;

double maxvec(int *v,int n){  //gets the max value of a vector
  double elmax;
  elmax=v[0];
  for(int i=1;i<n;i++){
    if(v[i]>elmax) elmax=v[i];
  }
  return elmax;
}

double indice(int *v,int n){  //gets the index corresponding to the max value of a vector
  double elmax=v[0];
  double indice;
  indice=0;
  for(int i=1;i<n;i++){
    if(v[i]>elmax){ elmax=v[i];indice=i; }
  }
  return indice;
}

int main(){

  const int n = 1000000;

  long x0;

  int ind;

  int k[n-2];     //vector that contains how many elements are there in the sequence for each initial   number

  for ( int i=2; i<n; i++){   //the numbers we are gonna run through the Collatz sequence (in this case the problem asks for n=1000000)

    k[i-2]=0;

    x0=i;

      while (x0!=1){          //using the property that all Collatz sequences end in 1

      x0=x0%2 + x0/2*((x0+1)%2)+ 3*x0*(x0%2); //the algorithm for the collatz sequence

      k[i-2] = k[i-2]+1;  //for the final iteration of the while loop, the (i-2)th component contains the information of the number of elements that corresponds to the initial value i

       }

  }

  cout<<maxvec(k,n-2)<<endl; //shows the maximum value of array k

  cout<<indice(k,n-2)+2<<endl; //shows the initial value for the max value of k, which is the solution to the problem

}


texts:
Firstly, I got the solution for this question in CodeChef, but I noticed one thing which still confuses me. This was the code which was accepted as correct.

#include<iostream>
using namespace std;
int main(){
    int testCases,count=0;
    cin>>testCases;
    unsigned long int a,b;
    while(testCases--){
            count=0;
            cin>>a>>b;
            while(a&(a-1)){
                    a>>=1;
                    count++;
            }
            while(a>b){
                    a>>=1;
                    count++;
            }
            while(a != b){
                    a<<=1;
                    count++;
            }

            cout<<count<<"\n";
    }
   return 0;
}

And this is the solution which was getting TLE:

 #include<iostream>
 using namespace std;
 int main(){
    int testCases,count=0;
    cin>>testCases;
    unsigned long int a,b;
    while(testCases--){
            count=0;
            cin>>a>>b;
            while(a&(a-1) != 0 || a>b){
                    a>>=1;
                    count++;
            }
            while(a != b){
                    a<<=1;
                    count++;
            }

            cout<<count<<"\n";
    }
 return 0;
}

Both the solutions are almost same. What I have just modified in the first is that I have put a separate while loop

for checking if a is the power of 2
for making value of a less than b

Now what I understood was that keeping separate while loop saves me time by NOT having to do two conditions check for each iteration.

Am I correct with this understanding, or I am missing something. If I am correct, is it good practice (as per optimization) to write separate loops.

I would like to know how I can write this code in a better way or what other good practice I can follow.


texts: TCP client and server supporting six simple commands

texts:
For a class, I was given an assignment to code a simple TCP connection between a server and a client. Once the TCP handshake is done, the client sends inquiries to the server. It's a 2 second conversation, if that.
I need some feedback on my code. Please keep in mind that I am new to Python. The prof kinda threw the class to the wolves on this.

This is the server code:

import socket
import time
import sys
#from thread import *

def Main():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = socket.gethostname()
        port = 8008

        s.bind((host, port))

        print ("Port, that's a wine right? " + str(port))

        s.listen(1)
        c, addr = s.accept()
        print ("200 SRP version 1.0 ready")
        print ("Connection from: " + str(addr))
        while True:
            data = c.recv(1024)
            data = str(data).upper()
            print ("sending: " + str(data))
            c.send(data)
            print ("from connected user: " + str(data))
            print ("Welcome, would you like a jelly baby?")

            if not data:
                        break
            if True:
                if data.startswith('HELO'):
                    try:
                        c.sendall("210 HELO " +  host + " This is Dalek High Command. You will obey all orders without question!")
                    except:
                        c.sendall("510 You are unauthorized! You will be exterminated!")
                    break
                elif data.startswith('REQTIME'):
                    try:
                        c.sendall ("220 I obey!  The time is " + time.strftime("%H%:M%:S"))
                    except:
                        c.sendall ("520 The time is unavailable!  Exterminate!")
                        break
                elif data.startswith('REQDATE'):
                        try:
                        c.sendall ("230 I obey!  The date is " + time.strftime("%Y/%m/%d"))
                    except:
                        c.sendall ("530 The date is unavailable!  Exterminate!")
                        break
                elif data.startswith('ECHO'):
                    try:
                        data = str(data).upper()
                        c.sendall ("240 Data received! " + data)
                    except:
                        c.sendall ("540 ECHO!  I cannot obey!  Assist!  Assist!  Cannot comply!  Exterminate!")
                        break
                elif data.startswith('REQIP'):
                    try:
                        c.sendall ("250 IP has been identified! " + host)
                    except:
                        c.sendall ("550 Alert!  I cannot obey! Your IP cannot be retrieved!")
                        break
                elif data.startswith('BYE'):
                    try:
                        c.sendall ("600 Alonzy! Bowties are cool!  See you later!")
                    except:
                        break
sys.exit()
c.close()

This is the client:

import socket

def Main():
        host = ''
        port = 8008

        s = socket.socket()
        s.connect((host, port))

        message = s.recv(1024)
        print('Received from server: ' + str(data))

        for x in range(0, 5):
            if x == 0:
                data = 'helo'
                s.send(data)
            elif x == 1:
                data = 'reqtime'
            elif x == 2:
                data = 'reqdate'
            elif x == 3:
                data = 'echo'
            elif x == 4:
                data = 'reqid'
            elif x == 5:
                data = 'bye'

        s.send(data)
        print(str(data))
        x = x + 1


texts:
Below is my solution to finding the minimum product sub-interval. It passed 8/12 or so test cases, but the other test cases timed out if they hadn't finished within 2 seconds. When I compile this code as Release, optimized, and to target x64, it takes about 7.6 seconds to finish on large input sizes, such as  this testcase. (I'm running this on Windows 8.1 with CPU: AMD FX-8320 3.49 GHz).

using System;
using System.Collections.Generic;
using System.Linq;

class SubInterval : IComparable<SubInterval> {
    public int start;
    public int end;

    public int Length { get { return start == 0 && end == 0? 0 : end - start + 1; } }

    public int CompareTo(SubInterval other) {
        if (this.Length > other.Length)
            return 1;
        else if (this.Length < other.Length)
            return -1;
        else if (this.Length == other.Length)
            return this.start < other.start ? 1 : -1;
        else
            return 0;
    }
}

class Solution {
    static void Main(string[] args) {
        int N, Q;
        int[] a, q;
        int[][] linesQ;

        //read from STDIN, initialize variables...

        System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
        for (int j = 0; j < Q; j++) {
            q = linesQ[j];
            if (q[0] == 2)
                a[q[1]] = q[2];
            else
                getMinSubInterval(a, q[1], q[2]);
        }
        watch.Stop();
        long ms = watch.ElapsedMilliseconds;
}

static void getMinSubInterval(int[] a, int i, int j) {

    int min = a[i];
    List<int> lookup = new List<int>() { i };
    for (int k = i; k <= j; k++) {
        if (a[k] == 0) {
            min = 0;
            break;
        }
        if (a[k] < min) {
            min = a[k];
            lookup = new List<int>() { k };
        }
        else if (a[k] == min && k > i) {
            lookup.Add(k);
        }
    }

    if (min == 0) {
        SubInterval zero = new SubInterval { start = i, end = j };
        Console.WriteLine("0 {0} {1}", zero.start, zero.end);
    }
    else if (min == 1 && lookup.Count > 1) {
        SubInterval longest = getLongestSubInterval1s(lookup, a);
        Console.WriteLine("1 {0} {1}", longest.start, longest.end);
    }
    else  {
        int idxMin = lookup[0];
        SubInterval sub = new SubInterval { start = idxMin, end = idxMin };
        Console.WriteLine("{2} {0} {1}", sub.start, sub.end, a[idxMin]);
    }

}

static SubInterval getLongestSubInterval1s(List<int> samesLookup, int[] a) {
    List<SubInterval> list = new List<SubInterval>();
    SubInterval sub;
    for (int k = 0, ikj = 0; k < samesLookup.Count; k++, ikj++) {

        if (k == 0 || !(a[samesLookup[k]] == a[ikj])) {
            sub = new SubInterval { start = samesLookup[k], end = samesLookup[k] };
            ikj = sub.start;
            list.Add(sub);
            continue;
        }
        (list[list.Count - 1]).end = samesLookup[k];
    }

    return list.Max<SubInterval>();
}

How can this code be improved upon so that it runs in \$ O(n \log(n)) \$ time, or what constant-time improvements can be made?


texts: Is there a way to optimise my Perlin noise?

texts:
I just started using Perlin noise a few days ago, and the results look quite good. But it takes over 3 seconds to calculate and draw a 1024x1024 bitmap of said noise. I use an array of 1024x1024 to store int32s ranging from -1 to 1.

Please note that the variable tileSize equals 1024 / resolutieX. This is in case I want to use a lower resolution Perlin noise.

 private void button1_Click(object sender, EventArgs e)
    {
        sw.Start();
        LibNoise.Perlin perlinMap = new LibNoise.Perlin();
        perlinMap.Lacunarity = lacunarity + 0.01d;
        perlinMap.NoiseQuality = LibNoise.NoiseQuality.High;
        perlinMap.OctaveCount = octaveCount;
        perlinMap.Persistence = persistence;
        perlinMap.Frequency = frequency;
        perlinMap.Seed = 1024;

        if (radioButton1.Checked)
            perlinMap.NoiseQuality = LibNoise.NoiseQuality.Low;
        else if (radioButton2.Checked)
            perlinMap.NoiseQuality = LibNoise.NoiseQuality.Standard;
        else if (radioButton3.Checked)
            perlinMap.NoiseQuality = LibNoise.NoiseQuality.High;

        double sample = trackBar6.Value * 10;

        double[,] perlinArray = new double[resolutieX, resolutieY];
        for (int x = 0; x < resolutieX; x++)
        {
            for (int y = 0; y < resolutieY; y++)
            {
                perlinArray[x, y] = perlinMap.GetValue(x / sample, y / sample, 1d);
            }
        }
        draw(perlinArray);
        textBox12.Text = sw.ElapsedMilliseconds.ToString() + "ms";
        sw.Reset();
    }

public void draw(double[,] array)
    {
        Bitmap afbeelding = new Bitmap(1024, 1024);
        Color color;
        int tileSize = 1024 / resolutieY;
        for (int y = 1; y < resolutieY; y++)
        {
            for (int x = 1; x < resolutieX; x++)
            {
                if (array[x, y] <= -0.2)
                    color = Color.DarkBlue;
                if (array[x, y] <= 0)
                    color = Color.DarkBlue;
                else if (array[x, y] <= 0.1)
                    color = Color.Blue;
                else if (array[x, y] <= 0.2)
                    color = Color.Beige;
                else if (array[x, y] <= 0.22)
                    color = Color.LightGreen;
                else if (array[x, y] <= 0.40)
                    color = Color.Green;
                else if (array[x, y] <= 0.75)
                    color = Color.DarkGreen;
                else if (array[x, y] <= 0.8)
                    color = Color.LightSlateGray;
                else if (array[x, y] <= 0.9)
                    color = Color.Gray;
                else if (array[x, y] <= 1)
                    color = Color.DarkSlateGray;
                else
                    color = Color.DarkSlateGray;

                //  color = Color.FromArgb(255);

                for (int i = 0; i < tileSize; i++)
                {
                    for (int j = 0; j < tileSize; j++)
                    {
                        afbeelding.SetPixel(((x - 1) * tileSize) + i, ((y - 1) * tileSize) + j, color);
                    }
                }

            }
        }

        pictureBox1.Image = afbeelding;
    }

Should I start using Simplex noise? Or am I just missing something obvious here?


texts: Find all words in a dictionary that can be made with a string of characters (Recursion/Binary Search)

texts:
I'm working on an algorithm that could take in a string of 20 random characters, and display to the user every word in a dictionary that can be successfully made with those letters, regardless of length. If the string is "made", it would return "mad", "made", etc.

However, the execution time is extremely poor with my current method. I've been recommended to give the Trie structure a shot. But seeing how Java doesn't have it built in, I wanted to see if there's a better approach to this algorithm, or if I should look at implementing my own Trie structure.

I currently use a Binary Search implementation to check for prefixes, found through recursion, and see if a certain recursive path should be continued or not.

private ArrayList<String> dict = new ArrayList<>();
private Set<String> possibleWords = new HashSet<>();

private void getAllValidWords(String letterPool, String currWord) {
    //Add to possibleWords when valid word
    if (letterPool.equals("")) {
       // No action to be done.
    } else if(currWord.equals("")){
        //Will run only the initial time the method is called.
        for (int i = 0; i < letterPool.length(); i++) {
            //Get the individual letters that will become the first letter of a word
            String curr = letterPool.substring(i, i+1);
            //Delete the single letter from letterPool
            String newLetterPool = (letterPool.substring(0, i) + letterPool.substring(i+1));
            if(inDict(curr)){
                possibleWords.add(curr);
            }
            boolean prefixInDic = binarySearch(curr);
            if(prefixInDic){
                //If the prefix isn't found, don't continue this recursive path.
                getAllValidWords(newLetterPool, curr);
            }
        }
    } else {
        //Every time we add a letter to currWord, delete from letterPool
        for(int i=0; i<letterPool.length(); i++){
            String curr = currWord + letterPool.substring(i, i+1);
            String newLetterPool = (letterPool.substring(0, i) + letterPool.substring(i+1));
            if(inDict(curr)){
                possibleWords.add(curr);
            }
            boolean prefixInDic = binarySearch(curr);
            if(prefixInDic){
                //If the prefix isn't found, don't continue this recursive path.
                getAllValidWords(newLetterPool, curr);
            }
        }
    }
}

private boolean binarySearch(String word){
    int max = dict.size() - 1;
    int min = 0;
    int currIndex;
    boolean result = false;
    while(min <= max) {
        currIndex = (min + max) / 2;
        if (dict.get(currIndex).startsWith(word)) {
            result = true;
            break;
        } else if (dict.get(currIndex).compareTo(word) < 0) {
            min = currIndex + 1;
        } else if(dict.get(currIndex).compareTo(word) > 0){
            max = currIndex - 1;
        } else {
            result = true;
            break;
        }
    }
    return result;
}


texts: Use of Exception to log execution stack trace

texts:
I've been back and forth with a colleague over the use of Throwable.fillInStackTrace. This Log class is meant to wrap the Simple Logging Facade for Java.

public class Log {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Log.class);

    private String stackTrace(Exception cause) {
        if (cause == null)
            return "";
        StringWriter sw = new StringWriter(1024);
        final PrintWriter pw = new PrintWriter(sw);
        cause.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }

    public void warn(Exception cause, String message) {
        String output = message + "\n" + stackTrace(cause);
        log.warn(output);
    }

    // debug(...), info(...), etc.
}

But it is being used thusly:

new Log()
    .warn((Exception)new RuntimeException().fillInStackTrace(), "I'm warning you.");

When reviewing this, my comments included things like the "Exceptions are exceptional" idiom.

But when I mentioned that creating a stack trace is an expensive operation and should be avoided, I was told that this used to be true in the past [e.g. with JVM implementations] but is now longer true [i.e. This has been fixed/optimized].

I was not aware of this development, so I checked around and most of the SO questions seem to indicate that making a stack trace is expensive.

Does this code seem reasonable? Would you consider this bad practice?


texts:
Given Input "hello my name is john"
Wrap to character #: 4
Output:
hello\nmyname\nisjohn\n

If a word would be cut in half by the wrap, fit the whole word in the row.
-(NSString *)wrappedColumn:(NSString )words wrappedLimit:(NSInteger *)maxWrap
{
NSArray *tempArray = [words compoentsSeperatedByString:@" "];
if (tempArray count == 0) {
    return @"";

if ([words.length <= maxWrap) {
   return words;

NSMutableString *outputString = [[NSMutableString alloc] init];
NSInteger *currentLength = 0;
for (NSString *word in tempArray){
   if ((currentLength + word.length) < maxWrap {
                [outputString appendString:word];
                currentLength = currentLength + word.length
    } else {
       [outputString appendString:@"\n"];
       currentLength = 0;
      }

return outputString;
}

Any critique would be amazing!


texts: Doing a roll back with multiple MySQLI prepared statement

texts:
This is my code for doing a roll back with multiple MySQLI prepared statement.

I want to know if anything is wrong with the code.

 $newRegistrationDataArray = array(
    "date" => $date,
    "name" => $name,
    "address" => $address,
    "country" => $country,
    "occupation" => $occupation,
    "emailAddress" => $emailAddress,
    "memberID" => $memberID,
    "usename" => $usename,
    "password" => $password,
    "salt" => $salt,
    "secretQuestion" => $secretQuestion,
    "secretAnswer" => $secretAnswer,
    "transactionCode" => $transactionCode,
    "perfectMoneyAccount" => $perfectMoneyAccount,
    "egoPayAccount" => $egoPayAccount,
    "payeerAccount" => $payeerAccount,
    "okPayAccount" => $okPayAccount,
    "bitcoinAccount" => $bitcoinAccount,
    "upline" => $upline,
    "userRegistrationIp" => $userRegistrationIp,
    "status" => $status
);

public function CreateNewAccount(&$newRegistrationDataArray){ ///note the &

    /* set autocommit to off */
    $this->dbConnection->autocommit(FALSE);

    $stmt1=$this->dbConnection->prepare("INSERT INTO `members` (date,name,address,country,occupation,emailAddress,memberID,usename,password,salt,secretQuestion,secretAnswer,transactionCode,perfectMoneyAccount,egoPayAccount,payeerAccount,okPayAccount,bitcoinAccount,upline,userRegistrationIp,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt2=$this->dbConnection->prepare("INSERT INTO `membertotalfinancialstatus` (memberId) VALUES (?)");

    /* variable needed */
    $memberId = $this->generateMemberId(); // a private function that generate member id
    $date = $newRegistrationDataArray['date'];
    $name = $newRegistrationDataArray['name'];
    $address = $newRegistrationDataArray['address'];
    $country = $newRegistrationDataArray['country'];
    $occupation = $newRegistrationDataArray['occupation'];
    $emailAddress = $newRegistrationDataArray['emailAddress'];
    $usename = $newRegistrationDataArray['usename'];
    $password = $newRegistrationDataArray['password'];
    $salt = $newRegistrationDataArray['salt'];
    $secretQuestion = $newRegistrationDataArray['secretQuestion'];
    $secretAnswer = $newRegistrationDataArray['secretAnswer'];
    $transactionCode = $newRegistrationDataArray['transactionCode'];
    $perfectMoneyAccount = $newRegistrationDataArray['perfectMoneyAccount'];
    $egoPayAccount = $newRegistrationDataArray['egoPayAccount'];
    $payeerAccount = $newRegistrationDataArray['payeerAccount'];
    $okPayAccount = $newRegistrationDataArray['okPayAccount'];
    $bitcoinAccount = $newRegistrationDataArray['bitcoinAccount'];
    $upline = $newRegistrationDataArray['upline'];
    $userRegistrationIp = $newRegistrationDataArray['userRegistrationIp'];
    $status = $newRegistrationDataArray['status'];
    /* variable needed */

    $stmt1->bind_param('sssssssssssssssssssss',$date,$name,$address,$country,$occupation,$emailAddress,$memberID,$usename,$password,$salt,$secretQuestion,$secretAnswer,$transactionCode,$perfectMoneyAccount,$egoPayAccount,$payeerAccount,$okPayAccount,$bitcoinAccount,$upline,$userRegistrationIp,$status);
    $stmt2->bind_param('s',$memberId);

    try
    {
        if( ($stmt1->execute() == false) OR ($stmt2->execute() == false)){

            /// close statement, roll back and throw an exception
            $stmt1->close();
            $stmt2->close();

            $this->dbConnection->rollback();
            throw new Exception("AN INTERNAL ERROR HAS OCCURED. TRY AGAIN LATER.");
        }
    }
    catch(Exception $e)
    {
        $error=$e->getMessage();
        throw new Exception($error);
    }

    $this->closeDBConn;
}


texts: ggplot2: a script for stacked and a line chart

texts:
So far I was successful to get what I need using below mentioned script, but I'm sure my script is far from being perfect (if it is possible at all). So, I'd greatly appreciate your comments on how would it have been done differently in order to improve it.

p6_ch1 <- read.xlsx("BEO_charts.xlsx", sheet = 7, startRow = 2, colNames = T, rowNames = F, detectDates = T, skipEmptyCols = T, skipEmptyRows = T)

p6_ch1$date <- as.Date(seq(as.Date("2009/1/1"), as.Date("2016/07/1")-1, by = "quarter"))
p6_ch1$date <- as.yearqtr(as.Date(p6_ch1$date, format = "Q%q %Y"))

p6_ch1_stack <- subset.data.frame (p6_ch1, select = c(1,3:5,7:9), p6_ch1$date >= "2013 Q1")
p6_ch1_line <- subset(p6_ch1, select = c(1,10), p6_ch1$date >= "2013 Q1")
p6_ch1_stack_melt <- melt(p6_ch1_stack, id.vars = "date", measure.vars = c(2:7))
p6_ch1_line_melt <- melt(p6_ch1_line, id.vars = "date")

p6.1 <- ggplot(data = p6_ch1_stack_melt, aes (x = date, y = value)) +
scale_x_yearqtr(breaks = seq(from = min(p6_ch1_stack$date, na.rm = T), to = max(p6_ch1_stack$date, na.rm = T), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(limits = c(-35,35), breaks = seq(-35,35,5)) +
  xlab ("") +
  ylab ("") +

  geom_bar(data = p6_ch1_stack_melt,
        aes(
          group = variable,
          fill=variable),
          stat = 'identity') +

  scale_fill_manual(
    guide = "legend",
    name = NULL,
    breaks= c(
      "tax_inc",
      "ved_inc",
      "oth_inc",
      "current_exp",
      "debt_service",
      "capex"),
    labels= c(
      "Налоговые доходы*",
      "Доходы от ВЭД",
      "Прочие доходы",
      "Текущие расходы**",
      "Обслуживание госдолга",
      "Капитальные расходы"),
    values = c(
      "#88CCEE",
      "#44AA99",
      "#117733",
      "#DDCC77",
      "#CC6677",
      "#AA4499"))

p6.1 <- p6.1 + geom_hline(aes(yintercept = 0),colour="#ABABAB")
p6.1 <- p6.1 +
  geom_line(data = p6_ch1_line_melt, aes(x = date, y = value, colour = variable), size = 1) +
  geom_point(data = p6_ch1_line_melt, aes(x = date, y = value, colour = variable), size = 1) +

  scale_colour_manual(
    guide = "legend",
    name = NULL,
    breaks = c("balance"),
    labels = c("Сальдо"),
    values = c("#332288", "#332288")) +

    theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "black"),
        #panel.grid.minor.x = element_line(colour = "#EDEDED", linetype = 2),
        panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .3),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "#EDEDED"),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        axis.line.y = element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(.3, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-9,1,1,1), "mm"),
        legend.background = element_rect(fill = "transparent", colour = NA),
        plot.margin = unit (c(1,1,0,-4), "mm"))

p6.1

CairoPDF("plot6.1.pdf", width=5.23622, height=2.83465)
plot(p6.1)
dev.off()

The script gives me a chart I need:


texts:
What kind of algorithm wold solve the following problem from https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=junar ?

  I have been given a positive integer n. Take the n first positive
  integers 1 to n and permute those to some order. At the beginning you
  can swap the position of two numbers. Each round you go through the
  sequence and your aim is to collect numbers from ascending order. If
  the original permutation is given, determine how many ways one can
  select two numbers from the original sequence to be swapped if one
  wants to collect all number with minimum number of rounds and how many
  rounds it would take to collect numbers in ascending order.

For example if the numbers are at the beginning 3, 1, 5, 4, 2, then you collect at the first round numbers 1 and 2, on the second round 3 and 4 and on the third round 5. So totally three rounds. But you can make a swap to the original sequence to make the following sequences:

3, 4, 5, 1, 2
3, 1, 4, 5, 2
3, 1, 2, 4, 5

and all of them can be collected in two rounds.

But what if n is larger than five, say about 100000? The cases are listed in https://www.ohjelmointiputka.net/tiedostot/junar.zip . Each file contains first the number of numbers and the next lines gives the numbers in some order.

Express the solution of each file as form

a b c

where a is the number of numbers to be collected, b is the smallest number of rounds that takes to collect all numbers if you swap at the beginning one pair of numbers, and c denotes how many ways you can swap at the beginning two numbers so that you can collect numbers in ascending order with minimum number of rounds. So the answer to the example 3, 1, 5, 4, 2 should be 5 2 3.

My brute force solution is as follows. First download the file in the link above to your computer and unzip it.

def swap(A,i,j):
    temp = A[i]
    A[i] = A[j]
    A[j] = temp
    return A

def is_same_round(tables,i,j):
    return tables.index(i) < tables.index(j)

def solve(file):
    tables = [line.strip('\n') for line in open(file)]
    for i in range(len(tables)):
        tables[i]=int(tables[i][0:len(tables[i])-1])
    tables = tables[1:len(tables)]
    roundnumbers = []
    for i in range(len(tables)):
        for j in range(i+1,len(tables)):
            rounds = 1
            tables = swap(tables,i,j)
            for luku in range(1,len(tables)):
                if not is_same_round(tables,luku,luku+1):
                    rounds += 1
            roundnumbers.append(rounds)
            tables = swap(tables,i,j)
    result = ""
    result += str(len(tables))
    result += " "
    result += str(min(roundnumbers))
    result += " "
    result += str(roundnumbers.count(min(roundnumbers)))
    print(result)

for i in range(1,10):
    file = 'junar'+str(i)+'.in'
    solve(file)


texts: Speed up computation on lists of lists in R (scalability issues)

texts:
My goal is to take a source list of vectors and apply a mapping to each vector. The mapping creates a list of lists. When the vector size in each list element is large (~20000), and the number of elements in the source list is large (~5000), my program does not seem to be efficient. How can I optimize my code?

I've tried two things: implementation in Rcpp and mclapply. The Rcpp implementation is comparable as expected, and the mclapply implementation may not be that efficient because I'm running my function in a larger function that is already parallelized over multiple cores.

Basic example

source.list = rep(list(seq(6)),3)
target.list = list(c(1,2),c(3,4),c(5,6))

result = map_partition(source.list,target.list)

> result
[[1]]
[[1]][[1]]
[1] 1 2

[[1]][[2]]
[1] 3 4

[[1]][[3]]
[1] 5 6

[[2]]
[[2]][[1]]
[1] 1 2

[[2]][[2]]
[1] 3 4

[[2]][[3]]
[1] 5 6

[[3]]
[[3]][[1]]
[1] 1 2

[[3]][[2]]
[1] 3 4

[[3]][[3]]
[1] 5 6

R implementation

map.partition.R <- function(invec, partitionlist) {
  lst <- lapply(partitionlist, function(x) invec[invec %in% x])
  return(lst)
}

result = lapply(X=source.list, FUN=map.partition,
                               partitionlist=target.list)


texts: Wrapper for complicated Range manipulation

texts:
I'm playing around with a class module to try to wrap up some complicated(ish) Range manipulation in Excel-VBA.

I might have a situation where I know the red range spans my target (the target is to have it's contents cleared) and all cells below the red range should go. Green areas are cells used that should not be deleted:

Another example: I only know the red cell - and all used cells just to it's right and below it are to be cleared. Again all green cells should be left alone:

Usually the above is done via manipulation by finding extreme cells (rows.count...toLeft etc) or the CurrentRegion property of Range. I've attempted to wrap that functionality into a Class Module:

Class Module Name: TargetRange

Private fCurrentRange As Excel.Range

''::
''::
Public Enum expandDirection
    toTheRight = 1
    fromTheRight = 2
    downwards = 3
    fromSheetBase = 4
End Enum

''::  read/write property - initial range
''::
Public Property Let CurrentRange(ByRef rng As Excel.Range)
    Set fCurrentRange = rng
End Property
Public Property Get CurrentRange() As Excel.Range
    Set CurrentRange = fCurrentRange
End Property

':: Expand
'::   this will need to use an enumerated type as options
'::
Public Sub expand(ByVal aDir As expandDirection)

Dim lstCell As Excel.Range
Dim lstRow As Long
Dim lstCol As Long

Set lstCell = Me.CurrentRange.Cells(Me.CurrentRange.Cells.Count)
lstRow = Me.CurrentRange.Cells(Me.CurrentRange.Cells.Count).Row
lstCol = Me.CurrentRange.Cells(Me.CurrentRange.Cells.Count).Column

If (aDir = downwards) Then

    Dim newLstRow As Long
    'newLstRow = lstCell.End(Excel.xlDown).Row
    newLstRow = Me.CurrentRange.CurrentRegion.Cells(Me.CurrentRange.CurrentRegion.Cells.Count).Row

    Me.CurrentRange = _
        Range( _
            Me.CurrentRange.Cells(1), _
            Me.CurrentRange.Worksheet.Cells( _
                newLstRow, _
                lstCol _
                ) _
            )
End If

If (aDir = toTheRight) Then

    Dim newLstCol As Long
    newLstCol = lstCell.End(Excel.xlToRight).Column

    Me.CurrentRange = _
        Range( _
            Me.CurrentRange.Cells(1), _
            Me.CurrentRange.Worksheet.Cells( _
                lstRow, _
                newLstCol _
                ) _
            )
End If

End Sub

I'm using it like this:

Dim r As TargetRange
Set r = New TargetRange
r.CurrentRange = wb.Sheets("foo").Range("A2")
r.expand downwards
r.expand toTheRight
r.CurrentRange.ClearContents

Questions:

As it stands could the class module be improved?
Are there some obvious methods missing from the class that could be added?
Is the whole thing a waste of time? (am I reinventing the wheel?)


texts:
I've come up with two ways to check to see if array is sorted and return true if it is.

public static boolean checkSortedness(int[] data)
{
    for(int i = 1; i < data.length; i++)
    {
        if(data[i-1] > data[i])
        {
            return false;
        }
    }
    return true;
}

I've also seen the i start at 0 and compare the next element instead of the previous. The other way which involves another variable is

public static boolean isSorted(int[] data)
{
     int previous = data[0];
     for(int i = 1; i < data.length; i++)
     {
         if(previous > data[i])
             return false;
         previous = data[i];
     }
     return true;
}

Which way is better and are there any alternatives?

What should the array parameter be named? I call it data but I've  considered arr. This class is meant to be fairly generic.


texts: Large table updates using AJAX in Internet Explorer 11

texts:
I have a website which only needs to support IE11. It is a single page application, which has about 200 table rows and each table row has 5 child rows.

There is a pulsing function that updates the table as records come in. Table rows are skipped over if no update comes in.

However, when receiving large updates (which should only occasionally happening), the application will hang as it slowly processes the javascript. I've tried to limit the JavaScript as much as possible, but still have a long running function.

I am a backend developer by nature, and was wondering if anyone had any tips to help support large table Ajax updates for IE since IE so poorly handles JS.

function writeTableLines(tempRows){
    /* This Function takes care of updating the text and coloring of
    required dynamic fields.
    All other values are not dynamically written.
    */
    for( i in tempRows){
   //i is the computer name
        tempValues = tempRows[i];
        // For Row
        selector = "[id='"+i+"']";

        // Network Name
        network_selector = "[id='"+i+"_network']";
        $(network_selector).text(tempValues['network']);

        if (tempValues['network_color']){
            $(network_selector).addClass(tempValues['network_color']);
            $(selector).find('.name').addClass(tempValues['network_color']);
        }else{
            $(network_selector).removeClass('warning');
             $(selector).find('.name').removeClass('warning');
        }

        // Boot Time
        boot_selector = "[id='"+i+"_boot']";
        $(boot_selector).text(tempValues['boot']);
        if (tempValues['boot_color']){
            $(boot_selector).addClass(tempValues['boot_color']);
            $(selector).find('.name').addClass(tempValues['boot_color'])
        }else{
            $(boot_selector).removeClass('issue');
            $(selector).find('.name').removeClass('issue');
        }

        // Last Checked In Timestamp
        check_in_selector = "[id='"+i+"_checked_in']";
        $(check_in_selector).text(tempValues['checked_in']);
        if (tempValues['service_unresponsive']){
            $(check_in_selector).addClass('redline');
            $(selector).find('.name').addClass('redline');
        }else{
            $(check_in_selector).removeClass('redline');
            $(selector).find('.name').removeClass('redline');
        }

        util_selector = $(selector).find('td.util').find('a');
        $(util_selector).text(tempValues['util'])
         if (tempValues['util_class']){
            $(util_selector).addClass(tempValues['util_class']);
        }else{
            $(util_selector).removeClass('redline warning');
        }

        workgroup_selector = $(selector).find('td.workgroup');

        if (($.trim(tempValues['workgroup'])) != $.trim($(workgroup_selector).text())){
            if ((tempValues['workgroup'] != selected) && (selected != 'All')){
                $(workgroup_selector).addClass('warning');
            }else{
                $(workgroup_selector).removeClass('warning');
            }
        }
        $(workgroup_selector).text(tempValues['workgroup'])
        toggle_links(i, tempRows[i]);
        $('#connectionGrid').trigger('updateAll', [false]);
    }
}

This function iterates over only received data. For each row item that was received, update the text of the cell, and add coloring as necessary.

I'm thinking I might just be screwed since its IE, but am open to all suggestions and ideas.

Image of the rows - child rows only available when expanded, but still need updates.


texts: Displaying content based on the current time

texts:
I'm new to PHP and just wrote a bunch of if statements to display content based on the current time.

Is there a better way of writing the following block of code to easily be maintainable? The only thing that changes in each if statement is the if variables, h4 tag and the $rows variable.

<?php

    date_default_timezone_set("Europe/London");

    $currentTime = date('Hi');
    $breakfastStart = "0200";
    $breakfastEnd = "1129";

    $lunchStart = "1130";
    $lunchEnd = "1559";

    $dinnerStart = "1600";
    $dinnerEnd = "2129";

    $lateStart = "2130";
    $lateEnd = "0159";

?>

<?php if ($currentTime >= $breakfastStart && $currentTime <= $breakfastEnd): ?>
        <?php
            $rows = get_field('breakfast', 41190);
            $row_count = count($rows);
            $i = rand(0, $row_count - 1);
        ?>

Breakfast

            <?php echo $rows[ $i ]['dish_name']; ?>

           <?php echo $rows[ $i ]['dish_description'];  ?>

            Served<?php echo $rows[ $i ]['time_served'];  ?>

<?php endif; ?>

<?php if ($currentTime >= $lunchStart && $currentTime <= $lunchEnd): ?>
        <?php
            $rows = get_field('lunch', 41190);
            $row_count = count($rows);
            $i = rand(0, $row_count - 1);
        ?>

Lunch

            <?php echo $rows[ $i ]['dish_name']; ?>

           <?php echo $rows[ $i ]['dish_description'];  ?>

            Served<?php echo $rows[ $i ]['time_served'];  ?>

<?php endif; ?>

<?php if ($currentTime >= $dinnerStart && $currentTime <= $dinnerEnd): ?>
        <?php
            $rows = get_field('dinner', 41190);
            $row_count = count($rows);
            $i = rand(0, $row_count - 1);
        ?>

Dinner

            <?php echo $rows[ $i ]['dish_name']; ?>

           <?php echo $rows[ $i ]['dish_description'];  ?>

            Served<?php echo $rows[ $i ]['time_served'];  ?>

<?php endif; ?>

<?php if ($currentTime <= $lateStart && $currentTime <= $lateEnd): ?>
        <?php
            $rows = get_field('late_night', 41190);
            $row_count = count($rows);
            $i = rand(0, $row_count - 1);
        ?>

Late Night

            <?php echo $rows[ $i ]['dish_name']; ?>

           <?php echo $rows[ $i ]['dish_description'];  ?>

            Served<?php echo $rows[ $i ]['time_served'];  ?>

<?php endif; ?>


texts:
Before I start working on a quite JavaScript heavy application I would like you to review my JS MVC approach.

How can it be improved?
Are there any mistakes/issues I should be aware of?

Since the entire app will have multiple modules I would like to split the code into standalone modules that can be loaded as required (any suggestions how to do this?)

html

<!DOCTYPE html>

            <input type="button" id="button" value="world"/>

project.js

var GLOBAL = {} || GLOBAL;

GLOBAL.SETTINGS = function($) {

    var global = {
        fontColor:"red"
    }

    return {
        MODEL : {
            text : "Text Inside The Containter"
        },

        VIEW : {
            container: $(".container")
        },

        CONTROLLER : {
            style : function() {
                GLOBAL.SETTINGS.VIEW.container.css("color",global.fontColor).append("
" + GLOBAL.SETTINGS.MODEL.text + "
");
            }
        },

        init : function() {
            GLOBAL.SETTINGS.CONTROLLER.style();
        }
    }
}(jQuery);

GLOBAL.SETTINGS.init();

utils.js

GLOBAL.UTILS = function($) {

var text = "SOMETHING"; //local

    return {
        MODEL : {
            text : "World"
        },

        VIEW : {
            button :   $("#button"),
            container: $("#message")
        },

        CONTROLLER : {
            hello : function(msg) {
                GLOBAL.UTILS.VIEW.container.append( "Hello " + GLOBAL.UTILS.MODEL.text + "
" );
            }
        },

        EVENTS : function() {
            GLOBAL.UTILS.VIEW.button.click( function() {
                GLOBAL.UTILS.CONTROLLER.hello();
            });
        },

        init : function() {
            GLOBAL.UTILS.EVENTS();
        }
    }
}(jQuery);

GLOBAL.UTILS.init();


texts: Printing some metrics from a Windows machine

texts:
New to Ruby here. I just made a script that print some metrics from a Windows machine about its disk. The script works fine and as I wanted it to. Now, since I'm new to the ruby and programming world, I'd like to ask you if anyone could help me to make to code look better or if there's other more efficient way I could have wrote it.

require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
require 'socket'

class LogicalDiskMetric < Sensu::Plugin::Metric::CLI::Graphite

  option :scheme,
    :description => "Metric naming scheme, text to prepend to .$parent.$child",
    :long => "--scheme SCHEME",
    :default => "#{Socket.gethostname}"

  #Run a wmic command to get some stats about the disks usage
  def get_logical_disk_metrics
    tmp = `wmic logicaldisk get caption, drivetype, freespace, size`.split("\n")
    logical_disk = []
    bytes_to_gbytes = 1073741824

    #Convert data from bytes to gigabytes and find the used space (size-free)
    tmp.each do |disk|
      disk = disk.split(" ")
      if disk[1].to_i == 3
        disk[2] = (disk[2].to_f/bytes_to_gbytes).round(2)
        disk[3] = (disk[3].to_f/bytes_to_gbytes).round(2)
        disk.push((disk[3].to_f - disk[2].to_f).round(2))
        logical_disk.push(disk)
      end
    end
    return logical_disk
  end

  #Add the disks usage in %
  def get_logical_disk_usage_percentage(logical_disk)
    logical_disk.each do |disk|
      disk.push(((disk[2].to_f/disk[3].to_f)*100).round(2))
      disk.push(100.00-disk[5])
    end
    return logical_disk
  end

  def run
    timestamp = Time.now.utc.to_i
    logical_disk = get_logical_disk_metrics()
    logical_disk = get_logical_disk_usage_percentage(logical_disk)

    logical_disk.each do |disk|
      metrics = {
        :"logical_disk_#{disk[0]}" => {
          :"size(Gb)" => disk[3],
          :"free_space(Gb)" => disk[2],
          :"free_space(%)" => disk[5],
          :"used_space(Gb)" =>  disk[4],
          :"used_space(%)" => disk[6]
        }
      }
      metrics.each do |parent, children|
        children.each do |child, value|
          output [config[:scheme], parent, child].join("."), value, timestamp
        end
      end
    end
    ok
  end
end


texts:
The goal:

  Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value.

I figured out how to get a list of dictionaries, and then add up the price. My output isn't pretty, but before I continue, I would simply like general critique.

class Product:
    def __init__(self, i, p, q):
        self.identification = i
        self.price = p
        self.quantity = q
        self.item_dictionary = {'ID: ': self.identification, 'Price: ': self.price, 'Quantity: ': self.quantity}

class Inventory:
    def __init__(self):
        self.identification, self.price_list, self.quantity_list = [], [], []
        self.products = [
            product_1.item_dictionary,
            product_2.item_dictionary
        ]  # Make list of item dictionaries

    for i in self.products:
        self.identification.append(i['ID: '])
        self.price_list.append(i['Price: '])
        self.quantity_list.append(i['Quantity: '])
        # Make unique lists of ID, Price, and Quantity

    print(sum(self.price_list))

product_1 = Product(32, 23, 2)
product_2 = Product(23, 65, 3)

inventory_1 = Inventory()


texts:
I want to know if the following parser covers every possible cases, and if the code can be cleaner/better organized.

Python 3 code:

def add_element(cache, element):
    if element != '':
        cache[-1].append(element)
    return ''

def to_py(raw_tcl_list):
    out = []
    cache = [out]
    element = ''
    escape = False
    for char in raw_tcl_list:
        if escape:
            if char not in ["\\", "{", "}", "[", "]", "$"]:
                raise ValueError("Incorrect escape character %s" % char)
            element += char
            escape = False
        elif char == "\\":
            escape = True
        elif char in [" ", "\t", "\r", "\n"]:
            element = add_element(cache, element)

        elif char == "{":
            a = []
            cache[-1].append(a)
            cache.append(a)

        elif char == "}":
            element = add_element(cache, element)
            if len(cache) < 2:
                raise ValueError("Close bracket without opening bracket.")

            cache.pop()
        else:
            element += char
    if len(cache) != 1:
        raise ValueError("Mismatched brackets.")
    return out[0]

def to_tcl(py_list):
    if type(py_list) == list:
        out_str = "{ "
        for item in py_list:
            out_str += to_tcl(item)
        out_str += "} "
        return out_str
    else:
        out_str = str(py_list) + " "
        for c in ["\\", "{", "}", "[", "]", "$"]:
            out_str = out_str.replace(c, "\\" + c)
        return out_str

import pprint

x = "{ 12 apple {100} {} {{12 34}} \n {56\n { \\{78 {11 12 11} 10}}}"
y = to_py(x)
z = to_tcl(y)
print("# Original #")
pprint.pprint(x)
print("\n# Translated to Python List #")
pprint.pprint(y)
print("\n# Translat back to Tcl List #")
print(z)

Output:

# Original #
'{ 12 apple {100} {} {{12 34}} \n {56\n { \\{78 {11 12 11} 10}}}'

# Translated to Python List #
['12',
 'apple',
 ['100'],
 [],
 [['12', '34']],
 ['56', ['{78', ['11', '12', '11'], '10']]]

# Translat back to Tcl List #
{ 12 apple { 100 } { } { { 12 34 } } { 56 { \{78 { 11 12 11 } 10 } } }

list of Tcl special characters: http://wiki.tcl.tk/989#pagetoceaa9fda9


texts:
You are given an array of N integers, find the Max Difference where
  the index of largest number is greater than the index of the smallest
  number. If not find the next smallest number, so on and so forth. If
  this condition cannot be met, return -1

Sample Input                        Sample Output

values = [1, 2, 3, 4, 5]                  4

values = [2, 3, 4, 5, 1]                  3

values = [121, 30, 45, 55, 1]             -1

My solution, Python 2.7

def findNewIndex(max_index, min_index, input_array):
    input_array.pop(min_index)

    num = min(input_array)
    min_index = input_array.index(num)

    if max_index > min_index:
        return input_array[max_index] - input_array[min_index]
    elif max_index < min_index and input_array:
        return  findNewIndex(max_index, min_index, input_array)
    else:
        return -1

def maxDifference(input_array):
    max_num = max(input_array)
    max_index = input_array.index(max_num)

    min_num = min(input_array)
    min_index = input_array.index(min_num)

    if max_index > min_index:
        print input_array[max_index] - input_array[min_index]
    else:
       ans =  findNewIndex(max_index, min_index, input_array)
       print ans

I'd like feedback on the solution, is this a good way to solve it? Any improvements I can make to the code in terms of performance/style?


texts: Sorting an integer array using heap sort

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

public static void main(String[] args) {

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

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

    buildMaxHeap(arr, arr.length);

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

    heapSort(arr);

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

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

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

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

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

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

    }

}

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

}


texts: Arduino: Change the color & color intensity of a LED periodically

texts:
Prerequisites:

A RGB-LED is attached and wired to the Arduino Uno-board.

Process description:

In the beginning the LED is turned off.

A loop starts and an output-signal is put on the red-part of the LED.

With every iteration the output-signal becomes increased in the following way: 0, 1, 2, 3, ...

The loop stops after 255 (maximal red) is reached. After a delay the output-signal becomes decreased (by using a loop again) in the way: 255, 254, 253 ... until 0 is reached.

Then the increasing and decreasing starts again but this time with the green-part of the LED.

After the blue-part of the LED has been increased and decreased the whole process starts again with the red-part.

GitHub-README with Image of the board-setup

Implementation:

   // -------- Declarations --------------
const int GREEN_LED_PIN = 9;
const int RED_LED_PIN = 11;
const int BLUE_LED_PIN = 10;
const int DELAY_WITHIN_LOOP = 10;
// ---------------------------------------

// ------- Own Functions -----------------
void setLed(int valRed, int valGreen, int valBlue) {
  analogWrite(RED_LED_PIN, valRed);
  analogWrite(GREEN_LED_PIN, valGreen);
  analogWrite(BLUE_LED_PIN, valBlue);
}

void changeColorIntensity(int position, int step, int i, int stop) {
  while (i != stop) {
    switch (position) {
      case 0:
        setLed(i, 0, 0);
        break;
      case 1:
        setLed(0, i, 0);
        break;
      case 2:
        setLed(0, 0, i);
        break;
    }

    i += step;
    delay(DELAY_WITHIN_LOOP);
  }
}
// -------------------------------------------

void setup() {
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(BLUE_LED_PIN, OUTPUT);
}

void loop() {
  for (int i = 0; i < 3; i++) {
    changeColorIntensity(i, 1, 0, 256);
    changeColorIntensity(i, -1, 255, -1);
  }
}

The sketch works just fine and solves exactly the described task.

What annoys me is the part with the switch-statement and the multiple function-invocations.

If someone has an idea how to solve that part then his/her answer would be very appreciated.

Generally: What would you have done different and why?

Looking forward to reading your comments, recommendations and hints!


texts: PHP download counter script with htaccess

texts:
I'd like to show you my script and would like to hear your security hints. Maybe the code is also useful to someone else.

What I want to archive:

Someone clicks on a link on my web page
a htaccess file looks for some file-extensions and if the requested file is one of these, it will be counted.
After the count (done with PDO prepare), the file is proceed to the user.

Because I want to get maximum security and not offering someone other files than from the upload folder I ask before doing it wrong.

.htaccess:

RewriteEngine on
RewriteRule ^(.*).(rar|zip|pdf|tar|apk|rpm|exe)$ /download.php?file=$1.$2 [L,NC]

download.php

<?php

// Allowed extensions
$filetypes = array("rar", "zip", "pdf", "tar", "apk", "rpm", "exe");

// Details of requested file
$file_path  = $_REQUEST['file'];

// NullByte cleaner
$file_path = str_replace(chr(0), '', $file_path);

// Split details
$path_parts = pathinfo($file_path);
$file_name  = $path_parts['filename'];
$file_ext   = $path_parts['extension'];

// CleanUp
$file_name  = preg_replace('/[^\0-9_a-zA-ZäöüÄÖÜ]+/', '', $file_name);
$file_ext  = preg_replace('/[^\0-9a-zA-Z]+/', '', $file_ext);

// Create path
$dir_path = $_SERVER['DOCUMENT_ROOT']."/";
$finalpath  = $dir_path . $file_name . "." . $file_ext;

// Allowed extension?
if ( in_array($file_ext, $filetypes) ) {

    // Does the file exist?
    if ( is_file($finalpath) ) {

        // Final security check
        setlocale(LC_ALL,'en_US.UTF-8');
        $local_ext = pathinfo($finalpath, PATHINFO_EXTENSION);

        // Allowed local extension?
        if ( in_array($local_ext, $filetypes) ) {

            // Logging
            // ..........

            // Download
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($finalpath));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($finalpath));
            ob_clean();
            flush();
            readfile($finalpath);
            exit;
        }

    }

}

// Something went wrong
echo "Error...";
exit;


texts:
I create https://github.com/storenth/react-redux-todo and ask to review my Todo-react-app for programming pattern: dividing components into presentational components and container components.
Here’s the basic idea behind it: if a component has to have state, make calculations based on props, or manage any other complex logic, then that component shouldn’t also have to render HTML-like JSX.
Instead of rendering HTML-like JSX, the component should render another component. It should be that component’s job to render HTML-like JSX.
So, my question about the /containers/TodosContainer that contains /components/Todos and /components/AddForm. Does it match the pattern? I didn't get where to place the AddForm, inside /components/Todos (to complex I guess)?
import React, { Component, Fragment } from 'react';
import { Todos } from "../components/Todos";
import { AddForm } from "../components/AddForm";

export class TodosContainer extends Component {
    constructor(props) {
        super(props);
        this.state = { items: [], text: '' };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.removeItem = this.removeItem.bind(this);
    }
    handleChange = (e) => {
        this.setState({
            text: e.target.value
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        if (this.state.text.length === 0) {
            return;
        }
        const newItem = {
            text: this.state.text,
            id: Date.now()
        };
        this.setState({
            items: this.state.items.concat(newItem),
            text: ''
        })
    }
    removeItem = (id) => {
        const items = this.state.items.filter(item => {
            return item.id !== id;
        })
        this.setState({
            items
        })
        console.log(this.state);
    }

    render() {
        return (
            <>
                <Todos items={this.state.items} removeItem={this.removeItem} />
                <AddForm items={this.state} onSubmit={this.handleSubmit} onChange={this.handleChange} />
            </>
        )
    }
}
```


texts: Should I put default values of attributes on the prototype to save space?

texts:
Suppose I've got a JavaScript function that I'm treating like a class - that is, I want to make many instances of it:
function Blerg() {
  this._a = 5;
}

Blerg.prototype.getA = function() {
  return this._a;
}

Blerg.prototype.setA = function(val) {
  this._a = val;
}

This class has one attribute, a, which the constructor instantiates to a default value of 5. It is accessed with the getter and setter.
Now suppose I have such a class but it has 30+ attributes (a, b, c, etc), and suppose like a that these all have unique default values, but also that it is uncommon for them to be changed from the default.
Suppose also that I need to make 10,000 or more Blerg instances, and so a design goal is to save space.
I'm wondering if it is a good idea to put all of the default values for my 30+ attributes on the prototype of my class instead. That way, when I create 10,000+ instances of my class, none of them have a, b, c, etc attributes, but calling getA() will still return the correct default value.
So I present this modified Blerg function, Blerg2:
function Blerg2() {
  // nothing!
}

Blerg2.prototype._a = 5;

Blerg2.prototype.getA = function() {
  return this._a;
}

Blerg2.prototype.setA = function(val) {
  this._a = val;
}

Are there downsides to taking this approach?

Some notes
The prototype way seems faster to create, see: http://jsperf.com/blergs
For that matter, the worst-case scenario does not look that bad: http://jsperf.com/blergs/2
And creating many of them using the code in the jsperf test (in its own html page) and adding:
var a = [];
for (var i = 0; i < 400000; i++) {
  a.push(new Blerg()); // or Blerg2
}

Suggests that the heap size for the objects in question is cut in half by using Blerg2.


texts: JavaScript function to generate tree object from flat object

texts:
The following function takes an object of items in the format of

{
  'complex-key': 'value',
  // Repeat
}

where complex-key is a key delimited by dots, and returns an object in the form of a tree, where you can access the value by traversing the parts of the complex keys as keys in the object (see examples below).

The function

function createMessages(items) {
    var result = {};
    Object.keys(items).forEach(function(key) {
        var keyParts = key.split('.');
        var currentObj = result;
        while (keyParts.length > 0) {
            var currentKey = keyParts.shift();
            if (keyParts.length === 0) {
                var currentItems = {};
                if (currentObj[currentKey]) {
                    currentItems = currentObj[currentKey];
                }
                currentObj[currentKey] = function() { return items[key]; };
                Object.keys(currentItems).forEach(function(currentItemKey) {
                    currentObj[currentKey][currentItemKey] = currentItems[currentItemKey];
                });
            }
            else if (!currentObj[currentKey]) { currentObj[currentKey] = {}; }
            currentObj = currentObj[currentKey];
        }
    });
    return result;
}

Examples

var message1 = createMessages({'a.b.c.d': 42});
console.log(message1.a.b.c.d() === 42); // true

var message2 = createMessages({'a.b.c.d': 42, 'a.b.c.e': 43});
console.log(message2.a.b.c.d() === 42); // true
console.log(message2.a.b.c.e() === 43); // true

var message3 = createMessages({'a.b.c.d': 42, 'a.b.c': 43});
console.log(message3.a.b.c() === 43); // true
console.log(message3.a.b.c.d() === 42); // true (properties on the functions)

The current function looks overly bloated and inefficient (with \$O(n\times m)\$ at best, and \$O(n\times m^2)\$ at worst). While this is going to be used for test code only, and to small objects only (no more than 10 keys), I would still want to find a way to make it prettier and more efficient. Would appreciate any and all help.


texts:
I was cleaning up some old code and came across this (it's to read input from a terminal):
static public int read_input_key() {

    /*
    F1 ESC O P [27 79 80]
    F2 ESC O Q [27 79 81]
    F3 ESC O R [27 79 82]
    F4 ESC O S [27 79 83]
    Up ESC [ A [27 91 65]
    Down ESC [ B [27 91 66]
    Left ESC [ D [27 91 68]
    Right ESC [ C [27 91 67]
    Home ESC [ 1 ~ [27 91 49 126]
    F5 ESC [ 1 5 ~ [27 91 49 53 126]
    F6 ESC [ 1 7 ~ [27 91 49 55 126]
    F7 ESC [ 1 8 ~ [27 91 49 56 126]
    F8 ESC [ 1 9 ~ [27 91 49 57 126]
    End ESC [ 4 ~ [27 91 52 126]
    Page-up ESC [ 5 ~ [27 91 53 126]
    Page-down ESC [6 ~ [27 91 54 126]
    Insert ESC [ 2 ~ [27 91 50 126]
    F9 ESC [ 2 0 ~ [27 91 50 48 126]
    F10 ESC [ 2 1 ~ [27 91 50 49 126]
    F11 ESC [2 2 ~ [27 91 50 50 126]
    F12 ESC [ 2 3 ~ [27 91 50 51 126]
    */

    //

    try {

        if (System.in.available() != 0) {

            int c = System.in.read();
            if (c == 27) {

                switch (System.in.read()) {
                case 79:
                    switch (System.in.read()) {
                    case 80:
                        return VK_F1;
                    case 81:
                        return VK_F2;
                    case 82:
                        return VK_F3;
                    case 83:
                        return VK_F4;
                    }
                case 91:
                    switch (System.in.read()) {
                    case 65:
                        return VK_UP;
                    case 66:
                        return VK_DOWN;
                    case 68:
                        return VK_LEFT;
                    case 67:
                        return VK_RIGHT;
                    case 49: {
                        switch (System.in.read()) {
                        case 126:
                            return VK_HOME;
                        case 53:
                            return System.in.read() == 126 ? VK_F5 : 0;
                        case 55:
                            return System.in.read() == 126 ? VK_F6 : 0;
                        case 56:
                            return System.in.read() == 126 ? VK_F7 : 0;
                        case 57:
                            return System.in.read() == 126 ? VK_F8 : 0;
                        }
                    }
                    case 52:
                        return System.in.read() == 126 ? VK_END : 0;
                    case 53:
                        return System.in.read() == 126 ? VK_PAGE_UP : 0;
                    case 54:
                        return System.in.read() == 126 ? VK_PAGE_DOWN : 0;
                    case 50: {
                        switch (System.in.read()) {
                        case 126:
                            return VK_INSERT;
                        case 48:
                            return System.in.read() == 126 ? VK_F9 : 0;
                        case 49:
                            return System.in.read() == 126 ? VK_F10 : 0;
                        case 50:
                            return System.in.read() == 126 ? VK_F11 : 0;
                        case 51:
                            return System.in.read() == 126 ? VK_F12 : 0;
                        }
                    }
                    }
                }
            } else {
                return c;
            }
        }
    } catch (IOException e) {
        // restore terminal?
        e.printStackTrace();
    }

    return 0;
}

It work's fine, but I feel like it can be done really different. To explain the long comment (I should atleast refactor that), this for example:
    F1 ESC O P [27 79 80]

Means when you press the F1 key you will get the sequence ESC O P, which is represented by the following ascii keys, 27 79 80.


texts:
I have the following configuration:

$('document').ready(function () {
    var what0 = [
        ["http://validator.w3.org/unicorn/", "Unicorn"],
        ["http://validator.w3.org/", "W3C Validation Service"],
        ["http://jigsaw.w3.org/css-validator/", "W3c CSS Validator"],
        ["http://text-compare.com/", "Text Compare!"]
    ],
        what1 = [
            ["https://imgflip.com/", "Imgflip.com"],
            ["http://jpillora.com/base64-encoder/", "Base64 Encoder"],
            ["http://www.showmycode.com/", "Adobe Flash Decompiler"],
            ["http://jsbeautifier.org/", "Beautify Js"]
        ],
        what2 = [
            ["http://plnkr.co/edit/?p=catalogue", "Plunker"],
            ["http://www.css3maker.com/index.html", "CSS3 Generator"],
            ["http://daneden.github.io/animate.css/", "Animate.css"],
            ["http://site.youidraw.com/", "YouDraw"]
        ],
        what3 = [
            ["http://realfavicongenerator.net/", "Favicon Generator"],
            ["http://grabicon.com/", "Grabicon"],
            ["http://www.buildmypinnedsite.com/en", "Windows 8.1 tile"],
            ["https://kraken.io/web-interface", "Kraken.io"]
        ],
        what4 = [
            ["http://ideone.com/rran1v", "C++0x Compiler"],
            ["http://webcompiler.cloudapp.net/", "online C++ compiler"],
            ["http://www.color-hex.com/", "Color Hex"],
            ["https://icomoon.io/app/#/select", "IcoMoon App"]
        ],
        wh = [what0, what1, what2, what3, what4];

    function Toggle(elem) {
        var hiding = document.getElementById("hiding" + elem),
            buttonforhiding = document.getElementById("buttonforhiding" + elem);
        $(hiding).hide();
        $(buttonforhiding).click(function () {
            $(hiding).toggle();
        });
    }
    for (var a = 0; a <= 4; a++) {
        Toggle(a.toString());
    }

    function populate(one, two) {
        var where = document.getElementById("hiding" + one),
            what = two,
            length = what.length - 1;
        for (var b = 0; b <= length; b++) {
            var vector = what[b];
            $(where).append('
' + what[b][1] + '
');
        }
    }
    for (var c = 0; c <= 4; c++) {
        var d = wh[c];
        populate(c, d);
    }

});
ul {
    list-style-type:none;
}

Folder 1

Folder 2

Folder 3

Folder 4

Folder 5

Its role is to populate some lists with the links in the what0, what1, what2, etc. arrays. It is working fine, but I was interested if you can come up with a code that is more efficient.

The requirements are:

The input data is the arrays called "what*", from 0 to any given number of arrays.
The output is the folder-style type lists. Also, these lists are initially hidden and shown only onclick.
The script must be using only JavaScript and jQuery.


texts:
I'm in the process of creating my first web app using node with mongodb on the backend. I could use some opinions on the schemas/models I've set up.

I have three schemas: User, Pet, Food. Here's the general relationship of them:

Users have pets -> Pets have a list of ingredients and list of favorite foods -> Food has list of ingredients.

Here's my userSchema:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minlength: 8,
    validate(value) {
      if (value.toLowerCase().includes('password')) {
        throw new Error('password contains password');
      }
    },
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw new Error('Email is invalid');
      }
    },
  },
  tokens: [
    {
      token: {
        type: String,
        required: true,
      },
    },
  ],
});

userSchema.virtual('pets', {
  ref: 'Pet',
  localField: '_id', // associated with the _id of the user
  foreignField: 'owner', // the name of the field on the other object that creates the relationship, which we set to the owner
});

const User = mongoose.model('User', userSchema);

Here's my pet model:

const Pet = mongoose.model('Pet', {
  name: {
    type: String,
    required: true,
    trim: true,
  },
  badIngredients: [
    [
      {
        Ingredient: {
          type: String,
        },
      },
    ],
  ],
  favoriteFoods: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Food' }],
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User', // reference to the User model
  },
});

and finally the food model:

const Food = mongoose.model('Food', {
  name: {
    type: String,
    required: true,
    trim: true,
  },
  brand: {
    type: String,
    required: true,
    trim: true,
  },
  flavor: {
    type: String,
    required: true,
    trim: true,
  },
  ingredients: [
    {
      type: String,
      required: true,
      trim: true,
    },
  ],
  imagePath: {
    type: String,
    required: true,
    trim: true,
  },
});

I'm unsure if it would be a good idea to have some kind of relationship between the pet's list of ingredients and the list of ingredients with the food. The general idea is a user can select ingredients that their pet is allergic to, and it will filter out the list of foods for them that DON'T contain those ingredients. They can then assign favorite foods to their pet.

I could also use some advice if using the userSchema.virtual property for pets is better than simply having a property on my user that is a list of pets.

The food itself will be static data stored somewhere.


texts: Short code in Python Rock Paper Scissors

texts:
I am studying and practicing Python; this is my Rock-Paper-Scissors game I've built from scratch.
I saw this task is for beginners. When writing this in all the examples I saw dozens of lines of code with if elif else statements.
I decided to write the shortest program for this game.
I'm just looking for any comments, improvements or bad habits. Any comments at all are welcome!

import random

my_win = 0
my_loss = 0
my_tie = 0

def game():

    global my_tie, my_loss, my_win

    var = {'scissors':(0,1,0),
           'paper':(0,0,1),
           'rock':(1,0,0)}

    user = input("Please choice scissors, paper or rock: ")
    while user not in ['scissors', 'paper', 'rock']:
            user = input("Please choice scissors, paper or rock: ")
    computer = random.choice(['scissors','paper','rock'])

    print(f"USER - {user} \nCOMPUTER - {computer}")

    for k, v in var.items():
        if k == user:
            one = int(v.index(1))
        if k == computer:
            two = int(v.index(1))

    if one < two:
        print(f"USER with {user} - WIN!")
        my_win += 1
    elif one == two:
        print("==TIE==")
        my_tie += 1
    else:
        print(f"COMPUTER with {computer} - WIN!")
        my_loss += 1

    def results():

        print ("You win %d times!" % my_win)
        print ("You lose %d times!" % my_loss)
        print ("You tie %d times!" % my_tie)

if __name__ == "__main__":
    game()


texts: Project Euler, Problem 273: finding perfect-square partitions

texts:
Problem:

  Consider equations of the form: \$a^2 + b^2 = N; 0 \leq a \leq b; a, b, N \in \mathbb{N}\$.

  For \$N=65\$ there are two solutions:

  \$a=1, b=8\$ and \$a=4, b=7\$.

  We call \$S(N)\$ the sum of the values of \$a\$ of all solutions of \$a^2 + b^2 = N\$.

  Thus \$S(65) = 1 + 4 = 5\$.

  Find \$\sum S(N)\$, for all squarefree \$N\$ only divisible by primes of the form \$4k+1\$ with \$4k+1 < 150\$.

My solution is painfully slow:

import math
import itertools
import time

def candidate_range(n):
    cur = 5
    incr = 2
    while cur < n+1:
        yield cur
        cur += incr
        incr ^= 6 # or incr = 6-incr, or however
def sieve(end):
    prime_list = [2, 3]
    sieve_list = [True] * (end+1)
    for each_number in candidate_range(end):
        if sieve_list[each_number]:
            prime_list.append(each_number)
            for multiple in range(each_number*each_number, end+1, each_number):
                sieve_list[multiple] = False
    return prime_list

primes = sieve(150)
goodprimes = []
for prime in primes:
    if prime%(4)==1:
        goodprimes.append(prime)
sum=[]
start_time = time.time()
#get a number that works
print("-------Part 1------")
mi=0
for L in range(1, len(goodprimes)+1):
    sumf=0
    for subset in itertools.combinations(goodprimes, L):
        max=2**L/2
        n=1
        for x in subset:
            n*=x

        for b in range(math.floor(math.sqrt(n/2)), math.floor(math.sqrt(n)+1)):
            a=math.sqrt(n-b*b)
            if a.is_integer() and b>=a:
                sum.append(a)
                mi+=1
                if mi==max:
                    mi=0
                    break
    for num in sum:
        sumf+=num
    print(L,sumf, "--- %s seconds ---" % (time.time() - start_time))

                    #q+=1

print("--- %s seconds ---" % (time.time() - start_time))
sumf=0
for num in sum:
    sumf+=num
print(sumf)


texts: Finding the sub-array with maximum sum - my slow approach

texts:
I decided to give the maximum sub-array sum problem an interesting go, however I will assure you that it doesn't perform well, and that I would never put this in production.

I'd like a review on this, if possible, it would be cool to see the running time, I'm sure it's upper bounded by at most \$O(n^3)\$, but it may actually be less:

public class FindMaximumSubArraySumProblem extends Problem<int[]> {
    private static final int[][] DATA = {
        {-1},
        {1},
        {-5, 1, -3, 7, -1, 2, 1, -4, 6},
        {-5, 1, -3, 7, -1, 2, 1, -6, 5},
        {-5, 6, -3, -2, 7, -5, 2, 1, -7, 6},
        {-5, -2, -1, -4, -7},
        {4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8},
        {4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 },
//        buildRandom(1000, -10, 100),
//        buildRandom(10000, -10, 100),
//        buildRandom(10000, -1, 10000)
    };

    private static int[] buildRandom(int size, int min, int max) {
        return new Random().ints(size, min, max).toArray();
    }

    public FindMaximumSubArraySumProblem() {
        super("Find Maximum Sub-array Problem", 1000, 10000);
    }

    @Override
    public String getResult() {
        return Arrays.toString(execute());
    }

    @Override
    public int[] execute() {
        return Arrays.stream(DATA).mapToInt(this::computeMaxSum).toArray();
    }

    private int computeMaxSum(final int[] array) {
        return IntStream.range(0, array.length)
                .map(i -> IntStream.range(i, array.length)
                        .map(j -> Arrays.stream(array)
                                .skip(i)
                                .limit(j - i + 1)
                                .sum()
                        )
                        .max()
                        .orElse(0)
                )
                .max()
                .orElse(0);
    }
}

The method to look at is computeMaxSum:

private int computeMaxSum(final int[] array) {
    return IntStream.range(0, array.length)
            .map(i -> IntStream.range(i, array.length)
                    .map(j -> Arrays.stream(array)
                            .skip(i)
                            .limit(j - i + 1)
                            .sum()
                    )
                    .max()
                    .orElse(0)
            )
            .max()
            .orElse(0);
}

Results are:

Find Maximum Sub-array Problem => [-1, 1, 11, 9, 8, -1, 25, 28] (hot 0,09256ms - cold 0,132ms (total 1028,825ms))


texts:
I am new to Python and I have tried to come up with a code for the number guessing game. But I am pretty sure this is not the right way to do it. I am able to get the right output, however, my code is pretty long. Any ideas on using a different logic or to reduce the code size would help.

I also would like to know how to code profile a python code for performance.

I am using IDLE and Python 3.+

import random

def main():
    while(True):
        inputchoice = input("Are you ready? Y/N : ")
        if(inputchoice.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
            print("Ok. Lets begin")
            randomnumberguessinggame()
            break
        elif(inputchoice.strip() in ("no","No","NO","nO","n","N")):
            print("Let me know when you are ready")
            break
        else:
            print("Invalid Entry. Try again")

def randomnumberguessinggame():
    print("Get ready to start guessing")
    actualnumber = random.randrange(0,1000)
    #print("The number to be guessed is %d"%actualnumber)
    flag = True;
    while(flag):
        try:
            guessednumber = int(input("Enter your guess "))
            if(guessednumber > actualnumber):
                print("That was a wrong guess. Your guess is higher than my number")
                while(True):
                    retry = input("Would you like to try again? Y/N : ")
                    if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
                        flag = True;
                        break
                    elif(retry.strip() in ("no","No","NO","nO","n","N")):
                        flag = False;
                        break
                    else:
                        print("Invalid Entry. Try again")
            elif(guessednumber < actualnumber):
                print("That was a wrong guess. Your guess is lower than my number")
                while(True):
                    retry = input("Would you like to try again? Y/N : ")
                    if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
                        flag = True;
                        break
                    elif(retry.strip() in ("no","No","NO","nO","n","N")):
                        flag = False;
                        break
                    else:
                        print("Invalid Entry. Try again")
            else:
                print("You've got it right. Congratulations!!")
                flag = False;
        except ValueError:
            print("Your guess is invalid. Kindly guess again.")
            flag = True;

main()

print("Exiting the game...")