texts: optimizing conversion between string and date

texts:
I was wondering if there was a more efficient way of taking strings that represent dates with the pattern being mmddyy or mmd yy or m d yy and converting them into a DateTime object?

111110 would be 11 11 10

111 10 would be 11 1 10

1 1 10 would be 1 1 10

The spaces are either ' ' or '\0' (the input I am given is not very clean)

This is what I have so far, which works for all cases.

//Converts a given input string into a valid date
private DateTime convertToDateFromString(string dateString)
{
  int length = dateString.Length;
  int month = 1;
  int day = 1;
  int year = 1;
  bool gotMonth = false;
  bool gotDay = false;
  bool gotYear = false;
  char c = ' ';
  char peek = ' ';
  string buffer = "";
  DateTime bufferDate;
  int count = 0;

  try
  {
    for (int i = 0; i < dateString.Length; i++)
    {
      c = dateString[i];
      if ((i + 1) < dateString.Length)
        peek = dateString[i + 1];
      else
        peek = '\0';

      if (c != ' ' && c != '\0')
      {
        buffer += c;
        count++;
        if ((peek == ' ' || peek == '\0' || count == 2) && gotMonth == false)
        {
          count = 0;
          gotMonth = true;
          month = int.Parse(buffer);
          buffer = null;
        }
        else if ((peek == ' ' || peek == '\0' || count == 2) && gotDay == false && gotMonth == true)
        {
          count = 0;
          gotDay = true;
          day = int.Parse(buffer);
          buffer = null;
        }
        else if ((peek == ' ' || peek == '\0' || count == 2) && gotYear == false && gotMonth == true && gotDay == true)
        {
          count = 0;
          gotYear = true;
          year = int.Parse(buffer);
          buffer = null;

          if (year >= 80 && year <= 99)
            year += 1900;
          else if (year >= 0 && year <= 79)
            year += 2000;
        }
      }
    }
    bufferDate = new DateTime(year, month, day);
  }
  catch (System.Exception ex)
  {
    bufferDate = new DateTime(1, 1, 1);
  }

  return bufferDate;
}


texts: Maximum distance between space stations HackerRank

texts:
I am just working on Flatland Space Stations problem, and it is not seeming to be a tough question, but my algorithm lags in some aspects, since it solves majority of the test cases but fails for some. Which is causing me not to move forward.

The cause of the failure is timeout only, no wrong output.

My Algo:

To loop through the number of cities
Loop through the cities which has the space stations
Store the minimum distance in the array or dict for that particular city
Find out the maximum distance stores in the array of difference between n cities

I have written two codes based upon the following Algo:

1. With the use of Dictionary: Time out for three cases

def flatlandSpaceStations(n, c):
    # n is the number of cities
    # c is the array of space station exists in the city(s)
    cityDiff = {}
    maxDiff = 0
    if n == len(c):
        return 0
    else:
        for i in range(n):
            lst = []
            for j in c:
                lst.append(abs(i-j))
                cityDiff[i] = min(lst)

    for key, value in cityDiff.items():
        if value > maxDiff: maxDiff = value

    return maxDiff

2. Using lists in Python: Failed two cases in Timeout only

def flatlandSpaceStations(n, c):
    # n is the number of cities
    # c is the array of space station exists in the city(s)
    maxDiff = []
    if n == len(c):
        return 0
    else:
        for i in range(n):
            minDis = []
            for j in c:
                minDis.append(abs(i-j))
            maxDiff.append(min(minDis))
    return max(maxDiff)

I want to find some optimum solution, which I can understand. The above programs have a very bad time complexity I know, but this is only solution I can think of right now. Any help would be appreciated.

As per vnp's suggestion, I have made another attempt, and made the solution optimized, but it is not working out for the Two test cases due to timeout issue.

Solution \$O(n^2)\$:

def flatlandSpaceStations(n, c):
    # n is the number of cities
    # c is the array of space station exists in the city(s)
    maxDiff = []
    if n == len(c):
        return 0
    else:
        for i in range(n):
            minVal = float('inf')
            for j in c:
                if abs(i-j) < minVal: minVal = abs(i-j)
            maxDiff.append(minVal)
    return max(maxDiff)

I am attaching one of the two time out failure test case here for more insight.

TEST CASE


texts: Solution for Parent/Child circular references: WeakReference class

texts:
Sometimes in advanced OOP scenarios, a class needs to hold instances of another class which needs to hold a reference to the "parent". For example when you have a dynamic UserForm control that needs to "call back" to the parent form that created it, or when you have a ViewAdapter that talks to some UI, which in turn needs to "call back" to the adapter.

Such relationships create circular references, and if nothing is done to solve this, the objects don't get cleaned up and you're looking at what's essentially a memory leak.

With the help of Comintern I've written a class that solves this problem, and called it WeakReference - in order to make the API as simple to use as possible, I wrapped it with an IWeakReference interface:

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "IWeakReference"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Option Explicit

Public Property Get Object() As Object
End Property

Here's the WeakReference class:

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "WeakReference"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Implements IWeakReference

#If Win64 Then
Private Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As LongPtr)
#Else
Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
#End If

Private Type TReference
    Address As Long
End Type

Private this As TReference

Public Function Create(ByVal instance As Object) As IWeakReference
    With New WeakReference
        .Address = ObjPtr(instance)
        Set Create = .Self
    End With
End Function

Public Property Get Self() As IWeakReference
    Set Self = Me
End Property

Public Property Get Address() As Long
    Address = this.Address
End Property

Public Property Let Address(ByVal value As Long)
    this.Address = value
End Property

Private Property Get IWeakReference_Object() As Object
    ' Bruce McKinney's code for getting an Object from the object pointer:
    Dim objT As Object
    CopyMemory objT, this.Address, 4
    Set IWeakReference_Object = objT
    CopyMemory objT, 0&, 4
End Property

Can this class be improved? Is the interface & factory method overkill?

Here's a simple example usage scenario:

Class: TheParent

Option Explicit

Private child As TheChild

Private Sub Class_Initialize()
    Set child = New TheChild
    Set child.Parent = Me
End Sub

Private Sub Class_Terminate()
    Set child = Nothing
End Sub

And the TheChild class:

Option Explicit

Private ref As IWeakReference

Public Property Get Parent() As TheParent
    Set Parent = ref.Object
End Property

Public Property Set Parent(ByVal value As TheParent)
    Set ref = WeakReference.Create(value)
End Property

Private Sub Class_Terminate()
    Stop ' expected break here when TheParent is terminated
    Set ref = Nothing
End Sub

And a little procedure to test everything:

Public Sub Test()
    Dim p As TheParent
    Set p = New TheParent
    Debug.Print ObjPtr(p)
    Set p = Nothing
End Sub

As expected, the Stop statement is hit in TheChild, and if you put a breakpoint in TheParent's Class_Terminate handler, it's also hit - whereas if you replace the IWeakReference with TheParent in TheChild, none of the two Class_Terminate handlers run.


texts:
That's an easy one. I just want to calculate the Hamming distance between two strings.

function hamming(str1,str2)
  local distance = 0

  -- cannot calculate Hamming distance if strings have different sizes
  if #str1 ~= #str2 then return false end

  for i = 1, #str1 do
    if str1:sub(i,i) ~= str2:sub(i,i) then
      distance = distance + 1
    end
  end

  return distance
end

Maybe the for-loop isn't the most efficient one. I'm not sure. Any improvements?


texts: Using Nokogiri to scrape Oscars winners from Wikipedia

texts:
I am scraping a Wikipedia page, getting info from that page and instantiating a new object with the information collected:

require_relative '../config/environment'

def get_winner
    award = Nokogiri::HTML(open("http://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture"))
    year = nil
    award.css('table.wikitable').each do |table|
        @year = winning_year(table).join("")
        winner_name =  winner_title(table)
        url_extention = table.css('td a').first.attr('href')
        winner_page = Nokogiri::HTML(open("http://en.wikipedia.org#{url_extention}"))
         budget = "N/A"
         winner_page.css('.vevent tr').each do |node|
           if node.text.include?('Budget')
             budget = format_budget(node.css('td').text)
           end
         end
         AcademyAwardBestPicture.new(@year,winner_name,budget)
    end
end

def winning_year(table)
    table.css('caption big').map do |a_tag|
        if a_tag.text.include?('[')
            a_tag.text.split('[').first
        else
            a_tag.text
        end
    end
end

def winner_title(table)
    table.css('td a').first.text
end

def format_budget(budget_money)
    formated_number = nil
    if budget_money.include?("-")
        budget_money = budget_money.split("-").first + " million"
    elsif budget_money.include?("–")
        budget_money = budget_money.split("–").first + " million"
    end
        budget_money.scan(/[\$£](\d{1,3}(,\d{3})*(\.\d*)?)( million)?/).each do |m|
          number = m[0].gsub(',', '').to_f
          unit = m[3]
          multiplier = 1
            if number == 55.0
                multiplier = 1e6
            end
              if unit == ' million'
                multiplier = 1e6
              end
            formated_number = number * multiplier
                if budget_money.include?("£")
                    formated_number = british_pound_currency_convert(formated_number)
                end
            end
        formated_number
end

def british_pound_currency_convert(amount)
    web_page = Nokogiri::HTML(open('http://measuringworth.com/datasets/exchangeglobal/result.php?year_source=1791&year_result=2007&countryE%5B%5D=United+Kingdom'))
        exchange_rate_table = web_page.css('table').last
        exchange_rate_cell = exchange_rate_table.css('tr')
        formated_amount = nil
        exchange_rate_cell.each do |cell|
            if @year == cell.children[0].text
                one_dollar_to_pound_rate = cell.children[1].text.gsub(/[^0.-9]/,'').to_f
                formated_amount = (amount / one_dollar_to_pound_rate).round(0)
            elsif @year == "2010"
                exchange_rate_2010 = 1.561
                formated_amount = (amount * exchange_rate_2010).round(0)
            end
        end
        formated_amount
end

The code is pretty slow, which takes about 13 seconds to scrape 87 "award winning best picture". Does anybody have suggestions on how to make it faster/ more robust?


texts:
In my code below I have restructured the following csv file from something like this:

date,type
2017-01,E
2017-01,E
2017-01,E
2017-01,U

To this:

{date: "2017-01", E: 3, U: 1}

Using d3.nest() with a rollup method.

The only thing is that I'm mapping out the type values somewhat manually like this:

var lineData = nestData.map(function(d) {
  return {date: d.key, E: d.values[0].value, U: d.values[1].value};
});

always expecting the types to be in order. I do this by simply sorting the data by type and then re-sort by date again.

