texts: Array even and odd indexes sorting and printing its values

texts:
I'm looking for a more elegant solutions of this task.

Task:
Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line.

Input Format:
The first line contains an integer (the number of test cases).
Each line of the subsequent lines contain a string.

puts "Input a number of test cases"
t = gets.to_i
t.times do
  puts "Input a string please"
  s = gets.strip
  z = s.split(//)
  b = z.each_with_index.sort_by { |i, x| [x.even? ? 0 : 1, x] }
  b.map { |i, x| print i if x.even? }
  print " "
  b.map { |i, x| print i if x.odd? }
  puts
end


texts: Is it a good practice to wrap datatypes in custom classes?

texts:
So in my current application, I was thinking to make a extended class for all the datatypes. For int, it will be something like ExtendedInt, for bool it will be something like ExtendedBool.

These individual extended classes will expose some special functonality bound to that type. For example, this is how i think my ExtendedInt will look like:

public interface IExtended
{
   bool IsModified { get; set; }
}

Public class ExtendedInt: IExtended
{
   private bool m_IsModified;
   private int m_MaxValue = int.MaxValue ;
   private int m_MinValue = int.MinValue;
   private int m_Value=int.MinValue;
   private int m_MaxValue = int.MaxValue ;
   private int m_MinValue = int.MinValue;

   public bool IsModified
      {
    get { return m_IsModified; }
    set { m_IsModified = value; }
      }

    public int Value
    {
        get { return m_Value; }
        set
    {
    // Only change the value if it is different.

             if (m_Value != value)
       {
          // Only set the value if it is in the valid range, if any max/min exists.
          if ((m_MaxValue > -1) && (value > m_MaxValue))
          {
              throw new ArgumentException("Value is above maximum value permitted.");
           }
           else if ((m_MinValue > -1) && (value < m_MinValue))
           {
               throw new ArgumentException("Value is below minimum value permitted.");
           }
           else
           {
              m_Value = value;
              this.IsChanged = true;
              if (m_Parent != null) m_Parent.DirtyState();
            }
               }
           }
       }

Similarly, I will provide ExtendedBool, ExtendedDouble, ExtendedDate, ExtendedString, etc..

Is this considered the best practice or it is overhead for my application?


texts: Class to simplify skipping some actions on the first loop iteration

texts:
Often I have to skip some actions on the first (or last) loop iteration. Now I need to append some arguments to a URL and separate the arguments by the & character.

For example:

http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml&cnt=7

To do so, the code looks like this:

public static String prepareUrl(String url, List<? extends NameValuePair> arguments) {
    boolean firstIteration = true;
    StringBuilder urlBuilder = new StringBuilder(url);
    for (NameValuePair argument : arguments) {
        if (firstIteration) {
            firstIteration = false;
        } else {
            urlBuilder.append("&");
        }
        urlBuilder.append(argument.getName());
        urlBuilder.append("=");
        urlBuilder.append(argument.getValue());
    }
    return urlBuilder.toString();
}

But it's very annoying to write and a little difficult to read such code. And it's easy to make a mistake in a loop body like this.

I wrote the next class, but I need your help to name the class and its methods properly (I'm pretty bad in English). And please, criticize my code severely.

// I know that class name must be a noun.
// But I can't think of a good name.
// And it seems to me that a comparison with the blank cartridge is a good one.
public abstract class FirstCartridgeIsBlank implements Runnable {

    private boolean firstCartridge;

    public FirstCartridgeIsBlank() {
        firstCartridge = true;
    }

    public final void run() {
        if (firstCartridge) {
            firstCartridge = false;
            blankShot();
        } else {
            shot();
        }
    }

    protected void blankShot() {
        // the inheritors can override this method if they need
    }

    protected abstract void shot();

}

Now the method prepareUrl() looks like this:

public static String prepareUrl(String url, List<? extends NameValuePair> arguments) {
    final StringBuilder urlBuilder = new StringBuilder(url);
    FirstCartridgeIsBlank appendAmpersand = new FirstCartridgeIsBlank() {
        @Override
        protected void shot() {
            urlBuilder.append("&");
        }
    };
    for (NameValuePair argument : arguments) {
        appendAmpersand.run();
        urlBuilder.append(argument.getName());
        urlBuilder.append("=");
        urlBuilder.append(argument.getValue());
    }
    return urlBuilder.toString();
}

I can't use the String.join() method from Java 8 because it's for the Android app (i.e. Java 6).


texts: Depth First Search vs Breadth First Search

texts:
So after years of teaching myself, I think I'm ready to stand on the shoulders of giants and ask you a good question!
I have a tree of nodes. What I want is a function that returns an array of the entire tree sorted by depth.
In my original attempt I wasn't aware at the time that I was performing a depth first search.
My solution was to:

recursively walk the tree, annotating depth as I go along.
sort the above based on the depth annotation.
filter out the depth annotation and return the sorted array.

That was three steps invoking 3 loops! So then someone alerted me to the concept of a breadth first search. I did my research and built (on my own) a BFS function! It looked so simple and did what I needed.
Then when I timed both versions; completely bafflingly; the cumbersome DFS version is faster! Why???
Here is my depth-first-search:
function dfsElementsInTree(input){
  // perform depth first search but
  // return a depth sorted array of an element or elements and any children
  let output = [];

  if (Symbol.iterator in input)
    // input is a HTMLcollection
    for (const element of input)
      doTraversal(element);
  else
    doTraversal(input);

  return output.sort((a, b) => a.depth - b.depth).map(item=>item.element);

  function doTraversal(element, depth=0) {
    output.push({element, depth});
    if (element.children.length) depth++;
    for (const child of element.children)
      doTraversal(child, depth);
  }
}

Here is my breadth-first-search:
function bfsElementsInTree(input) {
  // perform a breadth first search in order to have elements ordered by depth.
  let output = [];
  let queue = [];
  let visited = [];
  const enqueue = item => {queue.push(item); visited.push(item);};

  if (Symbol.iterator in input)
    // input is a HTMLcollection
    for (const element of input)
      queue.push(element);
  else
    queue.push(input);

  while (queue.length) {
    for (const element of queue)
      for (const child of element.children)
        if (!visited.includes(child))
          enqueue(child);
    output.push(queue.shift());
  }

  return output;
}

Ready for benchmarking here: https://jsben.ch/ZNuAx

But if you want to test it yourself, here's some code to generate some trees:
// Create trees of divs as such:
// (left to right)
// 1
// 1 -> 2
// 1 -> 2 -> 3
// 1 -> 2
// 1

const a1 = document.createElement('div');
const a2 = document.createElement('div');
const a3 = document.createElement('div');
const a4 = document.createElement('div');
const a5 = document.createElement('div');

[a1,a2,a3,a4,a5].forEach(e => e.className ='1');

const b2 = document.createElement('div');
const b3 = document.createElement('div');
const b4 = document.createElement('div');

[b2,b3,b4].forEach(e => e.className ='2');

const c3 = document.createElement('div');

c3.className = '3';

a2.appendChild(b2);

b3.appendChild(c3);
a3.appendChild(b3);

a4.appendChild(b4);

[a1,a2,a3,a4,a5].forEach(e => document.body.appendChild(e));

Thank you so much for your time. It's a real treat to have an expert looking over my shoulder!


texts:
I have a considerably large directive which is doing many things: First it renders a Google Map, then it adds a listener to check when the bounds of the map change, then it renders points on the map based where the bounds currently are, and finally it has a menu of options which allow the user to turn on and off various settings on the map.

The code snippet below has been heavily modified to show the most important aspects of the directive. I've also hardcoded the template rather than used a templateURL.

This directive works exactly the way I want it to, and my questions are more about best practices for Angular:

Should I be pulling out the Ajax calls and placing them inside a service?
Should I create a Map controller and put some of this configuration logic in there?
When do I know if I need a new controller for that matter?

I'm afraid there is too much going on inside this directive and it should be broken out.

(function(angular) {
 'use strict';

 angular.module('myApp.directives').directive('myAppMap', [function() {

 return {
  template: '
A whole bunch of toggles for the map go here
 \

'
  link: function(scope, element, attrs) {

    var map, markers = [], currentLayer = [];

    function initialize() {
      var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(34.05, -118.245),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
          mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'myApp_style']
        }
      },
      map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions)
      map.mapTypes.set('myApp_style', styledMap);
      map.setMapTypeId('myApp_style');
      google.maps.event.addListener(map, 'bounds_changed', (function() {
       _getClusters();
      })());
    }

    function _getClusters(filters) {
      $.ajax({
        url: "http://localhost:1625/ocpu/library/imyApp/R/gen_cluster/json",
        type: 'POST',
        dataType:'json',
        data: {
          NE_lng:map.getBounds().getNorthEast(),
          SW_lng:map.getBounds().getSouthWest()
          maxNumber: 100
        },
        success:function(data){
          _setMarkers(map, JSON.parse(data));
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log("ajax error - arun", xhr.status, thrownError);
        }
      })
    }

    function _setMarkers(map, clusters) {
      for (var i = 0; i < clusters.length; i++) {
        var thisCluster = clusters[i];
        var myLatLng = new google.maps.LatLng(thisCluster.lat, thisCluster.lon);
        markers[i] = new MarkerWithLabel({
          position: myLatLng,
          map: map,
          icon: "marker_01.png",
          labelClass: "myAppMarker",
          labelAnchor: new google.maps.Point(10, 40),
        })
        google.maps.event.addListener(markers[i], 'click', function() {
          map.setCenter(this.getPosition())
          map.setZoom(map.getZoom()+1);
        })
      }
    }

    function _toggleControls(direction) {
      if (direction=="open") {
        $(".mapControls").height("130");
        $(".mapControls .controls").fadeIn();
      }
      else {
        $(".mapControls .controls").fadeOut();
        $(".mapControls").height("30");
      }
    }

    $(".mapControls .open").click(function(){
      if ($(".mapControls .controls").is(":visible")) {
        _toggleControls("close")
      }
      else {
        _toggleControls("open")
      }
    })

    initialize();

   }
 }
}]);
})(window.angular);


texts: Serialization/Deserialization with Generics in Java

texts:
I've Implemented a Serialization Utility which Serializes/DeSerializes a class, along with writing JUnit Test Cases for the same.

Please Review the code and Suggest me how to improve it. Particularly in generics as I've not written much code with Generics in java.

SerializableEmployee.java - Class to be Serialized

public class SerializableEmployee implements Serializable{

    /**
     * This Serial version UID will change once any new version of class has been created
     */
    private static final long serialVersionUID = 1L;

    private String name;

    public SerializableEmployee(String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }

    @Override
    public String toString() {
        return "SerializableEmployee{" +
                "name='" + name + '\'' +
                '}';
    }
}

SerializationUtil.java - Util for Serializing and Deserializing

/**
 * Created by shashi on 21/12/15.
 *
 * @param <T> Type of class to Serialize and Deserialize from
 */
public class SerializationUtil<T> {

    /**
     * Logger for the class
     */
    public Logger LOG = LoggerFactory.getLogger("WHAT to Write here instead of T.class");

    /**
     * Serializes the given {@link T} object and save it into a file
     * @param type {@link T} object to be Serialized
     * @param fileName File in which {@link T} object is to be saved
     *
     * @return boolean specifying if {@link T} object has been serialized
     */
    public boolean serialize(T type, String fileName) {

        try(FileOutputStream fileStream = new FileOutputStream(fileName);
                ObjectOutputStream objectStream = new ObjectOutputStream(fileStream)) {
            objectStream.writeObject(type);
        }catch(IOException inputOutputException){
            LOG.error("Exception Occurred while Serializing {}. Message is ", "WHAT to Write here instead of T.class", inputOutputException.getMessage());

            return false;
        }

        return true;
    }

    /**
     * De-Serializes the given {@link T} object from the given file
     * @param fileName File from which {@link T} object has to be retrieved
     *
     * @return deserialized {@link T} object from the file
     */
    public T deSerialize(String fileName) {

        T employee = null;
        try(FileInputStream fileStream = new FileInputStream(fileName);
            ObjectInputStream objectStream = new ObjectInputStream(fileStream)) {
            employee = (T)objectStream.readObject();
        }catch(IOException | ClassNotFoundException inputOutputException){
            LOG.error("Exception Occurred while Serializing {}. Message is ", "WHAT to Write here instead of T.class", inputOutputException.getMessage());
        }

        return employee;
    }
}

SerializationUtilTest.java - jUnit Test cases for SerializationUtil class

/**
 * Created by shashi on 21/12/15.
 */
public class SerializationUtilTest {

    // Employee to Deserialize
    private static SerializableEmployee employee;
    // De-Serialized Employee
    private static SerializableEmployee deSerializedEmployee;

    // Utility class for Serialization
    private static SerializationUtil<SerializableEmployee> serializationUtil;

    // Provide Abstraction for Constants used
    interface Constants {
        String EMP_NAME = "Shashi";
        String FILE_NAME = "Emp-File";
    }

    @Before
    public void setUp(){
        employee = new SerializableEmployee(Constants.EMP_NAME);

        serializationUtil = new SerializationUtil<SerializableEmployee>();

        serializationUtil.serialize(employee, Constants.FILE_NAME);
        deSerializedEmployee = serializationUtil.deSerialize(Constants.FILE_NAME);
    }

    @Test
    public void employeeNotNullTest(){
        assertTrue(deSerializedEmployee != null);
    }

    @Test
    public void employeeNameEqualTest(){
        assertTrue(Constants.EMP_NAME.equals(deSerializedEmployee.getName()));
    }
}


texts: Sieve of eratosthenes: My optimized version

texts:
I wrote a simple prime number program that checks if a number is prime or not using sieve of eratosthenes, I also wrote an optimized version that only generates the sieve_arr when the val exceeds the length of sieve_arr.
sieve.py
# sieve.py

from array import array
from math import sqrt

def sieve(n=80):
    """Sieve of Erathosthenes"""

    sieve_arr = array('i', [True for _ in range(n+1)])
    sieve_arr_length = len(sieve_arr)

    for i in range(2, int(sqrt(sieve_arr_length)) + 1):
        if sieve_arr[i]:
            for j in range(i + i, n + 1, i):
                sieve_arr[j] = False;

    return sieve_arr

prime.py
# prime.py

import timeit
from array import array
from sieve import sieve

sieve_arr = array('i')

def isprime(val):
    global sieve_arr
    if val >= len(sieve_arr):
        sieve_arr = sieve(val * 2)

    return sieve_arr[val]

def isprime2(val):
    return sieve(val)[val]

if __name__ == '__main__':
    TEST1 = '''
from prime import isprime
for i in range(1, 10001):
    isprime(i)
    '''

    TEST2 = '''
from prime import isprime2
for i in range(1, 10001):
    isprime2(i)
    '''

    tt1 = timeit.repeat(stmt=TEST2, repeat = 5, number=1)
    print('prime Time taken: ', min(tt1))
    tt2 = timeit.repeat(stmt=TEST1, repeat = 5, number=1)
    print('Optimized prime Time taken: ', min(tt2))

I ran the test and had the following results
prime Time taken:  9.446519022000302
Optimized prime Time taken:  0.002043106000201078

Note: I didn't check for 0 and 1 in isprime() and isprime2() which aren't prime number, I wrote the code with performance in mind.


texts:
I have a Python3 script (running on Python 3.5.2) which reads 110 CSV files (tab delimited) into a list. The largest file is 20 MB and the list ends up looking like this:

[
    [line1],
    [line2],
    [line2021756],
    etc.
]

Right now the process takes about 32 seconds to complete:

python3 -m cProfile -s time script.py

10 files found
2021756 non-unique lines found.

9600828 function calls (9600673 primitive calls) in 32.900 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1   30.451   30.451   32.890   32.890 script.py:81(main)
  7419324    1.945    0.000    1.945    0.000 {method 'startswith' of 'str' objects}
  2021994    0.189    0.000    0.189    0.000 {method 'append' of 'list' objects}
    76528    0.164    0.000    0.164    0.000 {built-in method _codecs.utf_8_decode}
    76528    0.130    0.000    0.294    0.000 codecs.py:318(decode)
      110    0.007    0.000    0.007    0.000 {built-in method io.open}
        5    0.002    0.000    0.002    0.000 {method 'read' of '_io.FileIO' objects}
        3    0.001    0.000    0.001    0.000 {built-in method _imp.create_dynamic}
        5    0.001    0.000    0.001    0.000 {built-in method marshal.loads}
        1    0.001    0.001    0.001    0.001 {built-in method posix.listdir}
      110    0.001    0.000    0.001    0.000 {built-in method _csv.reader}
       48    0.001    0.000    0.002    0.000 <frozen importlib._bootstrap_external>:1215(find_spec)
      111    0.001    0.000    0.001    0.000 {built-in method posix.lstat}
      332    0.001    0.000    0.001    0.000 posixpath.py:71(join)

... and I would like to know if there is a way to significantly reduce that time?. It seems startswith and append are the main bottlenecks.

script.py

# Find CSV files.
files_found = glob.glob('{0}dir_*_name/{1}'.format(input_dir,file_of_interest))
len_files_found = len(files_found)
if len_files_found == 0:
    print_message('Error: zero {0} files found'.format(file_of_interest), True)
print_message('{0} files found'.format(len_files_found), False)

# Read each file into files_found_lines.
# files_found_lines will look like [[line1],[line2],[line3],...]
files_found_lines = []
for file in files_found:
    try:
        # Open file for reading text.
        with open(file, 'rt', newline='', encoding='utf-8') as f:
            reader = csv.reader(f, delimiter='\t')
            for row in reader:
                # Keep lines starting with BLAH.
                if row[0].startswith('BLAH'):
                    # Get first 9 columns.
                    files_found_lines.append(row[0:9])
    except Exception as error:
        print_message('Error: {0}'.format(error), True)

It's possible I may end up reading each CSV file into its own list instead of one big list like above, so just FYI.


texts: An efficient way to order content in controller [Spring Boot]

texts:
My code works as intended. CategoryController class has getAllCategories method, which tells ContentOrderMap class to map differently ordered categories to their respective OrderType enum.
The intention is whenever @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType changes from DEFAULT, to lets say, POST_COUNT_DESC, I would get differently ordered categories in my view.
My concern is if this is an efficient way of dealing with multiple ways of ordering my content. Previously I had a bunch of if statements in my controller and they would take care of getting and assigning information to model based on request param. This didn't seem very scalable since my controller method would get very big and would contain logic, which I think should not be there.
I'm having trouble correctly wording my problem and issues since I am new to this, if anything is not clear enough, I will gladly reword or explain.
Controller:
@Controller
@RequestMapping("/categories")
public class CategoryController {

private CategoryService categoryService;
private ContentOrderMap orderMap;

public CategoryController(CategoryService categoryService, ContentOrderMap orderMap) {
    this.categoryService = categoryService;
    this.orderMap = orderMap;
}

@GetMapping("/all")
    public String getAllCategories(@RequestParam(defaultValue = "0") int pageNumber, Model model, @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType) {
        orderMap.mapCategoriesToOrderType(pageNumber);
        Page<Category> categories = orderMap.categoriesByOrderType.get(categoriesOrderType);
        int pageCount = categoryService.getAllCategories(pageNumber).getTotalPages();
        model.addAttribute("orderType", categoriesOrderType);
        model.addAttribute("categories", categories.getContent());
        model.addAttribute("pageNumber", pageNumber);
        model.addAttribute("hasNextPage", categories.hasNext());
        model.addAttribute("pageCount", pageCount);
        return "categories";
    }
}

ContentOrderMap class
public Map<OrderType, Page<Category>> categoriesByOrderType = new HashMap<>();

public void mapCategoriesToOrderType(int pageNumber) {
        categoriesByOrderType.put(OrderType.DEFAULT, categoryService.getAllCategories(pageNumber));
        categoriesByOrderType.put(OrderType.POST_COUNT_DESC, categoryService.getAllCategoriesByPostCountDesc(pageNumber));
        categoriesByOrderType.put(OrderType.POST_COUNT_ASC, categoryService.getAllCategoriesByPostCountAsc(pageNumber));
        categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_DESC, categoryService.getAllCategoriesByFollowersCountDesc(pageNumber));
        categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_ASC, categoryService.getAllCategoriesByFollowersCountAsc(pageNumber));
        categoriesByOrderType.put(OrderType.POST_DATE_DESC, categoryService.getAllCategoriesByNewestPost(pageNumber));
        categoriesByOrderType.put(OrderType.POST_DATE_ASC, categoryService.getAllCategoriesByOldestPost(pageNumber));
    }

CategoryService
all of the methods seen above are more or less identical in service class, they only differ in their naming, so I am going to add only one of them for brevity's sake
public Page<Category> getAllCategoriesByPostCountDesc(int pageNumber) {
        Pageable pageable = PageRequest.of(pageNumber, 4);
        return categoryRepository.findAllOrderByPostCountDesc(pageable);
    }

In case its needed, I add an example of how categoryRepository looks
@Query(value = "SELECT c.* FROM category c LEFT JOIN review r ON c.id = r.category_id GROUP BY c.id ORDER BY COUNT(*) DESC",
            countQuery = "SELECT COUNT(*) FROM CATEGORY",
            nativeQuery = true)
    Page<Category> findAllOrderByPostCountDesc(Pageable pageable);