What I basically want to know is if there's a better way of achieving this or if there's a step or two that I can omit from the code making it more efficient.

Here's all the code:

var csvData =
`date,type
2017-01,E
2017-01,E
2017-01,E
2017-01,U
2017-01,U
2017-02,E
2017-02,E
2017-02,U
2017-02,U
2017-02,U
2017-03,U
2017-03,U
2017-03,E
2017-03,E
2017-03,E
2017-03,E`;

var durations = 0;

var parseTime = d3.timeParse("%Y-%m");

var margin = {top: 25, right: 25, bottom: 25, left: 25},
    width = 420 - margin.left - margin.right,
    height = 185 - margin.top - margin.bottom;

var g = d3.select("#chart").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleTime().range([0, width]),
    y = d3.scaleLinear().range([height, 0]),
    z = d3.scaleOrdinal(d3.schemeCategory10);

var xAxis = d3.axisBottom(x)
    .tickFormat(d3.timeFormat("%B"))
    .ticks(3);

var yAxis = d3.axisLeft(y).ticks(4);

var line = d3.line()
    .curve(d3.curveCardinal)
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.lines); });

g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")");

g.append("g")
    .attr("class", "axis axis--y");

var data = d3.csvParse(csvData, function(d) {
  d.date = d.date;
  d.type = d.type
  return d;
}).sort((a, b) => a.type - b.type)

  var nestData = d3.nest()
    .key(d => d.date)
    .key(d => d.type)
    .rollup(leaves => leaves.length)
    .entries(data);

  console.log("Nested: ", nestData)

  var lineData = nestData.map(function(d) {
    return {date: d.key, E: d.values[0].value, U: d.values[1].value};
  });

  lineData.forEach(function(d) {
    d.date = parseTime(d.date);
  })

  lineData.sort((a, b) => a.date - b.date)

  console.log("Mapped: ", lineData)

  parsed(lineData);

  function parsed(dataTest) {

    var keys = ["E","U"]

    var newData = keys.map(function(id) {
      return {
        id: id,
        values: dataTest.map(function(d) {
          return {date: d.date, lines: d[id]};
        })
      };
    });

    console.log("Mapped w/key: ", newData)

    z.domain(newData.map(function(c) { return c.id; }));

    var max = d3.max(dataTest, d => d3.max([d.E, d.U]));

    y.domain([0, max]).nice();

    x.domain(d3.extent(dataTest, d => d.date));

    g.selectAll(".axis.axis--y").transition()
      .duration(durations)
      .call(yAxis);

    g.selectAll(".axis.axis--x").transition()
        .duration(durations)
        .call(xAxis);

    var lineValues = g.selectAll(".lineValues")
      .data(newData);

    lineValues = lineValues
      .enter()
    .append("path")
      .attr("class", "line lineValues")
      .style("stroke", function(d) { return z(d.id); })
      .merge(lineValues);

    lineValues.transition()
      .duration(durations)
      .attr("d", function(d) { return line(d.values) })

  }
.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

<meta charset ="utf-8">


texts:
This is the Substring Game! challenge from HackerEarth:

  Watson gives Sherlock a string (let's denote it by S). Watson calculates all the substrings of S in his favourite order.

  According to the Watson's favourite order, all the substrings starting from first character of the string will occur first in the sorted order of their length, followed by all the substrings starting from the second character of the string in the sorted order of their length, and so on.

  For example, suppose S = abc. Then, all the substrings of S as per Watson's favourite order are:

  a
  ab
  abc
  b
  bc
  c

  Watson will ask Sherlock 'q' questions. In each question, Watson will give Sherlock a number and Sherlock has to speak the substring on that number. If there is no possible substring, then Sherlock has to speak -1.

Can the below code be improved to run in \$o(n^2)\$ complexity?

str=raw_input()
q=int(raw_input())
num=raw_input().split(' ')
substr=[]
for i,s in enumerate(str):
    #print i,s
    for j in range(i+1,len(str)+1):
        #print j
        substr.append(s+str[i+1:j])
#print substr
for i in range(0,q):
    try:
       print substr[int(num[i])-1]
    except IndexError:
       print -1

Sample Input
First line is the string - abc
Second line is the number of substrings asked- 2
Third line is the position of the substrings to return from the list of substrings- 2 5

The list of substrings would be ['a','ab','abc','b','bc','c']
Sample Output
ab
bc


texts:
As I wrote on SO, I need an ArrayList-like structure allowing just the following operations

get(int index)
add(E element)
set(int index, E element)
iterator()

while supporting iterations concurrent with modifications. While I'm waiting for something better, I tried it myself. It was a bit harder than expected, so I used synchronization, which made it easy again. I'm linking to the full code and the test and showing here the relevant part (i.e., everything but the imports).

/**
 * A data structure implementing a tiny subset of List operations and allowing concurrent access.
 *
 * See https://stackoverflow.com/q/26424030/581205 for requirements.
 */
public class ConcurrentIterable<E> implements Iterable<E> {
    class MyIterator extends UnmodifiableIterator<E> {
        @Override public boolean hasNext() {
            return index < size();
        }

        @Override public E next() {
            try {
                return get(index++); // Safe as the array never shrinks.
            } catch (final IndexOutOfBoundsException e) {
                // This is hacky, but better than checking the size upfront, as the size may change.
                throw new NoSuchElementException();
            }
        }

        private int index;
    }

    /**
     * The returned iterator may or may not see the changes made after its creation.
     * The only guarantee in case of concurrent modifications is is that
     * it sees no garbage provided that the items are immutable.
     */
    @Override public Iterator<E> iterator() {
        return new MyIterator();
    }

    public synchronized int size() {
        return size;
    }

    @SuppressWarnings("unchecked")
    public synchronized E get(int index) {
        checkElementIndex(index, size);
        return (E) data[index];
    }

    public synchronized void add(E element) {
        if (data.length == size) grow();
        data[size++] = element;
    }

    public synchronized void set(int index, E element) {
        checkElementIndex(index, size);
        data[index] = element;
    }

    private void grow() {
        data = Arrays.copyOf(data, newSize(data.length));
    }

    private static int newSize(int oldSize) {
        int result = oldSize + (oldSize>>3) + 4; // Grow by about 1/8 only.
        if (result-MAX_ARRAY_SIZE > 0) result = MAX_ARRAY_SIZE; // Handle overflow.
        if (result<=oldSize) throw new OutOfMemoryError();
        return result;
    }

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // See ArrayList.

    private int size;
    private Object[] data = new Object[4];
}

I'm aware that it's incompatible with the Collection or List interfaces, but it's not meant to be general use class (though it may change). I need no additional constructors or other features.

Concerning spacing and single line conditional statements... yes, I know, I just don't care (my own conventions differ slightly).

I'll probably try to re-implement this without synchronization as a challenge.


texts: Calculate min, max, mean and median out of array Version 2

texts:
This question is a follow up of:
Calculate min, max, mean and median out of array

I took all the suggestions an reworked the code. Like the description of the excercise suggests i only use one function for all the computations. Also with the sorting the max and median values can now be calculated easier.

I wonder if its good to return the Macro types INT_MIN INT_MAX and NAN for indicating no valid result?

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

struct Summary_data {
    long long smallest;
    long long largest;
    double median;
    double mean;
};

static inline int cmp(void const *lhs, void const *rhs) {
    const int *left = (const int *)lhs;
    const int *right = (const int *)rhs;
    return (*left > *right) - (*left < *right);
}

int* intdup(const int * source, const size_t len)
{
    assert(source);

    int * p = malloc(len * sizeof(*source));

    if (p == NULL)
        exit(1);

    memcpy(p, source, len * sizeof(*source));
    return p;
}

struct Summary_data calculate_values(const int* array, const size_t len)
{
    assert(array);

    struct Summary_data summary_data = { 0 };
    int* calc_array = intdup(array, len);
    size_t i;

    if (len <= 0) {             // dont bother to calc if invalid len
        free(calc_array);
        calc_array = NULL;
        summary_data.smallest = INT_MAX;
        summary_data.largest = INT_MIN;
        summary_data.mean = NAN;
        summary_data.median = NAN;
        return summary_data;
    }

    qsort(calc_array, len, sizeof *array, cmp);

    summary_data.smallest = calc_array[0];
    summary_data.largest = calc_array[len - 1];

    for (i = 0; i < len; ++i) {
        summary_data.mean += calc_array[i];
    }
    summary_data.mean /= len;

    if (len % 2 == 0) { // is even == return the arithmetic middle of the two middle values
        summary_data.median = (calc_array[(len - 1) / 2] + calc_array[len / 2]) / 2.0;
    }
    else {  // is odd  == retunr the middle
        summary_data.median = calc_array[len / 2];
    }

    free(calc_array);
    calc_array = NULL;

    return summary_data;
}

void print_result(const struct Summary_data* summary_data)
{
    assert(summary_data);

    printf("smallest: %i\n", summary_data->smallest);
    printf("largest: %i\n", summary_data->largest);
    printf("median: %g\n", summary_data->median);
    printf("mean: %g\n\n", summary_data->mean);
}

int main()
{
    int test_array[] = { 1,7,3,4,5,6,7,8,9 };       // 9 elements
    //  int test_array[] = { 1,7,3,4,5,6,7,8 };         // 8 elements

    int len = sizeof(test_array) / sizeof(test_array[0]);

    //len = 0;                                          // test when len is invalid
    struct Summary_data summary_data = calculate_values(test_array, len);

    print_result(&summary_data);
    getchar();
    return 0;
}


texts:
I'm doing a program in Delphi, writing in all kinds of files, either text or executable:

var
  openfile: TextFile;
begin
      AssignFile(openfile, 'test.exe');
      Append(openfile);
      WriteLn(openfile,'[test]hi world[test]');
      CloseFile(openfile);
end;

How can I improve this?


texts: Count bits that differ between integers X and Y

texts:
I'm trying to solve the following problem :

  You are given two integers, X and Y.  Calculate the number of bits that will be changed in order to convert integer X to integer Y.

Here is my solution

function findNumberOfBits(x, y){
    var bitCount = 0;
    var z = x ^ y;  //XOR x and y
        while (z !== 0){
          bitCount += z & 1;
          z = z >> 1;  //shift Z by 1 bit to the right
          //console.log("bitCount ", bitCount);
          //console.log(z);
         }
    return bitCount;
}

var result = findNumberOfBits(12, 16);

Is this correct? My tests seem to say yes, but just to make sure.
Is this the most efficient way to write it in JavaScript?


texts: Autofiltering and deleting rows two times too slow

texts:
For Each MyIndex In Worksheets
        If MyIndex.Name = "Inv_IB" Or MyIndex.Name = "Inv_MP"
            With Sheets(MyIndex.Name)
                nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
                Set dataRng = .Range("A2", .Range("N" & nFilasActual))
                dataRng.Sort key1:=Range("E2"), order1:=xlAscending
                dataRng.AutoFilter Field:=5, Criteria1:="<>ME"
                Application.DisplayAlerts = False
                dataRng.Offset(1, 0).Resize(dataRng.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
                Application.DisplayAlerts = True
                .ShowAllData
                nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
                Set dataRng = .Range("A2", .Range("N" & nFilasActual))
                dataRng.Sort key1:=Range("C2"), order1:=xlAscending
                dataRng.AutoFilter Field:=3, Criteria1:="<>BODEGA IND"
                Application.DisplayAlerts = False
                dataRng.Offset(1, 0).Resize(dataRng.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
                Application.DisplayAlerts = True
                .ShowAllData
                nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
                dataRng.Sort key1:=Range("H2"), order1:=xlAscending
                .Range("A2:A" & nFilasActual).FormulaR1C1 = "=IF(RC[2]<>R[-1]C[2],1,IF(RC[6]=R[-1]C[6],R[-1]C,R[-1]C+1))"
                .Range("O2").FormulaR1C1 = "=1"
                .Range("O3:O" & nFilasActual).FormulaR1C1 = "=R[-1]C + 1"

            End With
        End If
Next MyIndex

I'm saving info on these 2 sheets from another WorkBook. Then I want to filter this and delete the rest of the info. This is taking too long for what I want. Any ideas for how I can speed this up?


texts: AlwaysUpdate attribute for Entity Framework Code First POCO

texts:
The entity framework will only save properties it detects has changed via its proxy classes.  I have a situation where I want a property to always be saved no matter if it changed or not.

I wrote a blank attribute called AlwaysUpdate which I apply to the property.  I then overrode SaveChanges to scan for these attributes and mark the field as Modified.  Is this code all right?

public override int SaveChanges()
{
    var changeSet = ChangeTracker.Entries();
    if (changeSet != null)
    {
        foreach (var entry in changeSet.Where( c=> c.State == System.Data.EntityState.Modified ))
        {
            foreach (var prop in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(AlwaysUpdateAttribute), true).Count() > 0).Select( p => p.Name ))
            {
                if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Unchanged) continue;
                // Try catch removes the errors for detached and unchanged items
                try
                {
                    entry.Property(prop).IsModified = true;
                }
                catch { }
            }
        }
    }
    return base.SaveChanges();
}