texts: Custom function extending jQuery.Deferred

texts:
I couldn't find an example on how to have a custom function inherit jQuery's functions while leaving the original jQuery function I'm inheriting from unchanged (I wanted my function to have a read but didn't want it to get added to $.Deferred)

This works, but I really suspect it isn't the right way to do it.

var DeferredFileEntry = function(){
    var def = $.Deferred();
    var promise = def.promise;

    def.read = function(textFnCallback){ // <--this is the method I'm adding
        return $.Deferred(function(newDefer){
            var newDefer = $.Deferred();
            def.done(function(fileEntry){
                fileEntry.getText()
                    .done(function(text){
                        textFnCallback(text);
                        newDefer.resolve(fileEntry);
                    });
            });
        }).promise();
    };
    def.promise = function(){
        //expose the custom method to the returned promise
        promise.read = def.read;
        return promise();
    };
    return def;
};

An example usage:

var getFileEntry = function(){
    var def = DeferredFileEntry();
    libraryCall() // that promises to resolve with a FileEntry object
        .done(function(fileEntry){
            def.resolve(fileEntry);
        });
    return def.promise();
}

getFileEntry()
    .read(function(text){
        console.log("reading content:" + text);
    })
    .read(function(text){
        //chained,
        //doesn't run until the previous one has resolved
        console.log("reading content again: "+text);
    });


texts:
I have started learning data structures and have implemented my own stack implementation:

package com.algo.stack;

import java.io.Serializable;
import java.lang.reflect.Array;

public class MyStack<T extends Serializable> {

    private T[] myArray = null; // the array is the stack content
    private int arraySize = 0; // holds the size counter

    /*
     * Initialize stack for its size and generic type
     */
    public MyStack(Class<T> c,int stackSize){

        @SuppressWarnings("unchecked")
        final T[] a = (T[]) Array.newInstance(c , stackSize);
        this.myArray = a;
    }

    /**
     * The push method, which adds
     * numbers in internal array
     * @param obj
     * @throws Exception
     */
    public void push(T obj) throws Exception{
        if(this.arraySize < this.myArray.length){
            this.myArray[this.arraySize++] = obj;
        }else{
            throw new Exception("MyStack is Full, need to pop");
        }

    }

    /**
     * pops or removes elements from
     * the internal array in LIFO fashion
     * @return
     * @throws Exception
     */
    public T pop() throws Exception{
        if(this.arraySize <= 0){
            throw new Exception("Nothing to pop, stack is empty");
        }
        return this.myArray[--this.arraySize];
    }

    /**
     * Returns the total size
     * @return
     */
    public int size(){
         return this.arraySize;
    }