texts: Application for allowing a user to "follow" another user

texts:
I have taken a stab at creating my first jQuery script from scratch. I use this to post an update to a Django application that allows a user to "follow" another user. I am sure that there are better ways to do this and I appreciate any help that anyone can give.

<script type="text/javascript">
jQuery(function() {
    jQuery('.follow').click(function(event) {
        event.preventDefault();
        var url = jQuery(this).attr("href");
        var followtype = jQuery(this).text();
        var user = jQuery(".follow").attr("href").match('/relationships/[a-z]+/([a-z]+)/following/')[1];
        var postdata = {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        }
        jQuery.post(url, postdata, function(json){
            if(json.result == '1') {
                if(followtype == 'Follow') {
                    jQuery('.follow').text('Unfollow');
                    jQuery('.follow').attr("href", '/relationships/remove/'+user+'/following/');
                } else {
                    jQuery('.follow').text('Follow');
                    jQuery('.follow').attr("href", '/relationships/add/'+user+'/following/');
                }
            }
        })
    });
});
</script>


texts:
This code calculates, from a list of integers, the next fibonacci number for each integer. It does this for the first 60 numbers in the sequence. Any pointers on improving computing time, code readability, etc. are what I'm looking for.

def getFib(limit):
    a = 1
    b = 1
    res = [a, b]

    for i in range(1, limit):
        temp = a
        a = b
        b = temp + b
        res.append(b)
    return res

def nextFibonacci(fib, n):

    for x in n:
        if x < 1 or x > fib[len(fib)-1]:
            print("Value is out of range.")
        else:
            temp = x

            for c in fib:
                if c > temp:
                    temp = c
                    break

                print(temp)

def main():
    listMe = [1, 9, 22]
    fib = getFib(60)

    nextFibonacci(fib, listMe)

if __name__ == "__main__":
    main()


texts: Recursive JavaScript permutations function

texts:
I have a recursive function that calculates the permutations of a given list/array list. Although a similar implementation works great in Python, this JavaScript implementation cannot handle a list of more than 7 elements before its webpage kills it.
I realise this is a natural effect of the recursion, but I am only making \$n\$ recursive calls for a list of size \$n\$. Is there any JavaScript performance magic that could be used to save this function, even if only for a handful more cases?
function permute(list) {
    if (list.length == 1) { return [list] }
    let permutations = []
    let subpermutations = permute(list.slice(1, list.length))
    for (index in subpermutations) {
        let sublist = subpermutations[index]
        for (let pos = 0; pos < sublist.length+1; pos++) {
             permutations.push(sublist.slice(0, pos)
                         .concat([list[0]])
                         .concat(sublist.slice(pos, sublist.length)));
        }
     }
     return permutations;
}


texts:
Is there a neater way of handling the option response from req.cookie() in this code block (line 3 onwards)? Id like to avoid the nested if statements, and multiple returns if at all possible. req.cookie() returns an Option<Cookie> and the Cookie struct has a value function. If the cookie is present but has the wrong value, i want to return a bad request, however i also want to return a bad request if the cookie is not present at all. If the cookie value is OK, i want to continue and do further work:
#[get("/callback")]
async fn callback(req: HttpRequest, client: web::Data<BasicClient>, web::Query(cb): web::Query<Callback>) -> Result<HttpResponse> {
    if let Some(state_cookie) = req.cookie(STATE_COOKIE_NAME) {
        if state_cookie.value() != cb.state {
            return Ok(HttpResponse::BadRequest().finish())
        }
    } else {
        return Ok(HttpResponse::BadRequest().finish())
    }

    let token_result = client.exchange_code(AuthorizationCode::new(cb.code)).request(http_client);

    return match token_result {
        Ok(token_details) => Ok(handle_success(token_details)),
        Err(token_error) => Ok(handle_error(token_error))
    }
}


texts: Reduce an X/Y Value to an Index In a 1D array and Return the Array Value

texts:
Initially, this is not an attempt at early optimization, though it's thoroughly possible I'm looking in the wrong place :).
The following function returns a height value for aliased columns in a kind of voxel-style height-map renderer.
It is called many, many times for both AI and player controlled entities and used for collision detection. It is not being called unnecessarily, by any entities that are static by nature. So, it's really a question of whether there are any tricky operations I'm missing that could allow the interpreter to better JIT-compile my code.
Please assume that 'mapcol' is an array of [0,255] Numbers with a length of mapscalex*mapscalez. The map dimensions may actually be quite a bit bigger than is suggested here; relevant only because I think any memoization would flood RAM.
I've made my best attempt to sanitize this code for brevity. It naturally references variables that are necessarily augmented on level-load, here represented as simple globals.
var mapscalex = 256;
var mapscalez = 256;
var tilescale = 16;
var tilescaley = 4;

//Returns the Y value for a pair of X/Zs
function getmapheight(x,z){
      //Drop the coordinate to the map scale
      x = x/tilescale;
      z = z/tilescale;

      //Clamp the coordinate to the map dims
      x = Math.min(mapscalex-1,Math.max(0,Math.floor(x)));
      z = Math.min(mapscalez-1,Math.max(0,Math.floor(z)));

      //Project the 2D coord into a 1D coord for map sampling,--
      //and then return the map value scaled into world coordinates
      return(mapcol[(x+z*mapscalex)]*tilescaley);
}


texts:
I'm starting to reuse this pattern, and was wondering if there was a more succinct/clear way to write it.

Given a function foo taking a callback argument:

function foo(..., cb) { ... }

And function bar which calls foo with several different arguments taking a callback function of its own to be called when all the 'dependent' callbacks have been called, I write:

function bar(data, cb) {
    var promises = [];
    function createPromise() {
         var p = $.Deferred();
         promises.push(p);
         return function() { p.resolve(); };
    };
    for (var i = 0; i < data.length; i++) {
         foo(data[i], createPromise());
    }
    $.when.apply($, promises).then(cb);
}

I'm quite happy with the pattern, but the apply and closure-returning-a-function make me suspect that there might be a simpler way of doing the same... Ideas?


texts: pattern for validating an object against some condition

texts:
I have an object that's generated from an incoming json string. The string is deserialized in a custom converter that returns an object. This object has a method called IsValidForDB that checks if the properties are valid. This method looks like this:

public class MyObject
{
   public bool IsValidForDB()
   {
      if (this.SomeProperty != SomeCondition)
      {
          return false;
      }

      if (this.SomeOtherProperty != SomeOtherCondition)
      {
          return false;
      }
      ....... several other conditions

      return true;
   }
}

My question is this: is this pattern a good way of validating an object's properties?


texts:
There is a lot of code duplication because it generates hashes using multiple cryptographic hash algorithms.

How can I improve this code?