    public static void main(String[] args){
        MyStack<Integer> stack1 = null;
        MyStack<String> stack2 = null;
        try{
            stack1 = new MyStack<Integer>(Integer.class, 3);
            stack1.push(12);
            stack1.push(24);
            stack1.push(36);

            while(stack1.size() > 0){
                System.out.println(stack1.pop());
            }

            System.out.println("\n");

            stack2 = new MyStack<String>(String.class, 4);

            stack2.push("Leo");
            stack2.push("Tom");
            stack2.push("Nancy");
            stack2.push("Julean");

            while(stack2.size() > 0){
                System.out.println(stack2.pop());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

It's working fine and the output is:

36
24
12

Julean
Nancy
Tom
Leo

Please review my rough implementation and let me know of any flaws and how I can improve.


texts: Pass in parameters instead of multiple functions

texts:
I can't quite figure out the best way to approach this. I have two jQuery objects that both are used to set cookies. I then parse the JSON and set a cookie that is either the users height or the users weight.

This works fine, but I feel like there is an extreme amount of redundant code here that could be cleaned up but for the life of me I'm blanking on how to best do this. Ideally I'd like to be able to somehow condense this and have a function that I can pass in parameters if I want to receive the height cookie or the weight cookie.

Possibly something along the lines of: userInfo(heightCookie) or userInfo(weightCookie).

I'm a bit of a newbie, so code examples are ideal, please.

var height_cookie = {
        name: 'user-height',
        options: {
            path: '/',
            expires: 365
        }
    };
var weight_cookie = {
        name: 'user-weight',
        options: {
        path: '/',
        expires: 365
        }
    };

function userHeightCookie() {
            var userData = $.parseJSON($.cookie(height_cookie.name));
            return(userData);
    };

function userWeightCookie() {
            var userData = $.parseJSON($.cookie(weight_cookie.name));
            return(userData);
    };

function readHeightCookie(userInfo) {
        $.cookie(height_cookie.name, JSON.stringify(userInfo), height_cookie.options);
    };

function readWeightCookie(userInfo) {
        $.cookie(weight_cookie.name, JSON.stringify(userInfo), weight_cookie.options);
    };

var userInfo = readHeightCookie();
var userInfo2 = readWeightCookie();


texts:
For this problem, I came up with this ugly solution of appending the characters to the output and in case there is adjacent duplicate deleting from the output. Considering StringBuilder.deleteCharAt(i) is O(N), performance is O(N) + O(N) = O(N).

Please critique this, if this is a right way.

public static String removeDuplicate(String s) {
StringBuilder builder = new StringBuilder();
char lastchar = '\0';
for (int i = 0; i < s.length(); i++) {
  String str = builder.toString();
  if (!str.equals("")
      && (str.charAt(str.length() - 1) == s.charAt(i))) {
    builder.deleteCharAt(str.length() - 1);
  } else if (s.charAt(i) != lastchar)
    builder.append(s.charAt(i));
  lastchar = s.charAt(i);
}
return builder.toString();
}

Sample input outputs:

  Input:  azxxzy
  Output: ay

  Input: caaabbbaacdddd
  Output: Empty String

  Input: acaaabbbacdddd
  Output: acac


texts: Simple Flask API backend to maintain a word list

texts:
I made a little toy project last semester. I would like to get some insights about my code, particularly the part of handling the database. It is a CRUD kind of traditional API.

def fword(lon,lat,radius,ids):
    try:
        result = {}
        c, conn = connection()
        c.execute("SELECT * FROM wordlocation WHERE ((longitude-%s)*(longitude-%s)+(latitude-%s)*(latitude-%s))<%s",(lon,lon,lat,lat,radius))
        words = []
        for row in c.fetchall():
            t = {}
            if row[0] in ids:
                continue
            t["name"] = row[1]
            t["definition"] = row[4]
            t["id"] = row[0]
            t["lat"] = row[2]
            t["long"] = row[3]
            words.append(t)
        result["words"] = words
        j = json.dumps(result)
        c.close()
        conn.close()
        return j
    except Exception as e:
        logging.info(str(e))

def pword(lat,lng,word,definition):
    try:
        c, conn = connection()
        c.execute("INSERT INTO wordlocation (word,longitude,latitude,definition,lang) VALUES(%s,%s,%s,%s,%s)",
        (thwart(word),lat,lng,thwart(definition),'english'))
        conn.commit()
        c.close()
        conn.close()
        return "success!"
    except Exception as e:
        logging.info(str(e))

def cword(word, username):
    try:
        c, conn = connection()
        blank_word = " " + word
        c.execute("UPDATE userstat SET completed=CONCAT(IFNULL(completed,''), %s) , score=score+1 WHERE username=%s;",(blank_word, username))
        conn.commit()
        c.close()
        conn.close()
        return "successful collect"
    except Exception as e:
        logging.info(str(e))

def stat(username):
    try:
        c, conn = connection()
        c.execute("SELECT * FROM userstat WHERE username=%s", (username,))
        dict = {}
        u = c.fetchone()
        dict['username'] = username
        dict['words'] = str(u[1]).split()
        dict['score'] = u[2]
        return json.dumps(dict)
    except Exception as e:
        logging.info(str(e))

The backend logic:

@app.route("/getWord", methods=['GET'])
def getWord():
    if 'long' in request.args and 'lat' in request.args and 'radius' in request.args and 'ids' in request.args:
        try:
            longitude = float(request.args["long"])
            latitude = float(request.args["lat"])
            radius = float(request.args["radius"])
            ids = request.args.getlist("ids")
        except:
            return "Bad Request Parameters"
        try:
            allwords_json = fword(longitude,latitude,radius,ids)
            return allwords_json
        except Exception as e:
            logging.info(str(e))
    else:
        return "bad request"

@app.route("/postWord",methods=["GET","POST"])
def postWord():
    if 'lat' in request.args and 'long' in request.args and 'word' in request.args and 'definition' in request.args:
        try:
            lat = float(request.args['lat'])
            lng = float(request.args['long'])
            word = str(request.args['word'])
            definition = str(request.args['definition'])
            return pword(lat,lng,word,definition)
        except Exception as e:
            logging.info(str(e))
    else:
        return "badPost"

There are many other endpoints that is in a similar fashion. One issue I am aware of is the variable naming seems not readable.


texts:
I'm implementing the singly linked list data structure and functions to work with it. In particular I'm concerned about prepending and removing nodes. Currently I defined linked list as follows:

typedef struct string_list_node{
    int id;
    const char *value;
    struct string_list_node *next;
} string_list_node_t;

string_list_node_t **string_list_alloc(int id, const char *value){
    string_list_node_t *string_list_ptr = malloc(sizeof(*string_list_ptr));
    string_list_node_t **list = malloc(sizeof(*list));
    string_list_ptr -> id = id;
    string_list_ptr -> value = value;
    string_list_ptr -> next = NULL;
    *list = string_list_ptr;
    return list;
}

The thing I'm concerned about is the following implementation of prepend and delete_first_by_id functions:

void prepend(int id, const char *value, string_list_node_t ** list_ptr){
    string_list_node_t *node_ptr = *list_ptr;
    string_list_node_t *prepended_node = malloc(sizeof(*prepended_node));
    prepended_node -> id = id;
    prepended_node -> value = value;
    prepended_node -> next = node_ptr;
    *list_ptr = prepended_node;
}

//returns 0 if not found, 1 if found and list changed
int delete_first_by_id(string_list_node_t **source,
                       int id,
                       string_list_node_t ** deleted_value_out){
    string_list_node_t *prev = NULL;
    string_list_node_t *current = *source;
    while(current && current -> id != id){
        prev = current;
        current = current -> next;
    }

    if(current){
        if(!prev){
            *source = current -> next;
            *deleted_value_out = current;
        } else {
            *deleted_value_out = current;
            prev -> next = current -> next;
        }
        return 1;
    } else {
        return 0;
    }
}

Is this code looks ok in terms of sort of common C style? Is the behavior of the code undefined? I created a live example of usage here:

LIVE DEMO


texts: Finding sum of sub vector satisfying inequality

texts:
I am asked to implement code that checks if there is a sub vector that has a sum, v_l, that would satisfy \$ \frac{1}{4}mn + 1 \leq v_l \leq v - \frac{1}{4} m n - 1\$.

def possible(vec, m):
    n = len(vec)     # Number of columns
    v = sum(vec)
    global R

    R = []

    num = {i: 0 for i in set(vec)}
    for i in vec:
        num[i] += 1

    solution = dfs_backtrack(num, m, n, v)

return solution

def dfs_backtrack(vec, m, n, v):

    v_l = sum([i*vec[i] for i in vec.keys()])
    R.append(vec)

    if 0.25 * m * n + 1 <= v_l <= v - 0.25 * m * n - 1:
        return vec

    for i in vec.keys():
        temp = dict(vec)
        temp[i] -= 1
        if temp[i] is 0:
            temp.pop(i)
        if temp and temp not in R :
            temp = dfs_backtrack(temp, m, n, v)
        else:
            temp = None
        if temp:
            return temp
    return None

From my analysis it would have a space and time complexity of \$O(n^{m+1} m^{-m-1})\$, where \$1 \leq m \leq n\$. What can I do to improve the space and time complexity?


texts: Using pandas .apply to while loop through every row of the dataframe to get to intended substring given starting and ending index of a string

texts:
I have a function called postprocess that applies while loop condition to find for - and alphabets to each dataframe row. postprocess looks like this:

def postprocess(description, start_index, end_index):
      if (start_index > 0) & (start_index < len(description)):
        while bool(re.match(r"\w|\'|-", description[start_index - 1])) & bool(
            re.match(r"\w|\'|-", description[start_index])
        ):
            start_index = start_index - 1
            if new_start == 0:
                break
      description = description[new_start:new_end]
      return description

For example the description is credit payment velvet-burger and the start_index is 7 and end_index is 12. So description[start_index] will be b Which is the b in burger will be run in a while loop by tracing backwards to return the target substring we want to see because burger is not complete as we want the word velvet- also.
After running postprocess we will get velvet-burger.
The complete code looks like this:

df["target_substring"] = df.apply(lambda x: postprocess(
                         x["description"], x["start_index"], x["end_index"]+1),
                         axis=1)

Is there a better way to write this code?


texts:
I need to parse only valid timestamp formats:

Hours followed by minutes followed by seconds: t=1h2m3s
Minutes followed by seconds: t=2m3s
Only hours: t=3h
Only minutes: t=4m
Only seconds: t=5s and escape other timestamp formats like t=2m1h or t=3s2m or t=3s1h2m.

To get the hours, minutes and seconds, I use this Regex. Let me know any improvement can be done to make it simple.

function calculateInSeconds(timeStamp) {
  var timeInSeconds=0;
  if(timeStamp.match(/t=[0-9]*h?[0-9]*m?[0-9]*s?/g).toString()==timeStamp){
    timeStamp.replace(/([0-9]+)[h|m|s]/g, function(match, value) {
       if (match.indexOf("h") > -1) {
          timeInSeconds += value * 60 * 60;
       } else if (match.indexOf("m") > -1) {
                timeInSeconds += value * 60;
       } else if (match.indexOf("s") > -1) {
                timeInSeconds += value * 1;
       }
     });
   }
   console.log("timeInSeconds"+timeInSeconds);
}

calculateInSeconds("t=3m59s1h");//invalid
calculateInSeconds("t=1m59s");//valid
calculateInSeconds("t=1h");//valid


texts: Purging elements from the map if it reaches a memory size limit

texts:
I have implemented a LRU cache using ConcurrentLinkedHashMap. In the same map, I am purging events if my map reaches a particular limit as shown below.

I have a MAX_SIZE variable which is equivalent to 3.7 GB and as soon as my map reaches that limit, I am purging events from my map.

Below is my code:

import java.util.concurrent.ConcurrentMap;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;

// does this really equal to 3.7 GB?
public static final int MAX_SIZE = 20000000; //equates to ~3.7GB with assumption that each event is 200 bytes AVG

public static EvictionListener<String, DataObject> listener = new EvictionListener<String, DataObject>() {
    public void onEviction(String key, DataObject value) {
        deleteEvents();
    }
};
public static final ConcurrentMap<String, DataObject> holder = new ConcurrentLinkedHashMap.Builder<String, DataObject>()
            .maximumWeightedCapacity(MAX_SIZE).listener(listener).build();

private static void deleteEvents() {
    int capacity = MAX_SIZE - (MAX_SIZE * (20 / 100));
    if (holder.size() >= capacity) {
        int numEventsToEvict = (MAX_SIZE * 20) / 100;
        int counter = 0;
        Iterator<String> iter = holder.keySet().iterator();
        while (iter.hasNext() && counter < numEventsToEvict) {
            String address = iter.next();
            holder.remove(address);
            System.out.println("Purging Elements: " +address);
            counter++;
        }
    }
}

// this holder map is used in below method to add the events into it.
// below method is being called from some other place.
public void addToHolderRequest(String key, DataObject stream) {
    holder.put(key, stream);
}

Below is the maven dependency I am using for this:

<dependency>
    <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
    <artifactId>concurrentlinkedhashmap-lru</artifactId>
    <version>1.4</version>
</dependency>

I am not sure whether this is the right way to do this? Does this MAX_SIZE really equates to 3.7 GB if events are of 200 bytes in average? Is there any better way to do this? I also have a background thread which call deleteEvents() method every 30 second.


texts: Menu items to enter and exit full-screen mode in JavaFX

texts:
I need to improve this by using switch statement in which I want to set the text and setFullScreen. Is there any more elegant way to implement this?

final String change[] =
    {
        "Full Screen", "Exit Full Screen"
    };
    final MenuItem fullScreen = MenuItemBuilder.create().text(change[0]).build();

    fullScreen.setOnAction(new EventHandler<ActionEvent>()
    {
        @Override
        public void handle(ActionEvent e)
        {
            fullScreen.setText((fullScreen.getText().equals(change[0])) ? change[1] : change[0]);

            if (fullScreen.getText().equals(change[0]))
            {

                primaryStage.setFullScreen(false);
            }
            else
            {

                primaryStage.setFullScreen(true);
            }

        }
    });

    view.getItems().add(fullScreen);


texts:
I thought to do away with getters and setters behind the real world objects such as Person, Company or Address, i.e. getName and setName.

Each of these have public enum Attrib of states.

And the state is actually a pure Object mapped to a private HashMap.

package model;

import java.util.HashMap;
import java.util.Map;

public class Person {

    public enum Attrib {
        NAME, //String
        EMAIL, //String
        PHONE; //int

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    private final Map<Person.Attrib, Object> attribs;

    public Person(String name, String email, int phone) {
        attribs = new HashMap<>();
        attribs.put(Person.Attrib.NAME, name);
        attribs.put(Person.Attrib.EMAIL, email);
        attribs.put(Person.Attrib.PHONE, phone);
    }

    public Object getAttrib(Person.Attrib attribute) {
        return attribs.get(attribute);
    }

    public boolean setAttrib(Person.Attrib attribute, Object value) {
        if (attribute == Person.Attrib.PHONE && !(value instanceof Integer)) {
            return false;
        }
        attribs.put(attribute, value);
        return true;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            Person person = (Person) o;
            String _this = (String) this.getAttrib(Person.Attrib.NAME);
            String _that = (String) person.getAttrib(Person.Attrib.NAME);
            return _this.equalsIgnoreCase(_that);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return attribs.get(Person.Attrib.NAME).hashCode();
    }

    @Override
    public String toString() {
        return (String) attribs.get(Person.Attrib.NAME);
    }
}

I did saved some getters and setters but I guess it can't justify that all attributes are objects. To check what instanceof the getAttrib(Person.Attrib attribute) is, i.e. skim the class source to know whether you deal with a String or an Integer or Whatever, type cast it.


texts:
I'm a CS professor and provided this code as a small piece of a refactoring assignment:
private double getTotalPrice(int quantity, double itemPrice) {
    if (quantity == 13) {
        return itemPrice * 12; // Baker's dozen
    }
    else if (quantity >= 6) {
        return itemPrice * quantity * .95;
    } else {
        return itemPrice * quantity;
    }
}

Students are supposed to remove inappropriate magic numbers, but, when discussing the above code with them, I realized I don't know the best way to improve the above code. I'm not interested in improving performance, just teaching how to write clean and maintainable code.
Updates
I realize there are other problems with the code, some intentional. What I am most interested in is how to name the magic numbers.
The purpose of the code is to determine the total price for an order of up to 13 items (limit in place to prevent hoarding). My priorities are readability and maintainability.


texts:
The point of this question

I'm actually using it while developing a simple application and it seems to cover all my needs. Also it uses PDO so that we don't really have to worry about SQL Injection. I know I usually code strange, but I hope you could give me suggestions and feedback in order to improve it.

Code: Database Class

/* Operate on the database using our super-safe PDO system */
class db
{
    /* PDO istance */
    private $db = NULL;
    /* Number of the errors occurred */
    private $errorNO = 0;

    /* Connect to the database, no db? no party */
    public function __construct()
    {
        try
        {
            $this->db = new PDO(
                'mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host'), reg::get('db-username'), reg::get('db-password')
            );
        }
        catch (Exception $e)
        {
            exit('App shoutdown');
        }
    }

    /* Have you seen any errors recently? */
    public function getErrors() { return ($this->errorNO > 0) ? $this->errorNO : false; }

    /* Perform a full-control query */
    public function smartQuery($array)
    {
        # Managing passed vars
        $sql = $array['sql'];
        $par = (isset($array['par'])) ? $array['par'] : array();
        $ret = (isset($array['ret'])) ? $array['ret'] : 'res';

        # Executing our query
        $obj = $this->db->prepare($sql);
        $result = $obj->execute($par);

            # Error occurred...
            if (!$result) { ++$this->errorNO; }

        # What do you want me to return?
        switch ($ret)
        {
            case 'obj':
            case 'object':
                return $obj;
            break;

            case 'ass':
            case 'assoc':
            case 'fetch-assoc':
                return $obj->fetch(PDO::FETCH_ASSOC);
            break;

            case 'all':
            case 'fetch-all':
                return $obj->fetchAll();
            break;

            case 'res':
            case 'result':
                return $result;
            break;

            default:
                return $result;
            break;
        }
    }

    /* Get PDO istance to use it outside this class */
    public function getPdo() { return $this->db; }

    /* Disconnect from the database */
    public function __destruct() { $this->db = NULL; }
}

Use

$db = new db;
$user = $db->smartQuery(array(
    'sql' => "SELECT UserName FROM `post` WHERE UserUID = :uid",
    'par' => array('uid' => $uid),
    'ret' => 'fetch-assoc'
));
echo $user['Username'];

What I think is wrong

Well, I have encountered these 2 points while revisiting this code, and I'd like to get some feedback about them particularly:

The error system (which, let's face it, sucks right now)
The first try-catch code, which is actually working, but I never use that so, please, look at it.

Also if my application cannot connect to the database, most (if not all) features cannot be activated (such-as the PHP error log trough a database record, so that every times an error occurred, the admin is warned trough the application itself).


texts:
In my project, I am doing asynchronous processes in almost every classes. To explain my problem, I have created a sample:

public interface TestListener {
  void onResponse(Response result);
  void onError(Exception e);
}

public class AsyncTask {
  TestListener testListener;

  public AsyncTask(TestListener testListener, Request request)
  {

  }

  public void excute()
  {
    try {
      // process request
      Response response = new Response();
      testListener.onResponse(response);
    } catch (Exception e) {
      testListener.onError(e);
    }
  }
}

public class Test1 implements TestListener {

  public void doStuff()
  {
    Request request = new Request();
    // add some stuff to request;
    AsyncTask task = new AsyncTask(this, request);
    task.excute();
  }

  @Override
  public void onResponse(Response result)
  {
    // process response

  }

  @Override
  public void onError(Exception e)
  {
    // process error

  }
}

public class Test2 implements TestListener {

  void someStuff()
  {
    Request request = new Request();
    // add some stuff to request;
    AsyncTask task = new AsyncTask(this, request);
    task.excute();
  }

  @Override
  public void onResponse(Response result)
  {
    // process response

  }

  @Override
  public void onError(Exception e)
  {
    // process error

  }
}

This doesn't look good to me. In every class I have onResponse and onError. What I want to do is just create a helper class that will have onResponse and onError and it will return me the response.

public class Test1{
  public void doStuff(){
    AsyncHelper helper = AsyncHelper.getInstance();
    Response response = helper.test1Method(request);
  }
}

I have two questions:

Am I thinking correctly to remove onResponse code from every class and collect in one class.
How should I create an AsyncHelper class?


texts:
I'm looking for a review of my code for better design (to make sure it's more readable and legible).

<?php

// define variables and set to empty values
$nameErr = $phoneErr = $streetErr = $cityErr = $stateErr = $zipErr = "";
$name = $phone = $street = $city = $state = $zip = "";

// start script if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $nameErr = "Name is required";
    }
    else {$name = test_input($_POST["name"]);
            // check if name only contains letters and whitespaces
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
}

    if (empty($_POST["phone"])) {
        $phoneErr = "Phone # is required";
    }
    else {$email = test_input($_POST["phone"]);
        // check if phone only contains numbers and dashes in correct format
        if (!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/",$phone)) {
            $phoneErr = "Please resubmit Phone # in the following format: 555-     555-5555";
        }
    }

    if (empty($_POST["street"])) {
    $streetErr = "Address is required";
    }
    else {$street = test_input($_POST["street"]);
     // check if address syntax is valid
      if (!preg_match("/^[0-9a-zA-Z. ]+$/",$street)) {
       $streetErr = "Address appears to be invalid.";
      }
    }

    if (empty($_POST["city"])) {
      $cityErr = "City is required";
    }
    else {$city = test_input($_POST["city"]);
 // check if city syntax is valid
      if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
      $cityErr = "City appears to be invalid." ;
     }
    }

    if (empty($_POST["state"])) {
     $stateErr = "State is required";
}
    else {$state = test_input($_POST["state"]);
 // check if state is valid uppercase abbv. and two letters
 if (!preg_match("/^(A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADL N]
     |K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]
     |T[NX]|UT|V[AIT]|W[AIVY])$/",$state)) {
     $stateErr = "State appears to be invalid. (Hint...Use Upper-case!)" ;
   }
}

if (empty($_POST["zip"])) {
    $zipErr = "Zip Code field is required";
}
else {$zip = test_input($_POST["zip"]);
    // check if zip only contains numbers and dashes in correct format
    if (!preg_match("/^[0-9]{5}-[0-9]{4}$/",$phone)) {
        $phoneErr = "Please resubmit Zip Code in the following format: 55555-5555";
    }
}
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>


texts: Slow foreach loop to check for intersect

texts:
I'm trying to make a loop where it returns whether or not a rectangle collides and then to which coords the rectangle should move to.

I'm calling my function like this:

rectangles2[i].rect = rectangleupdated(i, rectangles2);

And this is inside my function:

private Rectangle rectangleupdated(int i, List<rectList> rectangles2)
{
    //fills rectangles with rectangles to check intersect with
    BOTTOM = rectangles2[i].rect;
    BOTTOM_LEFT = rectangles2[i].rect;
    BOTTOM_RIGHT = rectangles2[i].rect;
    //bool to be set to false if intersects returns true
    bBOTTOM = true;
    bBOTTOM_LEFT = true;
    bBOTTOM_RIGHT = true;
    //move the intersect rectangles
    BOTTOM.Y++;
    BOTTOM_LEFT.Y++;
    BOTTOM_LEFT.X--;
    BOTTOM_RIGHT.Y++;
    BOTTOM_RIGHT.X++;

    foreach (rectList rects in rectangles2)
    {
        if (!rects.type.Contains("bg"))
        {
            if (rectangles2[i].rect.Y < 500)
            {
                if (BOTTOM.IntersectsWith(rects.rect))
                {
                    bBOTTOM = false;
                }
                else if (BOTTOM_LEFT.IntersectsWith(rects.rect))
                {
                    bBOTTOM_LEFT = false;
                }
                else if (BOTTOM_RIGHT.IntersectsWith(rects.rect))
                {
                    bBOTTOM_RIGHT = false;
                }
            }
            else
            {
                return rectangles2[i].rect;
            }
        }
    }
    if (bBOTTOM == true) return BOTTOM;
    else if (bBOTTOM_RIGHT == true) return BOTTOM_RIGHT;
    else if (bBOTTOM_LEFT == true) return BOTTOM_LEFT;
    return rectangles2[i].rect;
}

I think I know a little bit why it's lagging so hard but I don't know how to fix it / make this code more usable.


texts: Find abstraction for classes which represent tables with differnt amount of colums (based on DataTables)

texts:
I have a lot of classes which are principal equal, but they consist small differences so that I can´t abstract then very well.

The classes represent different kinds of DataTables. Every Class has two important methods which every "table-class" has. Here a abstracted example:

internal class FooTable
{
    internal static DataTable CreateTable()
    {
        using (DataTable fooTable = new DataTable("fooTable"))
        {
            // number and content of rows are different from table to table.
            fooTable.Columns.Add("ColFoo");
            fooTable.Columns.Add("ColBar");
            fooTable.Columns.Add("ColSomethingElse");

            AddRow(fooTable, "ValueA", "ValueB", "ValueC");
            AddRow(fooTable, "ValueD", "ValueE", "ValueF");
            // ... more rows ...

            return fooTable;
        }
    }