package main;
import java.util.Scanner;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class String_Hash_Generator {
    public static void main(String args[]) throws NoSuchAlgorithmException {
        Scanner inputScanner = new Scanner(System.in);
        System.out.print("String: ");
        String input = inputScanner.next();

        /* MD2 */
        MessageDigest objMD2 = MessageDigest.getInstance("MD2");
        byte[] bytMD2 = objMD2.digest(input.getBytes());
        BigInteger intNumMD2 = new BigInteger(1, bytMD2);
        String hcMD2 = intNumMD2.toString(16);
        while (hcMD2.length() < 32) {
            hcMD2 = "0" + hcMD2;
        }

        /* MD5 */
        MessageDigest objMD5 = MessageDigest.getInstance("MD5");
        byte[] bytMD5 = objMD5.digest(input.getBytes());
        BigInteger intNumMD5 = new BigInteger(1, bytMD5);
        String hcMD5 = intNumMD5.toString(16);
        while (hcMD5.length() < 32) {
            hcMD5 = "0" + hcMD5;
        }

        /* SHA-1 */
        MessageDigest objSHA1 = MessageDigest.getInstance("SHA-1");
        byte[] bytSHA1 = objSHA1.digest(input.getBytes());
        BigInteger intNumSHA1 = new BigInteger(1, bytSHA1);
        String hcSHA1 = intNumSHA1.toString(16);
        while (hcSHA1.length() < 40) {
            hcSHA1 = "0" + hcSHA1;
        }

        /* SHA-256 */
        MessageDigest objSHA256 = MessageDigest.getInstance("SHA-256");
        byte[] bytSHA256 = objSHA256.digest(input.getBytes());
        BigInteger intNumSHA256 = new BigInteger(1, bytSHA256);
        String hcSHA256 = intNumSHA256.toString(16);
        while (hcSHA256.length() < 64) {
            hcSHA256 = "0" + hcSHA256;
        }

        /* SHA-384 */

        MessageDigest objSHA384 = MessageDigest.getInstance("SHA-384");
        byte[] bytSHA384 = objSHA384.digest(input.getBytes());
        BigInteger intNumSHA384 = new BigInteger(1, bytSHA384);
        String hcSHA384 = intNumSHA384.toString(16);
        while (hcSHA384.length() < 96) {
            hcSHA384 = "0" + hcSHA384;
        }

        /* SHA-512 */
        MessageDigest objSHA512 = MessageDigest.getInstance("SHA-512");
        byte[] bytSHA512 = objSHA512.digest(input.getBytes());
        BigInteger intNumSHA512 = new BigInteger(1, bytSHA512);
        String hcSHA512 = intNumSHA512.toString(16);
        while (hcSHA512.length() < 128) {
            hcSHA512 = "0" + hcSHA512;
        }

        System.out.println("\nMD2: " + hcMD2
                        + "\nMD5: " + hcMD5
                        + "\nSHA-1: " + hcSHA1
                        + "\nSHA-256: " + hcSHA256
                        + "\nSHA-384: " + hcSHA384
                        + "\nSHA-512: " + hcSHA512);
    }
}


texts:
Given any callable, deduces the first parameter in the parameter list of the function. Be ware, not for light hearted.

template <typename ... Args>
struct pick_first;

template <typename T, typename ... Args>
struct pick_first<T, Args ...>
{
    using type = T;
};

template <typename ... Args>
using pick_first_t = typename pick_first<Args...>::type;

template <typename Callable>
struct deduce_first_parameter
{
private:
    template <typename Func, template <typename ...> typename Operation>
    struct extract_function;

    template <typename R, typename ... Args, template <typename ...> typename Operation>
    struct extract_function<R(Args...), Operation>
    {
        using type = typename Operation<Args...>::type;
    };

    template <typename C, typename R, typename ... Args, template <typename ...> typename Operation>
    struct extract_function<R (C::*)(Args...), Operation>
    {
        using type = typename Operation<Args...>::type;
    };

    template <typename Func, template <typename ...> typename Operation>
    using extract_function_t = typename extract_function<Func, Operation>::type;

public:
    using type = extract_function_t<decltype(&Callable::operator()), pick_first>;
};

template <typename R, typename ... InputArgs>
struct deduce_first_parameter<R(InputArgs...)>
{
    using type = pick_first_t<InputArgs...>;
};

Some tests:

#include <vector>
#include <map>

struct dummy
{
    void operator()(std::vector<int>&) {}
    using correct_answer = std::vector<int>&;
};

struct not_so_dummy
{
    using correct_answer = const std::vector<std::map<int, char>>&;
    void operator()(const std::vector<std::map<int, char>>&) {}

};

void f(char, int);

int main()
{
    static_assert(std::is_same<deduce_first_parameter<decltype(f)>::type, char>::value);
    static_assert(std::is_same<deduce_first_parameter<dummy>::type, dummy::correct_answer >::value);
    static_assert(std::is_same<deduce_first_parameter<not_so_dummy>::type, not_so_dummy::correct_answer>::value);
}

After about two weeks of intense Java, I started missing C++. Especially templates.

Motivation:

I'm writing generic sliding window, which is complete, but I don't want to show it yet (I figured that it is possible to do stunning things with it). To supplement it, I need preprocessing iterator, which applies a user supplied functor before assigning to underlying iterator. To make the preprocessing iterator easy to use I need to deduce the first parameter's type to put into std::iterator<> (I know its deprecated, but some compilers still use it to detect iterators), because binding users to what underlying iterator can accept is awkward.

How to compile:

I'm afraid not that many compilers can handle this. I've tested it on clang++-3.9. There might be some warnings, they should be due to using C++17 feature to make template template parameters declared by typename possible (good luck on understanding this sentence).

I'm interested in any critique, but especially about reducing instantiation depth and count. Also fitting statements in one readable line would be great.


texts: getProcID and getProcessHandle functions

texts:
I made two functions: one to get process id and the other to get a handle with all access to that process using the process id. I'm looking for help with making these easy to use on all types of projects. The only thing I know is maybe letting the person chose the open process properties.

DWORD getProcID(const std::wstring &windowName, std::string &status)
{
    DWORD processID = NULL;
    HWND windowHandle = NULL;

    windowHandle = FindWindowW(NULL, windowName.c_str()); // Gets handle to top window (class name, window name)
    if (windowHandle) {
    GetWindowThreadProcessId(windowHandle, &processID); // returns thread that made window (window, process for window)
            if (processID != 0) {
                    return processID;
            }
            else { // if process id is bad
                status = "Error with process";
                return 0;
            }
    }
    else { // if window name is bad/not there
        status = "Error with window";
        return 0;
    }
    CloseHandle(windowHandle); // close window handle since we dont need it anymore
    return 0;
}

HANDLE &getProcessHandle(const DWORD processID, std::string &status) {
    HANDLE procHandle = NULL;

    if (processID != 0) {
        procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID); // returns handle to process (what you want, inherit stuff, process id)
        if (procHandle != INVALID_HANDLE_VALUE || procHandle != NULL) { // if handle returned by openProcess is good
            status = "Game is ready to hack";
        }
        else { // if handle retured by openProcess is bad
            status = "Error with handle";
        }
    }
    else {
        status = "Error with process id";
    }
    return procHandle;
}


texts:
This is an intersection-detection algorithm I developed as an alternative method to the one developed for my coursework. I won't post some of the other functions as they are used in the coursework too, feel free to ask if their names aren't self explanatory. This function simply returns whether 2 bcw objects are intersecting. bcw objects are either boxes or circles. What I'd like is any comments on my algorithm/coding style to help make me a better programmer.

def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30):
    """ Check whether Box-Circle World objects obj_A
    and obj_B collode. If so, return True,
    otherwise return False.
    """
    # items to be checked
    comp1 = [obj_A]
    comp2 = [obj_B]

    # does a component circumcircle collide, True = collides
    truth1 = [False]
    truth2 = [False]

    # Depth used to limit iterations to accuracy
    depth = 0

    while len(comp1)!=0 and depth<accuracy:
        # Find any non colliding components
        for c1,t1 in zip(comp1,range(len(truth1))):
            circum_1 = bcw_circumcircle(c1)
            for c2,t2 in zip(comp2,range(len(truth2))):
                circum_2 = bcw_circumcircle(c2)
                if tracer <> None:
                    tracer([c1,c2,circum_1,circum_2], ["k--","b--","r--","r--"])
                if bcw_do_circles_overlap(circum_1,circum_2) == True:
                    truth1[t1] = True
                    truth2[t2] = True
                    # Check for colliding components
                    in_1 = bcw_incircle(c1)
                    in_2 = bcw_incircle(c2)
                    if tracer <> None:
                        tracer([c1,c2,in_1,in_2],
                           ["g--","b--","r--","r--"])
                    if bcw_do_circles_overlap(in_1,in_2): return True

        # Subdivide all components whose outers collide
        sub = []
        for c1,t1 in zip(comp1,truth1):
            if t1:
                sub+=bcw_components(c1)

        comp1 = sub[::]
        truth1 = [False for i in comp1]

        sub =[]
        for c2,t2 in zip(comp2,truth2):
            if t2:
                sub+=bcw_components(c2)

        comp2 = sub[::]
        truth2 = [False for i in comp1]
        depth+=1

    return False

I was tempted by using the bcw objects as dictionary keys but they had to be mutable.


texts: Avoiding repetitive code for timestamping and updating status

texts:
This is some boilerplate I found myself writing on a new abstract class. It seems ripe for refactoring, but I'm not sure the best way to implement it more effectively. Is there a pattern for these sort of time-stamping/status-updating methods?

def create() {
    tsCreated = new DateTime()
    userCreated = springSecurityService.currentUser
    status = RequestStatus.OPEN
}

def accept() {
    tsAccepted = new DateTime()
    userAccepted = springSecurityService.currentUser
    status = RequestStatus.ACCEPTED
}

def send() {
    tsSent = new DateTime()
    userSent = springSecurityService.currentUser
    status = RequestStatus.SENT
}

def complete() {
    tsCompleted = new DateTime()
    userCompleted = springSecurityService.currentUser
    status = RequestStatus.COMPLETED
}

def cancel() {
    tsCanceled = new DateTime()
    userCanceled = springSecurityService.currentUser
    status = RequestStatus.CANCELED
}


texts:
Problem Statement:

  Create a class diagram and Java code for the following system and
  scenario, taking into account the possibility of future extensions.
  "The system is a command line utility that prints a short 'quote of
  the day' on the user's terminal when run. To begin with the quote is
  selected randomly from a set of hard-coded strings within the program
  itself, but that might change later on -- the quotes might be based on
  the user's history, the time of day, the date, etc.. Scenario:

  User types "java QuoteOfTheDay" on the command line.
  System prints out a quote of the day, with an attribution.

This is my code for the following:

Class Containing the main method

package quoteOfTheDay;
import java.util.Random;

public class QuoteOfTheDay {

    public static void main(String[] args) {
        System.out.println();

        Random rand = new Random();

        System.out.println(Quote.QUOTES[rand.nextInt(Quote.QUOTES.length)]);

    }
}

Quote Class containng the quotes.

    package quoteOfTheDay;

public class Quote {
    public static final String  QUOTES[] = {
            "Be yourself; everyone else is already taken.― Oscar Wilde",
            "A room without books is like a body without a soul. ― Marcus Tullius Cicero",
            "Be the change that you wish to see in the world. ― Mahatma Gandhi",
            "If you tell the truth, you don't have to remember anything. ― Mark Twain",
            "If you want to know what a man's like, take a good look at how he treats his inferiors, not his equals.― J.K. Rowling",
            "To live is the rarest thing in the world. Most people exist, that is all.― Oscar Wilde",
            "Without music, life would be a mistake. ― Friedrich Nietzsche",
            "Always forgive your enemies, nothing annoys them so much. ― Oscar Wilde",
            "Life isn't about getting and having, it's about giving and being. –Kevin Kruse",
            "Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill",
            "Strive not to be a success, but rather to be of value. –Albert Einstein",
            };
}