    private static void AddRow(
        DataTable table,
        string ColFoo,
        string ColBar,
        string ColSomethingElse)
    {
        DataRow dataRow = table.NewRow();

        dataRow["ColFoo"] = ColFoo;
        dataRow["ColBar"] = ColBar;
        dataRow["ColSomethingElse"] = ColSomethingElse;

        table.Rows.Add(dataRow);
    }
}

The differences between the tables are the number of columns and the datatyp of column content. With this implementation I can´t use abstract classes, because of the different amount of columns. The names of the columns are also redundant in code.

Finally I think about the use of params to solve the problem with different amount of columns, but I’m not sure how to make a good implementation other AddRow-methode.

private static void AddRow(DataTable table, params object[] values)
{
    ...
}

So did anyone know a better way to implement this? I'm sure there is a better way.


texts: Split big file into separate files depending on column's distinct values

texts:
I have a big file, which contains column names in the first row. The data is about 20GB and consists of 10s of millions of rows. Every other row contains data which I would like to append to other files depending on the distinct entries in a particular column (depending on index). When the program encounters a new distinct entry it creates the file other wise it should append the data. The following piece of code is my basic attempt to achieve this (I am Python newbie):

import re
import os

input_path_file1 = 'C:\InputData.txt'
output_path = r'C:\Output\Data'
unique_values = {}

# read in first line containing column names
with open(input_path_file1, 'r') as file:
    first_line = file.readline()

rows = 0
# 7 line_number
# 35 range
index = 35
with open(input_path_file1, mode='r') as file:

    # skip first row
    next(file)

    for line in file:
        splitted_data = re.split(r'\t+', line.rstrip('\t'))
        cell_data = splitted_data[index].replace('/', '')
        target = os.path.join(output_path, cell_data + '.txt')

        if cell_data in unique_values:
            unique_values[cell_data] += 1
        else:
            unique_values[cell_data] = 1
            with open(target, 'w') as outfile:
                outfile.write(first_line)

        with open(target, 'a') as outfile:
            outfile.write(line)

        rows += 1

Could this be made more efficient?


texts: Finding the most common character in a string

texts:
I have started to try and work out the TopCoder problems. The "StringDup" problem asks us to:

  Create a class called StringDup. Given a string made up of ONLY letters and
  digits, determine which character is repeated the most in the string ('A' is
  different than 'a'). If there is a tie, the character which appears first in
  the string (from left to right) should be returned.

Is there any way I can make my solution better or more efficient?  Is there something that I have missed? I'm new to Java and I thought this would be a good way to learn.

public class StringDup {

    public char getMax(String word)
    {
        int characterCount = 0;
        int maxCharacter = 0;
        char maxCharacterChar = '.';

        char[] cArray = word.toCharArray();

        for(int i =0; i < cArray.length; i++)
        {
            int characterASCII = (int)cArray[i];
            characterCount = 0;

            //System.out.print("Chracter ASCII: " + characterASCII + "\n");
            for(int x = 0; x < cArray.length; x++)
            {
                if(characterASCII == (int)cArray[x])
                {
                    characterCount ++;
                    //System.out.print("Character Count for " + characterASCII + " " +  characterCount  + "\n");
                    if(characterCount > maxCharacter)
                    {
                        maxCharacter = characterCount;
                        maxCharacterChar = cArray[i];
                    }
                }
            }
        }
        return maxCharacterChar;
    }
}

It is called using the main method.

StringDup frequentChar = new StringDup();
System.out.print(frequentChar.getMax("sssdkljgh"));


texts: Search for longest substring in alphabetical order in a given string

texts:
I would like some help with a review of a program that I wrote to identify the longest continuous sub-string that is in alphabetical order within a string.  This is a JavaScript adaptation of an exercise originally written in Python.  I am new to JavaScript.  I would like any help identifying ways that this program could be written more efficiently, specifically if there are techniques or conventions in JavaScript that could improve this program.

One thing that was different between Python and JavaScript was that I had to split the string into an array in order to perform the comparison of characters.  I saw another example where this was the technique to assess the strings in JavaScript.

Is there a better way in JavaScript to assess strings when looking for components other than creating an array?

The second part of the program that I would like help with is the way that the search executes immediately, instead of waiting for the call to the function with the button.  I left the label in the code to show that the alphabetical sub-string in the place holder language is immediately identified, instead of waiting for a call to the function with the button.

What should I have done to make the function wait for a new search string?

// test string azcbobobegghakl, should yield beggh
function findSubStr() {
  document.getElementById("main").style.visibility = "visible";
  var string = document.getElementById("enterString").value;
  var lastSub = [],
    longestSub = [];
  var Arr = string.split('');
  for (var i = 0; i < Arr.length; i++) {
    if (Arr[i] >= lastSub.slice(-1)) {
      lastSub = lastSub + Arr[i];
      if (lastSub.length > longestSub.length) {
        longestSub = lastSub;
      }
    } else {
      lastSub = Arr[i];
    }
  }
  document.getElementById("main").innerHTML = longestSub;
}

console.log(findSubStr());
#start {
  top: 25%;
  left: 40%;
  position: absolute;
}
#main {
  top: 50%;
  left: 45%;
  font-size: 1.5em;
  position: absolute;
  visibility: hidden;
}
#enterString {
  color: gray;
}

  <input id="enterString" value="Please enter string">
  <button id="search" onclick="findSubStr()">Sub-String Search</button>

A pen on CodePen.


texts: Periodically sending data from database to an API

texts:
I'm trying to make a timed background service in .NET Core (I found this approach in Microsoft Docs), that every 15 seconds it gets data from the database (1000 rows max, if something exists) then sends it to the API using a foreach loop. If a response status code is not 200 or 202, I change thr status column by id in the database.

How can I make this code faster? Should I use another approach?

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FDProcessor
{
    class FDSenderService : IHostedService, IDisposable
    {
        private Timer timer;
        private HttpClient httpClient = new HttpClient
        {
            BaseAddress = new Uri("https://example.com")
        };

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Service is started.");
            timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
            return Task.CompletedTask;
        }

        private async void DoWork(object state)
        {
            var data = DbManager.GetTransactions();

            foreach (var r in data)
            {
                StringContent jsonRequestBody = new StringContent(JsonConvert.SerializeObject(r));
                var response = await httpClient.PostAsync("/example/path", jsonRequestBody);

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Bad request. Status returned.");
                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                    DbManager.UpdateTransaction(null, r.TrnID);
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Stopping!");
            timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            timer.Dispose();
        }
    }
}


texts: Deleting the head node of a circular linked list

texts:
Today I tackled this coding challenge:

  Given a circular linked list, implement a method to delete its head node. Return the list's new head node.

I would appreciate any feedback.

public ListNode deleteAtHead(ListNode head) {

    if(head == null){
        return head;
    }
    ListNode temp = head;

    while(temp.next != head){
        temp = temp.next;
    }

    temp.next = head.next;
    head.next = null;
    head = temp.next;

   return head;
}


texts:
This code sort the string below in ascending order.
I'd prefer it split-up in two or three smaller, simpler methods. I'm also wondering whether my algorithm has a decent time complexity.

Given string
[H, B, D, G, F, E, A, C]
Output
[A, B, C, D, E, F, G, H]

public class sortArray {
    public static void sort (String[] str)
    {
        int lastPos = str.length - 1;
        int minPos = 0;
        String s = "";
        for (int i = 0; i < lastPos; i++)
        {
            minPos = i;
            for (int j = i + 1; j <= lastPos; j++)
                if (str[j].compareTo (str[minPos]) < 0)
                    minPos = j;
            if (minPos != i)
            {
                s = str[i];
                str[i] = str[minPos];
                str[minPos] = s;
            }
        }
    }

    public static void main(String[] args){
        String[] str = {"H", "B", "D", "G","F", "E", "A", "C"};
        sort(str);
        System.out.println(Arrays.toString(str));
    }
}


texts: Getting essential computer info for network admins

texts:
I recently had to install VNC on mass across a lot of computers on a domain and needed some info about their PC, for example:

Host name
Username
MAC Address
IPv4 Address
Domain name

Once all of this info is gathered, it is compiled into a text file and uploaded to a FTP server. To save files from being conflicted with the same name, I set each file to be named the name of the user.

This is the first ever script and first experience I have had with Powershell so please tell me if there is anything I can improve.

function Get-MACAddress {
    ipconfig /all | findstr "Physical" | Where-Object {$_.length -lt 58}
}
function Get-IPAddress {
    ipconfig | findstr "IPv4 Address"
}
function Get-HostName {
   get-content env:computername
}
function Get-UserName{
     get-content env:UserName
}
function Get-DomainName{
get-content env:USERDOMAIN
}
function CreateCSVdocument {
    Get-MACAddress | New-Item C:\Users\$($env:username)\Documents\$($env:username).txt -type file     -force
    Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Get-IPAddress | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt "Hostname:"
Get-Hostname | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt "User:"
Get-UserName | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt "Domain:"
Get-DomainName | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
}
function FTPUpload {
$Dir="C:\Users\$($env:username)\Documents\$($env:username).txt"

#ftp server
$ftp = "ftpserver"
$user = "username"
$pass = "password"

$webclient = New-Object System.Net.WebClient

$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)

#list every sql server trace file
foreach($item in (dir $Dir "$($env:username).txt")){
    "Uploading $item..."
    $uri = New-Object System.Uri($ftp+$item.Name)
    $webclient.UploadFile($uri, $item.FullName)
}

}
Get-DomainName
Get-IPAddress
Get-MACAddress
Get-HostName
Get-UserName
CreateCSVdocument
FTPUpload


texts:
I have a C program where the user can select from 10 different options. I've already split the core functionality of each option into different methods, but my main() function is still quite long. The rest of the code in main() involves getting user input and formatting strings to the display so that the program is clearer and looks nice.
E.g. my code is similar to:
int actionOneFunction(char *name) {
    /* Action one logic */
}

int actionTwoFunction(FILE *fptr) {
    /* Action two logic */
}

void getUserInput(char *display_msg, char *input_variable, int variable_size) {
    printf("%s", display_msg);
    fgets(input_variable, variable_size, stdin);
    strtok(input_variable, "\n"); /* Remove newline added by fgets */
}

void displayStartingText() {
    /*
        A bunch of printf statements
    */
}

int main() {
    int result
    int action;

    displayStartingText();

    printf("Select the action you would like to carry out: ");
    scanf("%d", &action);
    getChar(); /* Remove newline generated by scanf from buffer */

    if (action < 0 || action > 10) {
        printf("Invalid action selected.\n");
        return 1;
    }

    if (action == 1) {
        char name[255];

        printf("------------\n");
        printf(" Action One \n");
        printf("------------\n");

        getUserInput("Enter the name: ", name, sizeof(name));
        result = actionOneFunction(name);
        if (result != 0) {
            return errno;
        }
        printf("Action one was successful!\n");
    }
    else if (action == 2) {
        FILE *fptr;
        char name[255];
        char *content;

        printf("------------\n");
        printf(" Action Two \n");
        printf("------------\n");

        getUserInput("Enter the file name: ", name, sizeof(name));

        fptr = openFile(name, "r");
        content = actionTwoFunction(fptr);
        fclose(fptr);

        printf("Content: \n", content);
    }
    else if (action == 3) {
        /* ... */
    }

    /*
        ...
    */

    else if (action == 10) {
        /* ... */
    }

    return 0;

}

With all ten options and their functionality defined, my main() becomes rather long. Would it be better to put each of the if blocks into their own functions?


texts:
I'm trying to continue the learning process in Java, and I've made a simple yet useful class which will allow me to retrieve the data inside a table from an Oracle DB, using JDBC.

What I'm especially looking after in a review is:

styleguide - as in naming variables / classes, spacing, and so on)
usage of correct data types
best practices

Code:

package oraconnection;

import java.sql.*;

class OraConnection {

    public static void oracleDbConnection(
            String db_driver,
            String db_type,
            String db_driver_type,
            String db_host_name,
            String db_port,
            String db_service_name,
            String db_username,
            String db_password) {

        String connection_string = String.format("%s:%s:%s:@%s:%s/%s",
                db_driver,
                db_type,
                db_driver_type,
                db_host_name,
                db_port,
                db_service_name);

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection connection = DriverManager.getConnection(
                    connection_string,
                    db_username,
                    db_password);

            Statement statement = connection.createStatement();
            String query = "select * from some_table";

            ResultSet result = statement.executeQuery(query);

            while (result.next()) {
                System.out.println(
                        result.getInt(1) + "  " + result.getString(2) + "  "
                        + result.getString(3));
            }
            connection.close();

        } catch (Exception e) {
            System.out.println(e);
        }

    }

    public static void main(String[] args) {
        oracleDbConnection(
                "jdbc",
                "oracle",
                "thin",
                "host",
                "port",
                "service-name",
                "user",
                "pass");
    }
}

Please bear with the fact that I'm a beginner when it comes to Java and I don't have a deep knowledge about its insides, so please make your answers as detailed as possible.


texts:
I got inspired to do this after seeing this repo containing a bunch of weird syntactical quirks in JS, namely this example called "It's a fail!". The example was essentially the following:

  You would not believe, but …

(![] + [])[+[]] +
 (![] + [])[+!+[]] +
 ([![]] + [][[]])[+!+[] + [+[]]] +
 (![] + [])[!+[] + !+[]];
// -> 'fail'

I found this quite interesting; however, as revealed by the explanation later on, the actual characters were merely coincidentally obtained using the fact that certain array operations return true, false and undefined, from which we can grab certain indices. The issue with using this for text obfuscation, of course, it that it's not applicable to most characters. However, the way we grab those indices is also using some array syntax, following just three rules:

// Number definitions
+[] // -> 0
+!+[] // -> 1

// Addition
+!+[] + +!+[] // -> 2
+!+[] + !+[] // -> also 2, but with one less character

// Concatenation by arrayifying
+!+[] + [+[]] // -> 10
+!+[] + [+!+[]] // -> 11

Using this, we could implement an algorithm to convert any number into such a format. I've also made some optimisations, so for example, instead of doing +!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[] just to do 9, we could simply do [+!+[] + [+[]] - !+[]] - making 10 by concatenating 1 and 0, then subtracting 1. The same process is done for any number > 5.

Below is my code. Any comments on readability, naming, etc. is obviously welcome, but I'm also open to any suggestions on further ways to make the output number more compact.