Is this the right approach? Am I missing some things from the problem requirements? I am open for any kind of suggestions.


texts: Compare large text File in java line by line

texts:
Dear fellow developers I am doing a java program which compare two text files line by line, first text file has 99,000 lines and the other file has 1,15,000 lines. I want to read the files and compare in such a way so that if any line matches between the first file and the second file it should print the match.

I have written the code but it is taking almost 10 mins to complete, as it is printing due to the for loop. How can it be made fast, efficient and efficient in terms of memory allocation? How can it be optimized for performance? Please guide me.

public class Main {

static final String file1 = "file1.txt";
static final String file2 = "file2.txt";

static BufferedReader b1 = null;
static BufferedReader b2 = null;

static List<String> list_file1 = null;
static List<String> list_file2 = null;

public static void main(String[] args) {

    list_file1 = new ArrayList<String>();
    list_file2 = new ArrayList<String>();

    String lineText = null;

    try {
        b1 = new BufferedReader(new FileReader(file1));
        while ((lineText = b1.readLine()) != null) {
            list_file1.add(lineText);
        }
        b2 = new BufferedReader(new FileReader(file2));
        while ((lineText = b2.readLine()) != null) {
            list_file2.add(lineText);
        }
        compareFile(list_file1,list_file2);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static void compareFile(List<String> list_file1, List<String> list_file2) {
    for(String content1:list_file1){
        for(String content2:list_file2){
            if(content1.equals(content2)){
                System.out.println("Match Found:-"+content1);
            }
        }
    }
}
}


texts:
I am a beginner and I wanted to make programs that would help me while I learnt Java. I made a program to help me in my assignments. Any suggetions?

Main method

public class MirrorFormula {

public static void main(String[] args) {
        Scanner keyboardInput = new Scanner(System.in);
        double u =0;
        double v =0;
        double f =0;

        System.out.println("Hello! This is a calculator based on the Mirror Formula. \n");
        System.out.println("The mirror formula is a relation between the object distance, the image distance \n and the focal length.");
        System.out.println("The formula is : 1/u + 1/v = 1/f.  (u=distance of object, v=distance of image, f=focal length.)");
        System.out.println("It is applicable for both convex mirrors and concave mirrors.");
        System.out.println();
        System.out.println("This calculator can calculate :");
        System.out.println();
        System.out.println("1. Distance of the object from the pole of the spherical mirror.");
        System.out.println("2. Distance of the image from the pole of the spherical mirror.");
        System.out.println("3. Focal length");
        System.out.println("[If you have 2 of the values.]");
        System.out.println("________________________________________________________________________________________________________________________________");
        System.out.println("What value would you like to find out? ");
        System.out.println("Enter: \n 1. for Distance of object \n 2. for distance of image \n 3. for Focal length \n (Please note that you don't need to enter units. The ans. is in whatever unit you enter the values)" );

        int userChoice = keyboardInput.nextInt();

        System.out.println("________________________________________________________________________________________________________________________________");

        switch (userChoice) {

        case 1 :
            System.out.println("Please enter the distance of the image: ");
            v = keyboardInput.nextDouble();
            System.out.println("Please enter the focal length: ");
            f = keyboardInput.nextDouble();
            u = findU(v, f);
            break;

        case 2 :
            System.out.println("Please enter the distance of the object: ");
            u = keyboardInput.nextDouble();
            System.out.println("Please enter the focal length: ");
            f = keyboardInput.nextDouble();
            v = findV(u, f);
            break;

        case 3 :
            System.out.println("Please enter the distance of the object: ");
            u = keyboardInput.nextDouble();
            System.out.println("Please enter the distance of the image: ");
            v = keyboardInput.nextDouble();
            f = findF(u, v);
            break;

        }
    System.out.println("___________________________________________________");
    System.out.println(" Distance of the object from the pole is  | " + u + "  |");
    System.out.println(" Distance of the image from the pole is   | " + v + "  |");
    System.out.println(" The focal length                         | " + f + "  |");
    System.out.println("___________________________________________________");
}

Other methods

These calculate the ans. based on the input:

public static double findU(double v, double f) {

    double oneUpon;

    oneUpon = 1/f - 1/v;
    return 1/oneUpon;

}

public static double findV(double u, double f){

    double oneUpon;

    oneUpon = 1/f - 1/u;
    return 1/oneUpon;
}

public static double findF(double u, double v){

    double oneUpon = 1/u + 1/v;
    return 1/oneUpon;
}

}


texts:
I am using the code below that loops around thousands of time, I need this to be as fast as possible, however I am not an expert in Javascript and all I know is that this code is faster than doing it with the innerHTML method.

Can it be optimized? If so, how?

    var a,b,c,d,e,
    trEl, tdEl, imgEl

    for (i = 0; i < docs.length; i++) {
      trEl = document.createElement('tr');
      tdEl = document.createElement('td');
      td1El = document.createElement('td');
      td2El = document.createElement('td');
      td3El = document.createElement('td');
      imgEl = document.createElement('img');

      var str
      a = docs[i]['a']
      b = docs[i]['b']
      c = docs[i]['c']
      d = docs[i]['date'] + " - " + docs[i]['timestamp']
      e = docs[i]['_e']

      trEl.setAttribute('id', e);
      trEl.setAttribute('ondblclick', 'scan(' + '"' + e + '"' + ')');
      imgEl.setAttribute('src', 'css/bullet.png');
      tdEl.appendChild(imgEl);

      tdEl.appendChild(document.createTextNode(a));
      td1El.appendChild(document.createTextNode(d));
      td2El.appendChild(document.createTextNode(b));
      td3El.appendChild(document.createTextNode(c));

      trEl.appendChild(tdEl);
      trEl.appendChild(td1El);
      trEl.appendChild(td2El);
      trEl.appendChild(td3El);

      document.getElementById("search-results").appendChild(trEl)
      }


texts: NativeScript - Angular Service to watch iOS keyboard event listeners

texts:
I'm writing an app with NativeScript 6.4.1 and Angular version 8.

There are a series of UI events in iOS that you can watch to see what the keyboard is doing:
https://developer.apple.com/documentation/uikit/uikeyboarddidhidenotification?language=objc

I wrote a service to watch and subscribe to these changes.

Do you see any issues in the code with having too many Observables and listeners?

Here is my service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import * as application from 'tns-core-modules/application';

@Injectable({
    providedIn: 'root'
})
export class iOSKeyboardObserverService {

    public didShow$(): Observable<any> {

        return new Observable((observer) => {

            const iosObserver = application.ios.addNotificationObserver(UIKeyboardDidShowNotification, (notification) => {
                observer.next(true);
            });

            return () => {
                application.ios.removeNotificationObserver(iosObserver, UIKeyboardDidShowNotification);
            }
        });

    }

    public didHide$(): Observable<any> {

        return new Observable((observer) => {

            const iosObserver = application.ios.addNotificationObserver(UIKeyboardDidHideNotification, (notification) => {
                observer.next(false);
            });

            return () => {
                application.ios.removeNotificationObserver(iosObserver, UIKeyboardDidHideNotification);
            }
        });

    }
}

Example usage:

public isKeyboardShowing: boolean;

constructor(private page: Page, private ngZone: NgZone, private keyboardObserver: iOSKeyboardObserverService) {

    this.page.on(Page.layoutChangedEvent, (args: EventData) => this.onLayoutChanged(args));
    this.isKeyboardShowing = false;

    if (utils.ios) {

        this.keyboardObserver.didHide$().subscribe((result) => {
            this.setIsKeyboardShowing(result);
        });

        this.keyboardObserver.didShow$().subscribe((result) => {
            this.setIsKeyboardShowing(result);
        });
    }

}


texts: FileSystemWatcher with threaded FIFO processing

texts:
I have single threaded C# console application that uses FileSystemWatcher to watch folder for new files.

My app sees a file being written, waits until it is released, then picks it up and processes it. At the same time it writes a rolling log to a text file:

2014-08-06 16:20:1.500 - Found file : C:\test1.pdf
2014-08-06 16:20:1.510 - Waiting for file to become available
2014-08-06 16:20:2.010 - Processing file
2014-08-06 16:20:8.256 - Finished processing file: C:\test1.pdf
2014-08-06 16:20:8.785 - File C:\test2.pdf found!

etc..etc..

The current method ensures the following:

Each file is processed in the order that FileSystemWatcher sees it.
The log file is written in a linear fashion, one file at a time.

Files created in the folder seem to be cached FileSystemWatcher until the current file has finished processing.
This works OK but I don't like the fact that FileSystemWatcher is caching it, it must have a buffer limit somewhere and files might drop of the end.

I think I need two threads:

FileSystemWatcher thread that sees the new files and passes to a 'Files to Process' collection.
File processing thread that sees there are items in the 'Files to Process' collection and processes them, FIFO style.

I started work on this and decided to use an ObservableCollection for the 'Files to Process' list, I thought I could hang methods off the NotifyCollectionChangedAction events but I am a bit stuck as to where to now put the thread.

My questions are:

Do I need two threads?
Is ObservableCollection the best object to use to manage the list of files to process?
Where do I put a second thread? I am guessing that I need a new thread each time a new file is added to the ObservableCollection but won't that trigger a thread for each file, then the log will be jumbled up with each file that is added to the collection?

The files that FileSystemWatcher pick up become Document objects.
Here is the code I have so far:

//Make the objects and set events
watcher = new FileSystemWatcher();
watcher.Created += new FileSystemEventHandler(AddDocument);
docsToProcess = new ObservableCollection<Document>();
docsToProcess.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged);

//Called by FileSystemWatcher when it sees a new file
 void AddDocument(object source, FileSystemEventArgs f)
        {
            Document doc = new Document(f.FullPath);
            docsToProcess.Add(doc);
        }

//Called when the collection changes
 void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (Document doc in e.NewItems)
                    {
                        log.Write("Found file : " + doc.FullPath);
                        ProcessDoc(doc);
                    }
                    break;

                case NotifyCollectionChangedAction.Remove:
                    foreach (Document doc in e.OldItems)
                    {
                        log.Write("Finished Processing file : " + doc.FullPath);
                    }
                    break;

                default:
                    break;
            }
        }

//Called when a new document is added to the collection
 void ProcessDoc(Document doc)
        {
            //Do processing stuff to the document, also write to the log
            //Then remove itself from the collection
            docsToProcess.Remove(doc);
        }