const obfuscateNumber = num => {
  let chars = [...num.toString()];

  let outputStr = "";
  let tokens = 0;
  chars.forEach(char => {
    let digit = parseInt(char);

    outputStr += (tokens > 0? " + " : "")
    if (digit === 0){
      outputStr += (tokens > 0? "[" : "")
                      + "+[]"
                      + (tokens > 0? "]" : "");
    } else if (digit === 1) {
      outputStr += (tokens > 0? "[" : "")
                      + "+!+[]"
                      + (tokens > 0? "]" : "");
    } else if (digit <= 5) {
      outputStr += "[";
      for (i = 0; i < digit; i++){
        outputStr += (i == 0? "" : " + ") + "!+[]";
      }
      outputStr += "]";
    } else {
      outputStr += "[+!+[] + [+[]]";
      for (i = 0; i < 10 - digit; i++){
        outputStr += " - !+[]";
      }
      outputStr += "]";
    }

    tokens++;
  });

  return outputStr;
}

Note: when I use the word 'obfuscate', I mean it in the sense that the number is unreadable to average humans. Obviously, it easily decodable, and I'm not planning to implement it into some production-grade obfuscation software therefore.


texts:
I did this program and I need to make sure I did it right. The answers come out to be right but I want to make sure nothing is wrong with the coding.

class RecursiveMethods
{
    RecursiveMethods()          //default constructor
    {
    }

    public int fOf(int x)
    {
        if (x <= 10)                        //the base case
        {
            System.out.println(x + " <= 10, therefore ... f(" + x + ") = -5");
            return -5;
        }
        else
        {
            System.out.println(x + " > 10, therefore ... f(" + x + ") = f(" + x + " - 3) + 2 = f(" + (x -3) + ") + 2");
            return fOf(x-3) + 2;
        }
    }
}

public class RecursionMethodTester
{
    public static void main(String[] args)
    {
        int x;
        RecursiveMethods rMethods = new RecursiveMethods();

        System.out.println("---------------------------------");
        System.out.println("       f(x - 3) + 2    if x >  10");
        System.out.println("f(x) = ");
        System.out.println("       -5              if x <= 10");
        System.out.println("---------------------------------");
        System.out.println();

        x = 20;
        System.out.println("Example 1:  x = " + x);
        System.out.println("f(" + x + ") = " + rMethods.fOf(x));
        System.out.println();

        x = 19;
        System.out.println("Example 2:  x = " + x);
        System.out.println("f(" + x + ") = " + rMethods.fOf(x));
        System.out.println();

        x = 18;
        System.out.println("Example 3:  x = " + x);
        System.out.println("f(" + x + ") = " + rMethods.fOf(x));
        System.out.println();
    }
}


texts:
This code works but I'm not really sure if I wrote it good enough. It seems a bit vague but I can't really assess it properly. I'm particularly concerned with the xAxis variable. I don't like how I have to initialize it inside the first loop. I would rather have it next to yAxis. Is this a problem?

float yAxis = SPACE_BETWEEN_TILES;
float xAxis;

for(int i = 0; i < 3; i++) {
    xAxis = SPACE_BETWEEN_TILES;
    for(int v = 0; v < 3; v++) {
        shapeRenderer.rect(xAxis, yAxis, 10, 10);
        xAxis = TILE_WIDTH_AND_HEIGHT + xAxis;
    }
    yAxis = yAxis + TILE_WIDTH_AND_HEIGHT;
}


texts:
Auto populate user info from database when user inputs employee number.  The same applies when the user inputs name/extension/mobile/email/

Some code is duplicated.  Is there any way to make it shorter?

$(document).ready(function () {
    $("#empnum").change(function () {
        var fourdigitpatrn = /^[0-9]{4}$/;
        var idType = this.id;
        var myval = $.trim(this.value);
        if (myval == "" | myval.length < 3 ) return;
        if (fourdigitpatrn.exec(myval)) {
            myval ="EMP_"+myval;
            }
        if (myval.length) {
            $.ajax({
                contentType: "application/json; charset=utf-8",
                url: 'http://myserver.com/helpdesk/check_json.php',
                dataType: 'json',
                data: {type: 'empnum', term: myval},
                success: function (data) {
                    if(typeof data == "undefined" | data == null | data.length == 0){
                    alert("No Result");
                    document.getElementById("form1").reset();
                    return};
                    //console.log(data);
                    $("#empnum").val(data[0].empnum);
                    $("#ext").val(data[0].extension);
                    $("#omobile").val(data[0].omobile);
                    $("#pmobile").val(data[0].pmobile);
                    $("#ename").val(data[0].ename);
                    $("#name").val(data[0].empnum);
                    $("#email").val(data[0].email);
                },
                error: function (result) {
                    alert("Error");
                }
            });
        }
    });
});

$(document).ready(function () {
    $("#ext").change(function () {
        var extpatrn=/^[0-9]{2,11}$/;
        var idType = this.id;
        var myval = $.trim(this.value);
        if (!extpatrn.exec(myval))
        {
        alert ("2~11 digits needed");
        return;
        }
        if (myval == "" | myval.length < 2 ) return;
        if (myval.length) {
            $.ajax({
                contentType: "application/json; charset=utf-8",
                url: 'http://myserver.com/helpdesk/check_json.php',
                dataType: 'json',
                data: {type: 'ext', term: myval},
                success: function (data) {
                    if(typeof data == "undefined" | data == null | data.length == 0){
                    alert("No Result");
                    document.getElementById("form1").reset();
                    return};
                    //console.log(data);
                    $("#empnum").val(data[0].empnum);
                    $("#ext").val(data[0].extension);
                    $("#omobile").val(data[0].omobile);
                    $("#pmobile").val(data[0].pmobile);
                    $("#ename").val(data[0].ename);
                    $("#name").val(data[0].empnum);
                    $("#email").val(data[0].email);
                },
                error: function (result) {
                    alert("Error");
                }
            });
        }
    });
});

//similar script for auto populate on omobile/pmobile/email input
...
...
...


texts: Remove and Add items from array in nested javascript object

texts:
I have the following object at React state:

groups: [
    {
        id: 1,
        items: [
            {id: 1},
            {id: 2},
            {id: 3}
        ]
    },
    {
        id: 3,
        items: [
            {id: 1},
            {id: 3},
            {id: 4}
        ]
    }
]

I have written the following functions to add and remove items:

  removeItem(groupId, itemId) {
    // make a copy
    let {groups} = this.state

    const gIndex= groups.findIndex(g=> g.id == groupId);
    let items = groups[gIndex].items
    groups[gIndex].items = items.filter((i) => i.id !== itemId)

    this.setState({groups})
  }

  addItem(groupId, itemId) {
    // make a copy
    let {groups} = this.state

    const gIndex = groups.findIndex(g => g.id == groupId);
    let items = groups[gIndex].items
    groups[gIndex].items = items.concat({id: itemId})

    this.setState({groups})
  }

Is there any way to write it cleaner?


texts:
I'm learning ASP.NET and think I figured out ViewState. Can you tell me if I have it right?

The goal of the ViewState in this page is simply to keep the value in a DropDownList.

So first, let's have the aspx page markup:

<%@ Page Title="Parameters" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ParamPage.aspx.cs" Inherits="MyCompany.MyProject.WebGUI.ParamPage" %>

...

<asp:DropDownList ID="UserList" runat="server" AutoPostBack="True" Width="125px" OnSelectedIndexChanged="UserList_SelectedIndexChanged"></asp:DropDownList>

In Page_Load, the list is populated:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        BindUserList(); //Just to give an idea
}

I store the selection in a property which uses the ViewState:

protected string SelectedUser
{
    get { return (string)ViewState["SelectedUser"]; }
    set { ViewState["SelectedUser"] = value; }
}

The property is set when the selected index is changed:

protected void UserList_SelectedIndexChanged(object sender, EventArgs e)
{
    if (UserList.SelectedIndex == -1)
        SelectedUser = null;
    else
        SelectedUser = UserList.Text;
}