texts: Implement funcionality with handling errrors without throwing exceptions

texts:
In usual code if something goes wrong you throw an exception. However in some cases you need so that exceptions were processed and reported. Form validation is a good example. Error handling in this is realy easy. However I faced a problem when error handling is different from the previous example and that code does not look very pretty. Here is an example:

public function create($bcId) {
        $this->reporter->title("BC product resource creating report");
        $resource = $this->get($bcId);
        if (!$resource) {
            $this->reporter->report();
            return;
        }
        $dto = EntityDto::fromBc($resource);
        if (!$this->validator->validate($dto)) {
            $this->reporter->report($this->validator->getErrors());
            return;
        }
        $entity = Entity::fromDto($dto);
        $this->entityRepo->create($entity);
    }

    public function get($bcId) {
        try {
            $resource = $this->bcRepo->get($bcId);
        } catch (\Exception $e) {
            $this->reporter->add($e);
            return false;
        }
        return $resource;
    }

Without error handling the code would look like this:

public function create() {
        $resource = $this->bcRepo->get($bcId);
        $dto = EntityDto::fromBc($resource);
        $entity = Entity::fromDto($dto);
        $this->entityRepo->create($entity);
    }

Much less code and more clear. However I need proper error handling. I can not go with throwing exceptions because it will exit the app. I could have the following code:

public function create() {
        if (
            ($resource = $this->bcRepo->get($bcId)) &&
            ($dto = EntityDto::fromBc($resource)) &&
            ($entity = Entity::fromDto($dto)) &&
            ($this->entityRepo->create($entity))
        ) ; else {
            $this->report();
        }
    }

But it still is difficult to understand. Are there any variants to change the code to by prettier without chaning its behaviour?


texts:
I've been fiddling with templates and compile time stuff i implemented a variant container and wanted some opinions and recommendations this is just a learning exercise, a couple template classes not included here are tl_type_at which gives the type in a typelist at a given index; and tl_index_of which gives the index of the first occurrence of the given type in a typelist:

template <size_t Index, typename T, typename ... Ts>
struct variant_deleter
{
    variant_deleter<Index + 1, Ts...> next;
    void operator()(size_t HeldIndex, void* HeldPtr) const
    {
        if(Index == HeldIndex)
            delete static_cast<T*>(HeldPtr);
        else
            next(HeldIndex, HeldPtr);
    }
};

template <size_t Index, typename T>
struct variant_deleter<Index, T>
{
    void operator()(size_t HeldIndex, void* HeldPtr) const
    {
        if(Index == HeldIndex)
            delete static_cast<T*>(HeldPtr);
        }
};

struct bad_variant_access {};

template <typename T, typename ... Ts>
struct variant
{
    typedef typelist<T, Ts...> types;

    variant()
        : union_(new T())
        , held_(0)
    {}
    template <typename I>
    variant(I Init)
        : union_(new typename tl_type_at< tl_index_of<I, types>::index, types >::type())
        , held_(tl_index_of<I, types>::index)
    {}
    ~variant()
    { variant<T, Ts...>::deleter_(held_, union_); }

    template <typename P>
    variant<T, Ts...>& operator=(const P& rhs)
    {
        union_ = new(union_) P(rhs);
        held_ = tl_index_of<P, types>::index;
        return *this;
    }

    template <typename G>
    G& get()
    {
        if(held_ == tl_index_of<G, types>::index)
            return *static_cast<G*>(union_);
        else
            throw bad_variant_access {};
    }
private:
    void* union_;
    size_t held_;
    static const variant_deleter<0, T, Ts...> deleter_;
};


texts:
Challenge

Given a list of words mixed with extra symbols. Write a program that will clean up the words from extra numbers and symbols.

Specifications

The first argument is a path to a file.
Each line includes a test case.
Each test case is a list of words.
Letters are both lowercase and uppercase, and mixed with extra symbols.
Print the words separated by spaces in lowercase letters.

Constraints

The length of a test case together with extra symbols can be in a range from 10 to 100 symbols.
The number of test cases is 40.

Input Sample

  (--9Hello----World...--)
  Can 0$9 ---you~
  13What213are;11you-123+138doing7

Output Sample

  hello world
  can you
  what are you doing

Source

Solution:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void to_lowercase(char * input) {
    for(int i = 0; input[i]; i++){
        input[i] = tolower(input[i]);
    }
}

char * sanitize(char * input) {
    char *sanitized = malloc(sizeof (char) * 1024);
    int iterator = 0;
    int character_value;
    bool wordMatched = false;

    for (int i = 0; i < strlen(input); i++) {
        int character_value = input[i];
        // a-z = 97-122, A-Z = 65-90
        if (character_value >= 97 && character_value <= 122
        ||  character_value >= 65 && character_value <= 90) {
            sanitized[iterator++] = input[i];
            wordMatched = true;
        } else if (wordMatched) {
            wordMatched = false;
            sanitized[iterator++] = ' ';
        }
    }

    sanitized[iterator] = '\0';
    to_lowercase(sanitized);
    return sanitized;
}

int main(int argc, const char * argv[]) {
    FILE *file = fopen(argv[1], "r");
    char line[1024];
    while (fgets(line, 1024, file)) {
        printf("%s\n", sanitize(line));
    }

    return 0;
}


texts:
I have been trying to implement various substitution ciphers in python. I implemented the Baconian cipher using a dictionary in which the plaintext letters are keys and the ciphertext letters are the corresponding values. Is there a way to make the following code shorter or more efficient or is there a better approach to implementing the cipher.
Python program to implement Baconian cipher
'''This script uses a dictionary instead of 'chr()' & 'ord()' function'''

'''
Dictionary to map plaintext with ciphertext
(key:value) => (plaintext:ciphertext)
This script uses the 26 letter baconian cipher
in which I,J & U,V have distinct patterns
'''
lookup = {'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', 'D':'aaabb','E':'aabaa',
    'F':'aabab', 'G':'aabba', 'H':'aabbb', 'I':'abaaa', 'J':'abaab',
    'K':'abaab', 'L':'ababa', 'M':'ababb', 'N':'abbaa', 'O':'abbab',
    'P':'abbba', 'Q':'abbbb', 'R':'baaaa', 'S':'baaab', 'T':'baaba',
    'U':'babaa', 'V':'babab', 'W':'babaa', 'X':'babab', 'Y':'babba'
    'Z':'babbb'}
#Function to encrypt the string according to the cipher provided
def encrypt(message):
    cipher = ''
    for letter in message:
        #checks for space
        if(letter != ' '):
            #adds the ciphertext corresponding to the plaintext from the dictionary
            cipher += lookup[letter]
        else:
            #adds space
            cipher += ' '

    return cipher

#Function to decrypt the string according to the cipher provided
def decrypt(message):
    decipher = ''
    i = 0

    #emulating a do-while loop
    while True :
        #condition to run decryption till the last set of ciphertext
        if(i < len(message)-4):
            #extracting a set of ciphertext from the message
            substr = message[i:i+5]
            #checking for space as the first character of the substring
            if(substr[0] != ' '):
                '''
                This statement gets us the key(plaintext) using the values(ciphertext)
                Just the reverse of what we were doing in encrypt function
                '''
                decipher += list(lookup.keys())[list(lookup.values()).index(substr)]
                i += 5 #to get the next set of ciphertext
            else:
                #adds space
                decipher += ' '
                i += 1 #index next to the space
        else:
            break #emulating a do-while loop

    return decipher

def main():
    message = "ALICE KILLED BOB"
    result = encrypt(message.upper())
    print (result)

    message = "aaaaaababaabaaaaaabaaabaa abaababaaaababaababaaabaaaaabb aaaababbabaaaab"
    result = decrypt(message.lower())
    print (result)

#Executes the main function
if __name__ == '__main__':
    main()

I have been implementing most of the substitution ciphers using dictionaries and I want to know is there a another approach to this as I am bored of using dictionaries.


texts: Filtering (search) a model with multiple params in hash

texts:
This function in my Profile model receive a hash from a search form and should filter the table depending on those values. I guess there is something like a pattern for such a standard behavior, right now I ended up with this (unfortunately I had to reproduce the code here, so it might not work for some reasons, but you get the idea).

Just a note: we're storing in the model some strings containing multiple data, each of these fields should be a one-to-many relationship (db normality violation). I give an example: country_preferences is a string filled up by an html select :multiple => true. In the string I then find values like: ["Australia", "China", "United Kingdom"].

  def search opts # This default doesn't work the way I would like = {:user_type => :family}

    #TODO: default opts value in method sign if possible
    opts[:user_type] ||= :family

    # initial criteria
    fields= "user_type= ?"
    values= [opts[:user_type]]

    # each field filters the list in one of these three ways
    staight_fields = [ :country, :first_name, :last_name, :nationality ]
    like_fields = [:country_preferences, :keyword, :languages ]
    bool_fields = [:driver, :housework, :children ]

    # cicle the options and build the query
    opts.each do |k, v|
      if straight_fields.include? k
        fields += " AND #{k} = ?"
        values += v
      elsif like_fields.include? k
        fields += " AND #{k} like %?%"
        values += v
      elsif bool_fields.include? k
        fields += " AND #{k} = ?"
        values += v == 'true'
      else
        logger.warn "opts #{k} with value #{v} ignored from search"
      end
    end

    # execute the query and return the result
    self.registered.actives.where([fields] + values)
  end

I think I can use more scope but how can I combine them together? In general, how can I make this code much better?

The boss, when introducing the project, said one-to-many relationships for that kind of fields would be a pain in the back. What do you think about this pragmatic solution?


texts: Just require a file, or check if_readable first?

texts:
I'm writing a simple front controller, index.php is the main file.
In my index.php, first thing loaded is bootstrap.php via require_once().

I'm deliberating over two ways to load bootstrap.php:

A)

require_once 'bootstrap.php';

B)

if ( is_readable('bootstrap.php') )
  {
    require_once 'bootstrap.php';
  }
else
  {
    exit( 'Sorry, we have a temporary issue. We are aware and it should hopefully be resolved soon. Please try again in 10 mins' );
  }

I see most well know frameworks (Codeigniter etc) just use A, which is neat and simple. If the file is not found, A provides:

A means for the script to halt via the require_once() returning a
fatal error
Nothing else graceful or useful

However I'm tempted to use B as if the file is not found, B will:

Provides a basic message to the screen, no white screen
Avoids a fatal error which A will produce
B seems more frameworky and robust, controlling what happens via the
application rather than just relying upon PHP which falls back on a
fatal error