And I need to override the SaveViewState() and LoadViewState() functions fromPage`:

protected override object SaveViewState()
{
    object baseState = base.SaveViewState();
    string user = UserList.Text;
    return new object[] { baseState, user};
}

protected override void LoadViewState(object savedState)
{
    if (savedState != null)
    {
        object[] stateObjects = (object[])savedState;
        if (stateObjects[0] != null)
            base.LoadViewState(stateObjects[0]);
    }
}

And, in order to re-select the right user, in BindUserList, I do this:

private void BindUserList()
{
    //... get and bind list
    if (UserList.Items.Count > 0)
    {
        var item = UserList.Items.FindByText(SelectedUser);
        if (item != null)
            item.Selected = true;
    }
}

Is this the proper way to use ViewState? Am I missing something that would make this unsafe? Am I doing anything superfluous?


texts: Produce all multiples of a set of primes up to a certain limit

texts:
I have some Python code that generates all possible multiples and combinations of a given set of primes up to a certain limit. The code runs and does exactly what I intend it to do, now I am trying to optimize it in order to improve run-time.

import math
from collections import defaultdict
import itertools

lim = 10**13 #This limit can be changed if you'd like
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47] #So can these primes
res = defaultdict(list)
res[()] = [1] #Maybe not this

for n in range(1, len(primes) + 1):
    for combo in itertools.combinations(primes, n):
        for c in res[combo[:(n - 1)]]:
            stop = int(math.log(lim / c, combo[-1]))
            for x in range(1, stop + 1):
                res[combo[:n]].append(c * combo[-1] ** x)

multiples = []
for key in res:
    multiples += res[key]

multiples.sort()
print(multiples)

If you don't feel like reading through all that, the basic idea is to take increasingly large combinations of the set of primes, starting with a single prime, and computing all the permutations of the subset with increasing powers up to the chosen limit. The way I have it coded, I am initializing the dictionary with an empty tuple that maps to the number 1 as it makes writing the rest of the for loop much easier.

For example: Let's say your list of primes is \$[2,3,5]\$ and your limit is 30. First, it's going to take each number in that list and compute all the powers below 30, storing each in a dictionary key that maps to a list. So, after one loop, you would have:

res = {(): [1], (2):[2,4,8,16], (3):[3,9,27], (5):[5,25]}

The second time through the combinations would be \${2 \choose 3}\$, \${2 \choose 5}\$, and \${3 \choose 5}\$. In each combo, it chops off the last value and searches for the key associated with the remaining part of the tuple.  So for \${2 \choose 3}\$ it will look for the (2) key, i.e. the powers of two, and multiply them by increasing powers of three until they go above thirty.  So you will have:

\${2 \choose 3}\$ = \$[2 \cdot 3, 2 \cdot 9, 4 \cdot 3, 8 \cdot 3]\$ = \$[6, 18, 12, 24]\$

This process continues until you are out of combinations.

For lower limits the code actually runs fairly quickly.  For high limits (\$10^{13}\$, 20 primes) like I have listed above the code runs in about 5 minutes. I would like to get that down to under a minute if possible. I was wondering if I could turn the main for loop into a dictionary comprehension but I'm not sure if that's possible since I've initialized res outside of the main for loop, and need the () = [1] for my code to run.

I am not completely married to this idea, but I do think it's slick (I'm still pretty new to programming so we might have different ideas on what that means), so if I could preserve it that would be nice. Any ideas?


texts:
My Rails app geocodes users' IP when they are created and also when they update their data only if they change their city. The geocoding is slowing down my tests ridiculously.

This seems to me to be a poor way to avoid endless geocoding when running tests but I am unsure of a better way to do this.

   if Rails.env == 'production' || Rails.env == 'development'

       after_save :geocode, if: ->(user){ user.ip_address.present? and user.ip_address_changed? }

   end


texts: Grouping utility methods for View classes

texts:
I have the following class:

public final class ViewUtils {

    public static void setSize(View view, int width, int height) {
        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) view.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        view.requestLayout();
    }

    public static void setWidth(View view, int width) {
        setSize(view, width, view.getHeight());
    }

    public static void setHeight(View view, int height) {
        setSize(view, view.getWidth(), height);
    }

    public static boolean isRightEdgeOfScrollViewHasBeenReached(HorizontalScrollView scrollView) {
        View childView = scrollView.getChildAt(scrollView.getChildCount() - 1);
        return childView.getRight() == (scrollView.getWidth() + scrollView.getScrollX());
    }

    // Other methods will be added later

}

But I don't like the name isRightEdgeOfScrollViewHasBeenReached. I think it would be better if the method name didn't contain word ScrollView but is placed in a class which would be specialized only on the ScrollView.

Should I place this method in an inner class ViewUtils.ScrollView or in a separate class ScrollViewUtils?

I think the first option would be better, because creating a separate class for a few methods (currently only one method) is too "expensive".

And help me choose more appropriate name for the method isRightEdgeOfScrollViewHasBeenReached.

Summarizing the question

The choice is between two options:

To have all methods inside a single class:

public class ViewUtils {

    public static void methodForAllViews1() { }

    public static void methodForAllViews2() { }

    public static void methodForAllViews3() { }

    public static class TextView {

        public static void methodForTextViews1() { }

        public static void methodForTextViews2() { }
    }

    // etc.

}

To separate all methods and to place all util classes in the same package:

- utils
    - view
        * ViewUtils.java
        * TextViewUtils.java
        * ScrollViewUtils.java


texts:
I am working with some wireless communication in Arduino. My data will be wirelessly received like so:

97
97
97
...
...

979797 is the address of the transmitter. I have written the following code to check the address first before processing the data. My main concern is speed of computation.

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i]); //remove the print in binary option to decode
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
  {
    serialBuffer[startPosition] = value;
    startPosition++;
  }

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //check for start key
    address(RX.read())
    //process data
    processBytes(RX.read());
  }
}
void address(const uint8_t value)
{
  int counter = 0;
  int newVal = value;
  while(value == 97 && counter < 3)
  {
    counter++;
    newVal = RX.read();
  }
}

EDIT:
The data packet just has the following components: start key (979797) and 68 bytes of data. There is no termination key. Also, the transmitter transmits one byte at a time. Thus, each value received is less than 256. Hence why I am saving the data into a uint8_t[] array.

Other than the address() method, most of it was borrowed from Gammon. Here is the reference page for the arduino commands I am using. Are there ways I can optimize this computation?


texts: Compare JS files and pick according to requirement

texts:
Problem Statement:

Extract the filename and read if filename has jQuery on it, put them aside.
Second step will be to check one more and see if any jQuery files has ui in the filename.

Input:

script_ref1 = """<script type="text/javascript" src="js/jquery-1.9.1.min.js"/>
    <script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"/>
    <script type="text/javascript" src="js/jquery-ui.min.js"/>
    <script type="text/javascript" src="js/abc_bsub.js"/>
    <script type="text/javascript" src="js/abc_core.js"/>
    <script type="text/javascript" src="js/abc_explore.js"/>
    <script type="text/javascript" src="js/abc_qaa.js"/>"""

OR

script_ref2 = """<script type="text/javascript" src="js/jquery-1.9.1.min.js"/>
    <script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"/>
    <script type="text/javascript" src="js/abc_bsub.js"/>
    <script type="text/javascript" src="js/abc_core.js"/>
    <script type="text/javascript" src="js/abc_explore.js"/>
    <script type="text/javascript" src="js/abc_qaa.js"/>"""

And:

div_attr_info = {"data-js":"jquery-1.8.1.min.js, jquery-ui-1.2.min.js, custom1.js, custom2.js"}

Output:

for script_ref1

doc_js: [' custom1.js', ' custom2.js']

for script_ref2

doc_js: [' jquery-ui-1.2.min.js', ' custom1.js', ' custom2.js']

Algorithm:

Set jquery_flag and jquery_ui_flag flag to False.
Extracting specific src attributes from script tags.
Iterate on step2 result.
Set jquery_flag to True because jquery is substring in the file list.
Check ui is substring or not. and set jquery_ui_flag according to it.
Get JS file list from the dictionary for comparison.
Iterate and Do comparison.
Print result.

Can the code be improved or optimized? Can I reduce the runtime?

jquery_flag = False
jquery_ui_flag = False
for ii in re.findall('src="js/([^"]*jquery[^"]*)"', script_ref):
    jquery_flag = True
    if "ui" in ii:
        jquery_ui_flag = True

tmp = div_attr_info["data-js"].split(",")
doc_js = []

for ii in tmp:
    if jquery_ui_flag and "jquery" in ii:
        pass
    elif jquery_flag and not jquery_ui_flag and "jquery" in ii and "ui" not in ii:
        pass
    else:
        doc_js.append(ii)

print "doc_js:", doc_js


texts:
I have this task to find whether 5 integers are ordered from the smallest to the largest or not.

Depending on the results, the program output should be "yes" or "no". No loops or arrays supposed to be used (according to the task).
This is my solution, but it's 4 lines longer. Can anyone help me make this better?

int main() {
    int a, b, c, d, e;

    scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

    if ( a < b && b < c ) {
        if ( c < d && d < e ) {
            printf("yes");
        } else {
            printf("no");
        }
    } else {
        printf("no");
    }

    return 0;
}


texts:
Is it safe to upload images via MySQL in Blob? I've constructed my code like the following:

    public function upload_avatar($file, $user_id = false, $maxbytes = 102400) {
    global $sql;
    if($user_id == false) {
        $user_id = $this->_id;
    }
    $check = getimagesize($file);
    if($check == false) {
        return false;
    }
    $width = $check[0];
    $height = $check[1];
    if($width > 300) {
        return false;
    }
    if($height > 300) {
        return false;
    }
    $fp = fopen($file, 'rb');
    if(strlen($file) < $maxbytes) {
        $q = $sql->prepare("UPDATE `users` SET `avatar` = :file WHERE id = :user_id;");
        try {
            $q->bindParam(':file', $fp, PDO::PARAM_LOB);
            $q->bindParam(':user_id', $user_id);
            $q->execute();
        }
        catch(PDOException $e) {
            die($e->getMessage());
        }
        return true;
    } else {
        return false;
    }
}

Is it possible for a hacker to upload viruses via this script?


texts: Test Driven Development, Mocking & Unit-testing

texts:
I have the below code which is still under development - but I'm trying to get myself to find the ideal way to move forward.

public interface IMemberSubscriptionService
{
    void SelectSubscription(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrderPaidWith);
    IMemberSubscriptionRenewal GetCurrentApplicableRenewal(IMember member);

}

public class MemberSubscriptionService : IMemberSubscriptionService
{
    private readonly IMemberSubscriptionRenewalService memberSubscriptionRenewalService;
    public MemberSubscriptionService(IMemberSubscriptionRenewalService memberSubscriptionRenewalService)
    {
        this.memberSubscriptionRenewalService = memberSubscriptionRenewalService;
    }

    public void SelectSubscription(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrderPaidWith)
    {
        var renewal = GetCurrentApplicableRenewal(member);
        if (renewal == null || !object.Equals(renewal.Subscription, subscription))
        {//if they are different

            if (renewal != null)
            {
                updateRenewalDateToEndAsOfYesterday(renewal);
            }
            var newRenewal = createFirstSubscriptionRenewal(member, subscription, linkedOrderPaidWith);
            memberSubscriptionRenewalService.Renew(newRenewal);
        }

    }

    private IMemberSubscriptionRenewal createFirstSubscriptionRenewal(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrder)
    {
        IMemberSubscriptionRenewal renewal = member.SubscriptionRenewals.CreateNewItem();
        renewal.StartDate = CS.General_v3.Util.Date.Now.Date;
        renewal.EndDate = CS.General_v3.Util.Date.GetEndOfDay(PayMammoth.Connector.Util.GeneralUtil.GetDateTimeAfterIncrementingBillingPeriod(renewal.StartDate,
            subscription.DurationIntervalType,subscription.DurationInDays).AddDays(-1));
        renewal.LinkedOrder = linkedOrder;
        renewal.Save();
        return renewal;

    }

    private void updateRenewalDateToEndAsOfYesterday(IMemberSubscriptionRenewal renewal)
    {
        renewal.EndDate = CS.General_v3.Util.Date.Now.AddDays(-1);

    }

    #region IMemberSubscriptionService Members

    public IMemberSubscriptionRenewal GetCurrentApplicableRenewal(IMember member)
    {
        throw new NotImplementedException();
    }

    #endregion
}

What this code should do is 'select a subscription' (SelectSubscription) for a particular member.  A member has a list of SubscriptionRenewals which basically contain information for each period of a subscription, e.g taking a monthly subscription would have a SubscriptionRenewal for Jan 2012, another for Feb 2012, etc.

The SelectSubscription should get the current subscription, and if the subscription is to be changed, the existing renewal is updated to end as of yesterday, and the new subscription starts from today, for the total period (e.g changing from monthly to yearly).  If you have a SubscriptionRenewal from 1 - 29 Feb 2012, and today is 15 Feb and you call 'SelectSubscription' with a yearly interval, this should change the existing SubscriptionRenewal to end on 14Feb 2012, and create a new one from 15 Feb 2012 till 14 Feb 2013 for this particular case.

This is just to give you an idea of the functionality.  I need to create the respective unit tests for such a functionality, and came out with several scenarios, as per below:

if subscription is the same as the current, do nothing.
if a current subscription renewal exists, it is updated to end as of yesterday
test that SelectSubscription creates new renewal is created, based on today and the subscription

My main issue is on how to structure the code for unit-testing.  Should you create the GetCurrentApplicableRenewal as part of the same service?  This way, I cannot simply mock that functionality, when I am testing out a portion of the SelectSubscription.  Does it make sense to take that functionality out into a different interface/class, so that it can be mocked?