This (A or B) is only used a couple of times, once to load  bootstrap.php and then twice within bootstrap.php to load SPL autoloader and error management (etc). Thus dealing with require() and any errors/failures throughout the rest of the system are handled more gracefully (with SPL and error management) and so neither A or B are needed.

However, I'm trying to make the entire system tight and well coded, rather than "it's only used a few times, meh that'll do".

I'm personally drawn towards using B, but I don't want opinions on which you would use for personal reasons, there will be some logical reasons or rationale I have not considered which I'd be grateful for you to throw at me.

Such as B has too much overhead (likely negligible but just an example), major frameworks use A because XYZ, etc.

Questions:

Is A flimsy and a bit unprofessional by just allowing code within a framework to use PHP fall back to a fatal error? When a framework should manage things in the best possible way.
Is A acceptable just allowing a fatal error?
Is B over the top, too much code FWIW, and not really necessary?
Is B much better because it removes a stinky fatal error, and because it controls how the application degrades rather than relying on a PHP fatal error to halt?


texts: Producing queries based on user interface selection

texts:
I have written a module in my application that makes extensive use of dynamic LINQ to produce Linq/SQL queries based on user interface selection.
Currently, the Linq-SQL translation is resulting in very unoptimised query results, so I am looking at ways to get LINQ to improve the SQL that it is producing.

The following is a typical scenario:

Firstly, the user interface controls are selected, resulting in a LINQ statement of:

Company_contacts.Any(Cust_order_header.Any(Order_time >= @0))

The table relations are as following:

Companies 1-*
Contacts 1-*
Cust_order_header

The Cust_order_header contains the datetime field Order_time.

Don't worry about @0 - that is a dynamic Linq parameter that is passed in containing the datetime object.

The query translates to:

  Give me all companies that have placed orders within the last (insert days based on datetime) days

This results in a query that takes 5 minutes to complete, and kicks the hell out of the server.

The SQL it has created (which I have retrieved using ((ObjectQuery)groupQuery).ToTraceString()) is:

SELECT *
FROM [dbo].[Companies] AS [Extent1]
WHERE  EXISTS (SELECT
    1 AS [C1]
    FROM ( SELECT
        [Extent2].[Company_cont_key] AS [Company_cont_key]
        FROM [dbo].[Company_contacts] AS [Extent2]
        WHERE [Extent1].[Company_reference] = [Extent2].[Company_reference]
    )  AS [Project1]
    WHERE  EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[Cust_order_header] AS [Extent3]
        WHERE ([Project1].[Company_cont_key] = [Extent3].[Company_cont_key]) AND ([Extent3].[Order_time] >= convert(datetime, '2012-05-20 00:00:00.000', 121))
    )
)

Now, firstly - there are no joins in there, which leads me to think that the SQL it is producing is significantly unoptimised.

AS, if I do to the following in SQL Management Studio manually:

SELECT *
FROM [dbo].[Companies] co
join  [dbo].[Company_contacts] cc on co.Company_reference = cc.Company_reference
join  [Cust_order_header] coh on coh.Company_cont_key = cc.Company_cont_key
WHERE  [Order_time] >= convert(datetime, '2012-05-20 00:00:00.000', 121)

Then it's < 1s.

So, I have spent 3 weeks putting together my Dynamic-LINQ based user controls/solution; getting rid of it isn't an option.

I should also mention I am using an SQL2000 database. There is nothing I can do about this by the way.

Whilst playing around with the SQL to see if I can get improvements, I have noticed that bizarrely if I change the operator from '>' as it should be to '<', which takes the set of rows I was to ignore, it returns 18k rows (instead of the intended 300) but only takes 2 seconds instead of 4 minutes for the smaller query.

I'm wondering what the options are, or specifically how I should go about configuring LINQ to do things a bit better. I'm even starting to wonder if it's my dynamic LINQ extension code that is unoptimised (downloaded from here).


texts:
I was issued the following coding challenge from a company to write an encoding and decoding function:

  Encoding: This function needs to accept a signed integer in the 14-bit
  range [-8192..+8191] and return a 4 character string. The encoding
  process is as follows:

  Add 8192 to the raw value, so its range is translated to [0..16383]. Pack that value into two bytes such that the most significant bit of each is cleared.
  Unencoded intermediate value (as a 16-bit integer):
  00HHHHHH HLLLLLLL

  Encoded value:
  0HHHHHHH 0LLLLLLL
  Format the two bytes as a single 4-character hexadecimal string and return it.

  Decode:

  Your decoding function should accept two bytes on input, both in the
  range [0x00..0x7F] and recombine them to return the corresponding
  integer between [-8192..+8191]

Here is my solution to both functions:

public static String encode(int num){
    if(num < -8192 || num > 8191) {
        throw new IllegalArgumentException("This function only takes ints within the 14-bit range (-8192 to 8191)");
    } else {
        //step 1
        //System.out.println("Unencoded Decimal Value: "+ num);

        num += 8192;
        //System.out.println("Intermediate Decimal: " + num);

        //step 2
        String numString = Integer.toHexString(num);
        //System.out.println("Intermediate Hex: " + numString);

        //step 3
        String theBinary = Integer.toBinaryString(Integer.parseInt(numString,16));

        while(theBinary.length() < 14){
            String zero = "0";
            zero += theBinary;
            theBinary = zero;
        }
        //Build the updated Binary
        String newBinary = "";
        for(int i=theBinary.length() -1; i>=0; i--){
            newBinary += theBinary.charAt(i);
            if(i== 7 || i == 0){
                newBinary += "0";
            }
        }
        newBinary = new StringBuilder(newBinary).reverse().toString();

        StringBuilder sb = new StringBuilder();
        sb.append(Integer.toHexString(Integer.parseInt(newBinary,2)));
        while(sb.length() < 4) {
            sb.insert(0, '0'); // pad with leading zero if needed
        }
        String hex = sb.toString();

        System.out.println("The Encoded Hex: " + hex);

        System.out.println();
        return hex;
    }
}

public static int decode(byte byte1, byte byte2){
    if(byte1 < 0x00 || byte2 < 0x00 || byte1 > 0x7F || byte2 > 0x7F){
        throw new IllegalArgumentException("This function only takes bytes between 0x00 and 0x7F");
    }
    //Append Zeros
    String pt1 = Integer.toBinaryString(byte1);
    while(pt1.length() < 7){
        String zero = "0";
        zero += pt1;
        pt1 = zero;
    }
    //Append Zeros
    String pt2 = Integer.toBinaryString(byte2);
    while(pt2.length() < 7){
        String zero = "0";
        zero += pt2;
        pt2 = zero;
    }
    String fullBinary = pt1 + pt2;
    //System.out.println("Full Binary: "+fullBinary);
    int decimalValue = Integer.parseInt(fullBinary, 2);
    //System.out.println("Decimal Value: "+decimalValue);
    int originalValue = decimalValue - 8192;
    System.out.println("Original Value: " + originalValue);

    //System.out.println();
    return originalValue;
}

I recieved that this solution "did not demonstrate the level of expertise required". The only requirements issued in the challenge were to write the functions and to return the specified value (which it does) and to do it quickly (which it does). My main question is where could I have improved this code to to "demonstrate more expertise". I'm just looking for an entry level programming position, but I keep getting responses like this that are vague even when I write code that completes the task issued.


texts: Unit testing Spark transformation on DataFrame

texts:
Looking for suggestions on how to unit test a Spark transformation with ScalaTest.  The test class generates a DataFrame from static data and passes it to a transformation, then makes assertion on the passing static data generated in the test class.  (The transform creates a second column b defined as col("a").plus(5).)

I got this to work but wonder if there's a better way to create the DataFrame?   asJava feels awkward, as does defining the row data and schema separately.

class TransformTest extends FlatSpec with Matchers with SharedSparkContext {
  "Transformer" should "add column to dataframe" in {
    val sqlContext = new SQLContext(sc)
    val rows = Seq[Row](
      Row(1),
      Row(2),
      Row(3)
     ).asJava
   val schema = StructType(Seq(StructField("a", IntegerType)))

   val df = sqlContext.createDataFrame(rows, schema)
   val df2 = new Transform().addCol(df)
   assert(df2.count() > 0)
   assert(df2.agg(sum("a")).first.getLong(0) == 6)
   assert(df2.agg(sum("b")).first.getLong(0) == 21)
  }
}


texts: Form for OTP entry with six single-character text fields

texts:
I am working on an app in which I have to pass 6 digits OTP through 6 textFields in which you to provide only one character and after that it automatically goes to another textField. I created 6 textFields outlets and used this code.

override func viewDidLoad() {
    super.viewDidLoad()

txtOTP1.delegate = self
txtOTP2.delegate = self
txtOTP3.delegate = self
txtOTP4.delegate = self
txtOTP5.delegate = self
txtOTP6.delegate = self

}

And I used this logic to create the functionality

 func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
    // Range.length == 1 means,clicking backspace
    if (range.length == 0){
        if textField == txtOTP1 {
            txtOTP2?.becomeFirstResponder()
        }
        if textField == txtOTP2 {
            txtOTP3?.becomeFirstResponder()
        }
        if textField == txtOTP3 {
            txtOTP4?.becomeFirstResponder()
        }
        if textField == txtOTP4 {
            txtOTP5?.becomeFirstResponder()
        }
        if textField == txtOTP5 {
            txtOTP6?.becomeFirstResponder()
        }
        if textField == txtOTP6 {
            txtOTP6?.resignFirstResponder()
        }
        textField.text? = string
        return false
    }else if (range.length == 1) {
        if textField == txtOTP6 {
            txtOTP5?.becomeFirstResponder()
        }
        if textField == txtOTP5 {
            txtOTP4?.becomeFirstResponder()
        }
        if textField == txtOTP4 {
            txtOTP3?.becomeFirstResponder()
        }
        if textField == txtOTP3 {
            txtOTP2?.becomeFirstResponder()
        }
        if textField == txtOTP2 {
            txtOTP1?.becomeFirstResponder()
        }
        if textField == txtOTP1 {
            txtOTP1?.resignFirstResponder()
        }
        textField.text? = ""
        return false
    }
    return true
}

But it is very long and messy. Is there anyway I can make it simple?


texts: Speeding up an algorithm for finding the number of distinct lines

texts:
Is there a way to speed up the following python code:

auxdict = {0:0}
divdict = {}

def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5) + 1):
        if (n % i == 0):
            divisors.extend([i, n/i])
    divisors = list(set(divisors))
    divisors.sort()
    return divisors

def aux(k):
    if k in auxdict:
        return auxdict[k]
    else:
        if not k in divdict:
            divdict[k] = divisors(k)
        r = sum(map(aux, divdict[k][:len(divdict[k])-1]))
        auxdict[k] = (k+1)**3 - k**3 - r
        return auxdict[k]

def lines(k):
    result = 0
    for i in range(int(k/2),0,-1):
        result += int(k/i-1) * aux(i)
    return (k+1)**3 - result - 1

for i in [10**6, 10**10]:
    print i, lines(i)

It is a modified version of a Mathematica code I found. The code finds the maximum number of distinct lines in a 3D cube of lattices of size n: http://oeis.org/A090025

The problem is the code is very slow and doesn't work for larger values. I want to evaluate lines(10**10)


texts:
I have a web application which is being used by users from different parts of the world. In order for users of the site, to be able to view the timestamps in their local time, I've a settings page set up which will allow the user to store their preferred timezone (Europe/Berlin, America/Chicago) etc. When a user is authenticated successfully, value fetches from the DB and stores it in a session.

From what I've read so far, the best practice seems to be to store the datetime value in UTC format when a new record is created in a database and while displaying it, convert it to the user's timezone. So to achieve the following, this is what I'm doing:

if($this->userIsAuthenticated())
{
   $this->session->timezone = "Europe/Berlin"; // this value is coming from db
}

// inserting records
date_default_timezone_set("UTC");
$data = array("created_time"=>date("Y-m-d H:i:s"));
$this->db->insert("my_table", $data);

// fetching records
$date_from_db = $row->created_time;
$display_date = new DateTime($date_from_db , new DateTimeZone('UTC'));
$display_date->setTimeZone(new DateTimeZone($this->session->timezone));
return $display_date->format("m/d/Y h:i a");

So the workflow is as follows:

Use date_default_timezone_set() for every insert query
Pull the value from the db and set it to UTC using DateTime class
Then set the timzeone to user's timezone

This solution works. But, is this best way of doing it? Or, are there any more modular ways of achieving the same result?


texts:
I'm in the process of refactoring one of my open source projects, branch here.

The basic idea of the refactor is to allow for classes and all of its children in the graph to be scoped. I wrote a blog post about it here.

The container is abstracted into an interface:

public interface IScopedContext : IDisposable
{

}

public interface IScopedContext<out TEntryPoint> : IScopedContext where TEntryPoint : class
{
    TEntryPoint EntryPoint { get; }
}

StructureMap implementation:

internal sealed class StructureMapScopedContext<TEntryPoint> : IScopedContext<TEntryPoint> where TEntryPoint : class
{
    private readonly IContainer nested;

    public StructureMapScopedContext(IContainer container)
    {
        nested = container.GetNestedContainer();
        nested.Configure(config => config.For<IScopedContext>().Use(this));
        EntryPoint = nested.GetInstance<TEntryPoint>();
    }

    public TEntryPoint EntryPoint { get; private set; }

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

Basically after refactoring you can do:

public class Host
{
    private readonly IScopedContext<MyWorker> myWorkerContext;

    public Host(IScopedContext<MyWorker> myWorkerContext)
    {
        myWorkerContext = myWorkerContext;
    }

    public void Start()
    {
        using(myWorkerContext)
        {
            myWorkerContext.EntryPoint.Start();
        }
    }
}

Is it a solid design? Any pitfalls?


texts: Compile SASS files in a directory via Gulp.js tasks, one of which produces logging output

texts:
If the default task is executed here, the file name to be compiled is passed to the argument of the CompileSass function. When the sass task is executed, the callback function to be executed at the end is passed by gulp.

The CompileSass function logs the file name when it is passed. Also, when anything other than the file name is passed, the log output will not be performed with the CompileSass function.

This is easily done by determining the argument with the typeof operator.

function CompileSass(filePath) {
    const time = process.hrtime();
    const isFilePath = typeof filePath === "string";
    if (isFilePath) { // same if condition
        console.log("compiling now");
    }
    return src(path["sass"])
        .pipe(sass({outputStyle: "expanded"}))
        .on("end", () => {
            if (isFilePath) { // same if condition
                console.log(`Compiled '${filePath}' now`);
            }
        })
        .pipe(dest("css"))
        .on("end", () => {
            if (isFilePath) { // same if condition
                const TaskTime = prettyTime(process.hrtime(time));
                console.log(`Finished compiled ${TaskTime}`);
            }
        });
}

exports.default = () => {
    watch(dir).on("all", (directory) => {
        CompileSass(directory);
    });
};

exports.sass = series(CompileSass); // in fact, there is other tasks in series function's argument

However, this if statement is repeated even though the log output conditions are the same. I wanted to consolidate this if statement in one place. But I couldn't come up with a good idea for that. I believe that increasing package dependencies leads to management complexity, so I am reluctant to introduce new packages whenever possible.

Is there a good way to make the conditional branch for log output common in the gulp method chain?


texts:
I'm attempting to implement a basic hash table in Python using only lists. Any tips would be appreciated (including better hash functions).
I intend this to handle collisions with separate chaining.

Are there any features I didn't implement that are standard in hash tables?

Are there any things I handled incorrectly or could have implemented in a better way?

My implementation:
class HashTable(object):

    table = [None] * 256

    def get_value(self, key):
        total = 0
        for i in range(len(key)):
            total += ord(key[i]) * (7**i)
        return (len(key) * total) % 256

    def insert(self, key):
        val = self.get_value(key)
        if self.table[val] == None:
            self.table[val] = key
        else:
            if type(self.table[val]) == list:
                self.table[val].append(key)
            else:
                self.table[val] = [self.table[val], key]

    def delete(self, key):
        val = self.get_value(key)
        if self.table[val] != None:
            if type(self.table[val]) == list:
                i = self.table[val].index(key)
                self.table[val][i] = None
            else:
                self.table[val] = None
        else:
            KeyError()

    def lookup(self, key):
        found = False
        val = self.get_value(key)
        if type(self.table[val]) == list:
            found = key in self.table[val]
        else:
            found = self.table[val] == key
        return found

Note: This works on both Python 2 and should work in Python 3


texts: Reproduce the system() function of linux

texts:
My mentor says to reproduce the system() function of Linux exactly as given in the man pages. I have written the below code. Could someone review this code and provide me any suggestions for improvising. I am a beginner. Thanks :).

 #include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
int my_system(const char *command);

int my_system(const char *command)
{
    int ret = 0;

    ret = execl("/bin/sh", "sh", "-c", command, (char *)NULL);
    if (ret == -1)
        error(1, 0, "error occcured in the execl() system call\n");
}

int main(int argc, char *argv[])
{
    pid_t pid;
    int ret;
    int wstatus;

    if (argc > 2)
        error(1, 0, "Too many arguments\n");
    pid = fork();
    if (pid == -1) {
        error(1, 0, "error in creating the sub-process\n");
    } else if (pid == 0) {
        ret = my_system(argv[1]);
    } else {
        wait(NULL);
    }
    return 0;
}

```


texts: Determining whether a list of pathways and its genes are all included in another list

texts:
I am evaluating if a list of pathways and its genes has pathways included in another pathways. So the way I thought about it is to create a function that does just a single comparison.

all_in <- function(x, y) {
  if (length(x) > length(y)) {
    0
  } else {
    ifelse(all(x %in% y), 1, 0)
  }
}

And then Vectorize to be able to use outer

all_in_vec <- Vectorize(all_in, vectorize.args = c("x", "y"))

And use it as follows:

nested <- outer(paths2genes, paths2genes, all_in_vec)

example:

paths2genes <- structure(list(`1430728` = c("10", "9"), `156580` = c("10", "3",
"9"), `156582` = c("10", "9"), `194840` = c("2", "3"), `211859` = c("10",
"9")), .Names = c("1430728", "156580", "156582", "194840", "211859"
))

Tests:

library(testthat)
expect_true(all(diag(nested) == 1L))
expect_equal(nested[1, 2], 1L)

However I have recently found that Vectorize should be avoided in favor of a built-in vectorization. Is there any built-in method I am missing? How can I vectorize this code ?


texts: Primitive full-text search on some properties of an object

texts:
I am not a JS/TS Guru, so i wanted to ask if one could write this better.

I needed a very primitive Full-Text-Search of some properties of an Object. What do you think?

export const search = <T, K extends keyof T>(term: string, objects: T[], keys: K[]): T[] => {
  const foundObjects = objects.filter(x => {
    for (const key of keys) {
      if (x.hasOwnProperty(key) === false) {
        continue;
      }

      const val = x[key];

      if (typeof val === 'string' && val.toLowerCase().includes(term)) {
        return true;
      } else {
        continue;
      }
    }
    return false;
  });
  return foundObjects;
};


texts: Initialize and sum an array in Java using threads

texts:
This bit of code initializes an array of any given size where each index corresponds to a thread and a value. That is, index 0 has 0, index 1 has 1, and so on. Then, the values, 0 to n, in the indexes are summed.

This code as part of an assignment though I'm wondering if there are any ways it could be improved? Namely, is there an alternative to using 2 for loops and calling thread.join() on them?

I'd be open to any advice and would gladly take it!

public class Processor {

    static volatile int numberOfValues = 17;
    static double processedArray[];
    static Thread threadsArray[];
    static volatile int sum;
    static Object lock1 = new Object();
    static Object lock2 = new Object();

Adding values to the array, each index in the array gets a thread to initialize that value:

    private static void initializeArray() {
        threadsArray = new Thread[numberOfValues];
        processedArray = new double[numberOfValues];

        for (int i = 0; i < threadsArray.length; i++) {
            threadsArray[i] = new Thread(new Runnable() {
                public void run() {
                    synchronize(lock1) {
                        processedArray[numberOfValues - 1] = numberOfValues;
                        numberOfValues--;
                    }

                }
            });
            threadsArray[i].start();
        }

Here is the first for loop joining all threads after the initialization of the array:

        for (int i = 0; i < threadsArray.length; i++) {
            try {
                threadsArray[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

Summing the values in the array:

        for (int i = 0; i < threadsArray.length; i++) {
            threadsArray[i] = new Thread(new Runnable() {
                public void run() {
                    synchronize(lock2) {
                        sum += processedArray[numberOfValues];
                        numberOfValues++;
                    }

                }
            });
            threadsArray[i].start();
        }

Here is the second for loop joining all the threads after summing:

        for (int i = 0; i < threadsArray.length; i++) {
            try {
                threadsArray[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

Main:

    public static void main(String args[]) {
        initializeArray();
        for (int i = 0; i < threadsArray.length; i++) {
            System.out.println(processedArray[i]);
        }

        System.out.println("Sum: " + sum);
    }
}