texts:
I recently watched a video in which the speaker said that Haskell is not suited for real-world tasks, such as copying files from one folder to another.
So I tried to write a program that copies a given file system tree to a new location. The usage of the program is

copy_tree <source path> <target path>

If the target path does not exists, it is created. Then all folders and files under <source path> are copied to <target path>. Here is my copy_tree.hs source. I would like to have feedback and suggestions on how to improve it. Especially, I would like to make it as succinct and as idiomatic as possible.

One thing that I do not like very much is that the code calls doesDirectoryExist twice.

import System.Directory
import System.Environment
import System.FilePath

getSubitems path = getSubitemsRec ""
  where
    getChildren path = do
        isDir <- doesDirectoryExist path
        if isDir
          then fmap (filter (`notElem` [".", ".."])) (getDirectoryContents path)
          else return []

    getSubitemsRec relPath = do
        children <- getChildren (path </> relPath)
        let relChildren = [relPath </> p | p <- children]
        nephewItems <- mapM getSubitemsRec relChildren
        return (relChildren ++ (concat nephewItems))

copyItem baseSourcePath baseTargetPath relativePath = do
    let sourcePath = baseSourcePath </> relativePath
    let targetPath = baseTargetPath </> relativePath

    putStrLn $ "Copying " ++ sourcePath ++ " to " ++ targetPath
    isDir <- doesDirectoryExist sourcePath
    if isDir
      then createDirectoryIfMissing False targetPath
      else copyFile sourcePath targetPath

copyTree s t = do
    subItems <- getSubitems s
    createDirectoryIfMissing True t
    mapM_ (copyItem s t) subItems

main = do
    args <- getArgs
    if (length args) == 2
      then copyTree (args !! 0) (args !! 1)
      else putStrLn "Usage: copy_tree <source> <target>"


texts: Customizing color for the navbar of my Android app

texts:
I got my navigation bar to be the color I want of Blue background with white text.

Here is my code which works but this feels totally hacky. Please suggest improvements
styles.xml
<resources>
    <style name="AppTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#6a9abd</item>
        <item name="android:titleTextStyle">@style/TitleBarTextColor</item>
    </style>

    <style name="TitleBarTextColor" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:textColor">#ffffff</item>
    </style>
</resources>


texts: Changing these two functions into one function

texts:
I have two functions that are similar. The only differences is that they're using two different models. How can I change them into one function?

 ITagRepository tagRepo = new TagRepository();
 ICategoryRepository catRepo = new CategoryRepository();

public void AddTagsDontExist(string tags)
    {
        var allTags = tagRepo.GetAllQueryAble();
        string[] tag = tags.Split(',');

        foreach (var item in tag)
        {
            if (allTags.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                tagRepo.Add(new Tag
                 {
                     Name = item.ToString(),
                     DateAdded = DateTime.Now,
                     LastModifiedDate = DateTime.Now,
                     IsDeleted = false
                 });
            }
        }
    }

    public void AddCategoriesDontExist(string Categories)
    {
        var allCategory = catRepo.GetAllQueryAble();
        string[] Category = Categories.Split(',');

        foreach (var item in Category)
        {
            if (allCategory.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                catRepo.Add(new Category
                {
                    Name = item.ToString(),
                    DateAdded = DateTime.Now,
                    LastModifiedDate = DateTime.Now,
                    IsDeleted = false
                });
            }
        }
    }


texts: iterate over an array and delete elements conditionally

texts:
The following logic:

Iterate over the URLs array and If the HTTP request with the given URL does not timeout, continue. If the URL times out, remove it from the array and continue with the next one until the array is exhausted.

Has been implemented in the following way:

@urls.delete_if do |url|
  begin
    doc = perform_request(some_params)
    break
  rescue TimeoutError
    Rails.logger.warn("URL #{url} times out, will be removed from list")
    true
  end
end

Anyone for a cleaner solution? Basically, I want to iterate over an array and remove elements from it if there is a timeout, but if the URL works loop should end and app should continue processing.


texts: How to make this ping test with timer more efficient?

texts:
I wrote a small ducktaped VBA script which pings servers every 15 mins or so.  If a server's status is anything other than "Alive", the server and timestamp is written to another worksheet called "Log".

Sub Countup()
    Dim CountDown As Date
    CountDown = Now + TimeValue("00:00:01")
    Application.OnTime CountDown, "Auto_Open"
End Sub

Sub Auto_Open()
    Dim count As Range

    Set count = Worksheets("Servers").Range("A1:A1")
    count.Value = count.Value - TimeSerial(0, 0, 1)
    If count <= 0 Then
        count = Worksheets("Servers").Range("C1:C1")
        Call GetComputerToPing
        Call Countup

        Exit Sub
    End If
    Call Countup
End Sub

Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal Col As Integer)
    Dim lLastRow As Long
    Dim iHeader As Integer

    With ActiveSheet.ListObjects(strTableName)
        'find the last row of the list
        lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.count
        'shift from an extra row if list has header
        If .Sort.Header = xlYes Then
            iHeader = 1
        Else
            iHeader = 0
        End If
    End With
    'add the data a row after the end of the list
    ActiveSheet.Cells(lLastRow + 1 + iHeader, Col).Value = strData
End Sub

'Requires references to Microsoft Scripting Runtime and Windows Script Host Object Model.
'Set these in Tools - References in VB Editor.

Function sPing(sHost) As String
    On Error Resume Next
    sHost = Trim(sHost)
    Dim ipaddress As String
    Dim computername As String
    Dim Model As String
    Dim memory As Long

    Dim oPing As Object, oRetStatus As Object
    Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}")
    Set oPing = oPing.execquery("select * from win32_pingstatus where address ='" & sHost & "'")
    For Each oRetStatus In oPing
        If IsNull(oRetStatus.statuscode) Then
            sPing = "Dead"
        ElseIf oRetStatus.statuscode = 11010 Then
            sPing = "Request Timed Out"
        ElseIf oRetStatus.statuscode = 11013 Then
            sPing = "Destination Host Unreachable"
        Else
            sPing = "Alive"
        End If
    Next
    Set oPing = Nothing
    Set oRetStatus = Nothing
End Function

Sub GetComputerToPing()
    Application.DisplayAlerts = False
    'On Error Resume Next
    Dim applicationobject As Object
    Dim i As Integer

    i = 3 'row to start checking servers from
    Do Until Cells(i, 1) = ""
        'If Cells(i, 1) <> "" Then
            'If Cells(i, 2) = "Request Timed Out" Or Cells(i, 2) = "" Or Cells(i, 2) = "Dead" Then
                Cells(i, 2) = sPing(Cells(i, 1))
                Cells(i, 3) = Now()

                'log it to Log
                If Cells(i, 2).Value <> "Alive" Then
                    Call copytest(i)
                End If
            'End If
        'End If
        i = i + 1
    Loop
Set applicationobject = Nothing
End Sub

Function findlast_Row() As Long
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Log")

    With ws
        findlast_Row = .Range("A" & .Rows.count).End(xlUp).Row
    End With
End Function
Sub copytest(ByVal intRow As Integer)
    'screens for last row in log sheet
    iLastRow = findlast_Row() + 1
    Worksheets("Log").Range("A" & CStr(iLastRow) & ":E" & CStr(iLastRow)).Value = Worksheets("Servers").Range("A" & CStr(intRow) & ":E" & CStr(intRow)).Value
End Sub

Is there another way (or better way) to do the countdown timer?


texts:
Is it OK to do that ?

for example, I have my log out service

  logout: function() {
    var defer = $q.defer();

    this.getCustomer().then(function(credentials) {
      $http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout',
      {username: credentials.username, customer: credentials.customer}
    ).success(function(data) {
        if (data.error) {
          defer.reject(data);
        }
        LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER).then(function() {
          /*Removing LocalForage Items*/
          cleanLocalForage();
          defer.resolve(data);
        }, function(err) {
          console.log(err);
          defer.reject(data);
        });
      }).error(function(data) {
        cleanLocalForage();
        defer.reject(data);
      });
    }, function(err) {
      defer.reject(err);
    });
    return defer.promise;
  },

and then I have a function in a controller which returns an error once the session expires. When the session expires I need to logout the user and redirect him to the login path. So, this is what I have so far:

$scope.removeSlip = function(slip) {
  BetSlipFactory.removeSlip(slip).then(function() {
  }, function(err) {
    console.log(err);
    AuthFactory.logout();
    $location.path('/');
  });
};

or should I do something like this with the logout promise into the BetSlipFactory.removeSlip() promise ?

$scope.removeSlip = function(slip) {
  BetSlipFactory.removeSlip(slip).then(function() {
  }, function(err) {
    console.log(err);
    AuthFactory.logout().then(function() {
     $location.path('/');
    })
  });
};

there is my question: what is the proper way in this case ?


texts: Processing lexical analyses of sentences using the Perl split function

texts:
I have two kinds of lexical analyses of sentences that I need to process.  One type of data comes in a "tagged" format, and the other comes in a "parsed" format.

Tagged

The input (@subsentences) looks like:

5.4_CD Passive_NNP Processes_NNP of_IN Membrane_NNP Transport_NNP 85_CD We_PRP have_VBP examined_VBN membrane_NN structure_NN and_CC how_WRB it_PRP is_VBZ used_VBN to_TO perform_VB one_CD membrane_NN function_NN :_: the_DT binding_JJ of_IN one_CD cell_NN to_TO another_DT ._.

Desired output

5.4 Passive Processes of Membrane Transport 85 We have examined membrane stru....

My code

@finalsentence = split(/_\S+/,$subsentences[$j]);

Parsed

   Parsing [sent. 1 len. 31]:
        nsubj(85-7, Processes-3)
        nn(Transport-6, Membrane-5)
        prep_of(Processes-3, Transport-6)
        nsubj(examined-10, We-8)
        nsubjpass(used-17, it-15)
        xsubj(perform-19, it-15)
        conj_and(examined-10, used-17)
        xcomp(used-17, perform-19)
        dobj(perform-19, function-22)
        prep_of(binding-25, cell-28) <- refer to this for examples below

Desired output (for the last line)

the sent. number (ie. sent. 1 )
the grammar function (ie. prep_of )
the first dependency word (ie. binding )
the second dependency word (ie. cell )

My code

Here is how I do it, but when I check for word boundaries (\b), sometimes they're not defined and on top of that, it's pretty crude:

For the sent. number:

@parsesentcounter = split (/.*sent\.\s/, $typeddependencies[$i]);
@parsesentcounter = split (/\s/, $typeddependencies[$i]);

This (crude method) leaves the sent. number (sent. 1) at $parsesentcounter[2]

For the grammar function:

@grammarfunction = split(/\(\S+\s\S+\s/,$typeddependencies[$i]);

This leaves the grammar function(prep_of) at $grammarfunction[0]

For the dependency words, I do it in a few steps (I think I get lost a bit here):

@dependencywords = split (/,\s+/,$typeddependencies[$i]); ## Take out all commas, there was also a space associated
@dependencywords = split (/-\S+\s+/,$typeddependencies[$i]); ## Take out all -digits and space

This leaves the second dependency word(cell) at $dependencywords[1].

Then for first dependency word:

@firstdependencyword = split(/.*subj\w*.|.*obj\w*.|.*prep\w*\(|.*xcomp\w*\(|.*agent\(|purpcl\(|.*conj_and\(/,$dependencywords[0]);

This leaves the first dependency word (binding) at $firstdependencyword[1]


texts: Conway's Game of Life command line program in C++

texts:
I have programmed Conway's Game of Life in C++.

/*
    Any live cell with fewer than two live neighbors dies, as if by under population.
    Any live cell with two or three live neighbors lives on to the next generation.
    Any live cell with more than three live neighbors dies, as if by overpopulation.
    Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
*/

#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <string>
#include <stdlib.h>

#define EXTRA_SPACE 1
#define GRID_SIZE 35

#define ALIVE_CELL '#'
#define DEAD_CELL ' '

struct CellCoords { int y, x; };

void setup_grid();
void generation();
void display_grid();
void sleep(int);

std::array<std::array<char, GRID_SIZE + EXTRA_SPACE * 2>, GRID_SIZE + EXTRA_SPACE * 2> grid;

int main() {

    setup_grid();

    int gen = 1;

    do {
        system("cls");
        std::cout << std::endl << "Generation " << gen << std::endl;
        display_grid();
        sleep(100);
        generation();
        gen++;
    } while (true);

    std::cin.get();
    return 0;
}

void setup_grid() {

    std::ifstream file("grid.txt");
    std::string line;
    int i = EXTRA_SPACE;

    while (std::getline(file, line)) {
        for (int j = EXTRA_SPACE; j < GRID_SIZE; j++) {
            if (line[j] == '1')
                grid[i][j] = ALIVE_CELL;
            else
                grid[i][j] = DEAD_CELL;
        }
        i++;
    }

    file.close();
}

void generation() {

    std::vector<CellCoords> cells_to_kill;
    std::vector<CellCoords> cells_to_be_born;

    int neighbors;

    for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
        for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {

            neighbors = 0;

            if (grid[y - 1][x    ] == ALIVE_CELL) neighbors++;
            if (grid[y - 1][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y    ][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x    ] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x - 1] == ALIVE_CELL) neighbors++;
            if (grid[y    ][x - 1] == ALIVE_CELL) neighbors++;
            if (grid[y - 1][x - 1] == ALIVE_CELL) neighbors++;

            if (grid[y][x] == ALIVE_CELL) {
                if (neighbors < 2 || neighbors > 3)
                    cells_to_kill.push_back({ y, x });
            } else if (neighbors == 3) {
                    cells_to_be_born.push_back({ y, x });
            }
        }
    }

    for (int i = 0; i < cells_to_kill.size(); i++) {
        CellCoords cell = cells_to_kill[i];
        grid[cell.y][cell.x] = DEAD_CELL;
    }

    for (int i = 0; i < cells_to_be_born.size(); i++) {
        CellCoords cell = cells_to_be_born[i];
        grid[cell.y][cell.x] = ALIVE_CELL;
    }
}

void display_grid() {

    std::cout << std::endl;

    for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
        for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {
            std::cout << grid[y][x] << ' ';
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

void sleep(int time) {
    for (int i = 0; i < time; i++);
}

How can I improve the code? Was making an extra 2 rows and columns in the grid array a good idea?


texts: Run multiple prerequisite methods in parallel before continuing

texts:
I have an application in which I have multiple slow running prerequisite methods I need to call in order to have the data I need to continue.

To try to speed this up I am doing this:

Dictionary<string, string> processOptions = null;
Dictionary<string, string> businessAreas = null;
Dictionary<string, string> requirementLevels = null;
List<TemplateSection> sections = null;
List<TemplateVersion> versions = null;

var prerequisiteTasks = new List<System.Threading.Tasks.Task>();

prerequisiteTasks.Add(new System.Threading.Tasks.Task(() => sections = GetSectionsInTreeForm(latestVersionGuid)));
prerequisiteTasks.Add(new System.Threading.Tasks.Task(() => versions = GetTemplateVersions(templateId)));
prerequisiteTasks.Add(new System.Threading.Tasks.Task(() => processOptions = GetOptionSetProcessPhaseTypes()));
prerequisiteTasks.Add(new System.Threading.Tasks.Task(() => businessAreas = GetOptionSetBusinessAreaTypes()));
prerequisiteTasks.Add(new System.Threading.Tasks.Task(() => requirementLevels = GetOptionSetRequirementLevelTypes()));

prerequisiteTasks.ForEach(x => x.Start());
System.Threading.Tasks.Task.WaitAll(prerequisiteTasks.ToArray());

Each of the methods above can take anything from 2-5 seconds to complete.
Is there a nicer way of doing this, or is this something I shouldent do?

P.S. the code as is works great and decreases the time used by around 30%.


texts:
I have a dataframe like:

    time_stamp           id          next_timestamp
0   2010-04-16 11:57:52  string_1    NaT
1   2010-04-16 12:06:16  string_1    NaT
2   2010-04-16 12:40:53  string_2    NaT

I want to fill next_timestamp column, with the next time_stamp that id has (if it exists).

Result would be something like:

    time_stamp           id          next_timestamp
0   2010-04-16 11:57:52  string_1    2010-04-16 12:06:16
1   2010-04-16 12:06:16  string_1    NaT
2   2010-04-16 12:40:53  string_2    NaT

My code at the moment:

for row in df.index:
    row_time_stamp = df.time_stamp[row]
    id_array = df.id[row]
    df_temp = df.loc[(df['time_stamp'] >= row_time_stamp) & \
                     (df['time_stamp'] <= row_time_stamp + datetime.timedelta(days=7))]
    try:
        next_id_msg = df_temp.loc[(df_temp['id'] == str(id_array))].time_stamp.min()
        df['next_timestamp'][row] = next_id_msg
    except IndexError:
          df['next_timestamp'][row] = pd.NaT

The problem is that my my df is 50+ million rows long, and setting up a temp table for every row is not a good pattern.

Please help me out with a better pattern.


texts: Process string vector and change each string to uppercase

texts:
The question below came from C++ primer 5th edition.

  Read a sequence of words from cin and store the values a
  vector. After you’ve read all the words, process the vector and change
  each word to uppercase. Print the transformed elements, eight words to a
  line.

I was just wondering if there is any way to improve my solution.

int main(){

    vector<string> stringVector;
    string s;
    while(cin >> s){
        stringVector.push_back(s);
    }
    for(string &s : stringVector){
        for(char &c : s){
            c = toupper(c);
        }
    }
    for (int i = 0; i != stringVector.size(); i++){
        if (i != 0 && i % 8 == 0){
            cout << endl;
        }
        cout << stringVector[i] << " ";
    }

    return 0;
}


texts:
With the help of SO I got my code working, but I think it still could be improved, in particular I do not like using asInstanceOf. Is there some way how to avoid it?

  trait UpdatedTrait[A, K, T] {
    def upd(k: K, t: T): A
  }

  trait UpdatedFunctor[A, K, T] {
    def upd(a: A, k: K, t: T): A
  }

  implicit class UpdatedMap[M[KT, TT] <: Map[KT, TT], K, T](a: M[K, T])(implicit f: UpdatedFunctor[M[K, T], K, T]) {
    def upd(k: K, t: T) = {
      f.upd(a, k, t)
    }
  }

  implicit def mapUpdatedFunctor[M[KT, TT] <: Map[KT, TT], K, T] = new UpdatedFunctor[M[K, T], K, T] {
    override def upd(a: M[K, T], k: K, t: T): M[K, T] = {
      a.updated(k, t).asInstanceOf[M[K, T]]
    }
  }

  val m = Map("A" -> "1")
  val sm = collection.immutable.SortedMap("A" -> "1")

  val mt = m.upd("A", "2")
  val smt: collection.immutable.SortedMap[String, String] = sm.upd("A", "2")

  println(mt)
  println(smt)


texts:
Challenge
Determine the largest contiguous sum of integers in a list.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case represented by a comma separated list of integers.
For each test case, find and print the largest contiguous sub-array sum.

Sample Input

-10,2,3,-2,0,5,-15
2,3,-2,-1,10

Sample Output

8
12

Source
#include <stdio.h>
#include <string.h>

#define LINE_LENGTH 1024
#define MIN_INT -32768

int largest_contiguous_sum(int *array, int size) {
    int max = MIN_INT;
    int current_max = MIN_INT;
    for (int i = 0; i < size; i++) {
        current_max = current_max + array[i] > array[i] ? current_max + array[i] : array[i];
        max = max > current_max ? max : current_max;
    }
    return max;
}

int compute_largest_contiguous_sum(char *line) {
    char seperator[] = ",";
    char *token;
    int var;
    int array[512];
    int i = 0;

    token = strtok(line, seperator);
    while (token != NULL) {
        sscanf(token, "%d", &var);
        array[i++] = var;
        token = strtok(NULL, seperator);
    }

    return largest_contiguous_sum(array, i);
}

int main(int argc, char *args[]) {
    if (argc < 2) {
        fprintf(stderr, "File path not provided. Exiting...\n");
        return 1;
    }

    if (argc > 2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    FILE *file = fopen(args[1], "r");
    if (file == NULL) {
        perror("Error");
        return 1;
    }

    char line[LINE_LENGTH];
    while (fgets(line, LINE_LENGTH, file)) {
        printf("%d\n", compute_largest_contiguous_sum(line));
    }

    fclose(file);
}

First time using strtok and wondering if there was a better tool.


texts: Reviewing the file download controller in spring rest

texts:
In my project, so this controller is working perfectly, my objective is to read the log file from the server which is created on daily basis, so I have to read the log file which is heavier in size around maybe 2GB, so my question is that please review the below code and advise my is my code is smart enough to read such heavy log file, or should I need to do some modifications in it to read such file in chunks and also look if any modifications I need to introduce into from performance point of view or exceptional handling point of view and from REST practices point of view
@GetMapping("/download")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resource> download(@RequestParam String filename) {
    File file = new File(serverLocation + File.separator + filename + EXTENSION);

    HttpHeaders header = new HttpHeaders();
    header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + EXTENSION);
    header.add("Cache-Control", "no-cache, no-store, must-revalidate");
    header.add("Pragma", "no-cache");
    header.add("Expires", "0");

    Path path = get(file.getAbsolutePath());
    Resource resource = null;
    try {
        resource = new InputStreamResource(Files.newInputStream(path));
    } catch (IOException e) {
        LOGGER.error(String.format("Exception occurred while reading the log file%s", e));
    }
    return ResponseEntity.ok()
            .headers(header)            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);

}


texts: Testing whether sums of cubes are Fibonacci numbers

texts:
I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program.

import java.lang.*;
import java.math.*;

public class FindFib
{
 public static void main(String args[])
 {
  long uLimit=9223372036854775807L;   //long maximum value
  BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D);  //Golden Ratio

  for(long a=1;a<=uLimit;a++)    //Outer Loop, 1 to maximum
   for(long b=1;b<=a;b++)     //Inner Loop, 1 to current outer
   {
    //Cube the numbers and add
    BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3));
    System.out.print(c+" ");  //Output result
    //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c]
    BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)),
     e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP));
    //Mobius test: if integer in interval (floor values unequal) Fibonacci number!
    if (d.toBigInteger().compareTo(e.toBigInteger())!=0)
     System.out.println();    //Line feed
    else
      System.out.print("\r");    //Carriage return instead
   }
  //Display final message
  System.out.println("\rDone.                                                                                ");
 }
}

Now the use of BigDecimal and BigInteger was deliberate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?


texts: LeetCode 76: Minimum Window Substring - Java

texts:
I'm posting my Java code for the Minimum Window Substring. If you have time and would like to review, please do so, I appreciate that.
Problem

Given a string string and a string target, find the minimum window
in string which will contain all the characters in target in
complexity O(n).
Example:
Input: string = "ADOBECODEBANC", target = "ABC" Output: "BANC"
Note:
If there is no such window in string that covers all characters in
target, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
string.

Java
import java.util.*;
import javafx.util.*;

class Solution {
    public String minWindow(String string, String target) {
        if (string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length()) {
            return "";
        }

        int minLeft = 0, minRight = 0, min = string.length();
        boolean flag = false;
        int targetLength = target.length();
        Map<Character, Integer> map = new HashMap<>(targetLength);

        for (char character : target.toCharArray()) {
            map.put(character, -~map.getOrDefault(character, 0));
        }

        int left = 0, right = 0;

        while (right < string.length()) {
            char character = string.charAt(right);
            map.put(character, map.getOrDefault(character, 0) - 1);

            if (map.get(character) > -1) {
                targetLength--;
            }

            while (targetLength == 0 && left <= right) {
                flag = true;
                int curLength = -~right - left;

                if (curLength <= min) {
                    minLeft = left;
                    minRight = right;
                    min = curLength;
                }

                char leftChar = string.charAt(left);
                map.put(leftChar, -~map.getOrDefault(leftChar, 0));

                if (map.get(leftChar) > 0) {
                    targetLength++;
                }

                left++;
            }

            right++;
        }

        return flag == true ? string.substring(minLeft, -~minRight) : "";
    }
}

Reference

Question

Solution

Discussion


texts: Initialize a Sieve of Eratosthenes in Scala

texts:
I am learning Scala while solving some exercises and I am currently solving an exercise where I need to initialize a Sieve of Eratosthenes.

I am using the following code:

  val sieve = Array.fill[Boolean](100)(true)

  for (p <- 2 until sieve.length if sieve(p) && math.pow(p, 2) <= sieve.length) {
    for (i <- p * 2 until sieve.length by p) {
      sieve(i) = false
    }
  }

I see some problems with this approach, for example, the outer loop still evaluates all numbers from some Y until sieve.length to test the condition sieve(p) && math.pow(p,2) <= sieve.length, although the code inside the loop is not executed for those values of p.

I think this could be solved with the following code:

 var p = 2
 while(math.pow(p, 2) <= sieve.length)
 {
   if(sieve(p))
     for (i <- p * 2 until sieve.length by p)
       sieve(i) = false

   p += 1
 }

I may be wrong, but I think I am complicating too much.

What's a good way to initialize a Sieve of Eratosthenes using Scala?


texts:
I am really new at this and I was wondering if there is a more efficient way of writing this code, which converts time format to 12-hour from 24-hour format, and vice-versa.

For example 07:16:35PM converts to 19:16:35, and 13:05:25 to 1:05:25PM.

public static void convertTimeTo24(String time)
{

    if(time.substring(8,10).equals("PM") && Integer.parseInt(time.substring(0,2)) < 12)
        {
            String hour12 = time.substring(0,2);
            int hour24 = (Integer.parseInt(hour12)) + 12;

            if(hour24<24)
                {
                System.out.print(hour24+time.substring(2,8));
                }

            if(Hour24>23)
                {
                System.out.print(00+time.substring(2,8));
                }
        }

    else if(time.substring(8,10).equals("AM") && Integer.parseInt(time.substring(0,2)) == 12)
        {
        System.out.print("00"+time.substring(2, time.length()));
        }

    else
        {
       System.out.print(time.substring(0,8));
        }
}

public static void convertTimeTo12(String time)
{
    int hour24 ;
    if(Integer.parseInt(time.substring(0, 2)) > 12 ) //check if the hr is greater than 12
        {
            hour24 = Integer.parseInt(time.substring(0, 2)) - 12; //substract 12 from the hr
            if(hour24 < 10)
                {
                System.out.println("0"+hour24 + time.substring(2, time.length())+"PM"); //print hour the hour in 24hr format
                }

            else
                {
                System.out.println(+hour24 + time.substring(2, time.length())+"PM"); //print hour the hour in 24hr format
                }
        }

    if(Integer.parseInt(time.substring(0, 2)) == 0 )
        {
        hour24 = Integer.parseInt(time.substring(0, 2)) + 12; //print hour the hour in 24hr format
        System.out.println(hour24 + time.substring(2, time.length())+"AM"); //print hour the hour in 24hr format
        }

}

public static void main(String[] args) {
           Scanner in = new Scanner(System.in);
           String time = in.nextLine();      //sets time to string input
           if(time.length()<10)      //check if input is in 24hours format or 12
             convertTimeTo12(time); //call the convert function above if its 12 hrs format
           else
           convertTimeTo24(time); // calls function to convert 12hr to 24hr format

}

}


texts: Swapping of element with its neighboring element (Python)

texts:
Does this code seems good or it can be improve (without any library)?
Elements swapping of a list with its neighboring element
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

lenofalist = len(alist)

index = 0
temp = 0
last_element = 0
if lenofalist % 2 != 0:

    last_element = alist.pop()
    lenofalist -= 1

    while index < lenofalist:
        temp = alist[index+1]
        alist[index+1] = alist[index]
        alist[index] = temp
        index += 2

    alist.append(last_element)

else:
    while index < lenofalist:
        temp = alist[index+1]
        alist[index+1] = alist[index]
        alist[index] = temp
        index += 2


texts: Solution to a simple Hackerrank problem: Compare the Triplets

texts:
Given two equally sized arrays of integers A and B, compute the number of times A[i] > B[i] and the number of times A[i] < B[i] for each index i.

New to scala, I put together the following solution:

import scala.io.Source

object Solution {

    def main(args: Array[String]) {
        val lines = Source.stdin.getLines
        val alice = lines.next.split(" ").map(_.toInt)
        val bob = lines.next.split(" ").map(_.toInt)

        val competitions = alice zip bob
        val scoreA = competitions.count(c => c._1 > c._2)
        val scoreB = competitions.count(c => c._1 < c._2)

        printf("%d %d", scoreA, scoreB)
    }
}

I normally solve these problems using python, so I simply searched online for my usual programming constructs. I have a few questions.

Is there a more general way to print a list of space separated integers? Currently my use of printf is limited to exactly two.
Are there any pitfalls I'm unaware of?
Ideas of more concise solutions without sacrificing readability?

Any other insights would be greatly appreciated!


texts: How to write save block code like this more elegant in Ruby?

texts:
I have a class Creator which will execute a block code for a number of times. I'm not sure how to write this in a more elegant way in Ruby.

class Creator
    attr_accessor :block
    def self.create(&block)
        @block = block
        return self
    end

    def self.for(number)
        0.upto(number) {
            block.call
        }
    end
end

And this is how I call it which I want to stay like this.

Creator.create{
  SomeModel.create!(@attr)
}.for(30)


texts: UPenn Homework 3: localMaxima :: [Integer] -> [Integer]

texts:
Please see this question for the general description.
Exercise 2: localMaxima :: [Integer] -> [Integer]
A local maximum
of a list is an element of the list which is strictly
greater than both the elements immediately before and after it
localMaxima :: [Integer] -> [Integer]
localMaxima l =
  let getMaxOf3 x y z | x < y && y > z = Just y
                          | otherwise = Nothing
      accumulate l2 acc = case l2 of
                           u:v:w:xs -> case (getMaxOf3 u v w) of
                                        Just q -> accumulate (v:w:xs) (q:acc)
                                        Nothing -> accumulate (v:w:xs) acc
                           otherwise -> []
  in reverse (accumulate l [])


texts: Emitting multiple States for Single Input using ViewModelType architecture

texts:
Below I have enum representing State of a UITableView.
The states are divided into 3 categories as below.
For all the 3 states I have different UITableViewCells which will be shown for respected cases.
So for fetchMovies input, I am actually checking the movies count and emitting the state & once again after the result.
Can the code written in transform be further reduced or any suggestions.
You can find the architecture here CleanArchitectureRxSwift
import Foundation
import RxSwift
import RxCocoa

protocol ViewModelType {
  associatedtype Input
  associatedtype Output

  func transform(input: Input) -> Output
}

enum MoviesViewModelState {
  case loading
  case loaded([String])
  case loadRemaining
}

class MoviesViewModel: ViewModelType {

  deinit {
    print("HomeViewModel deinit")
  }

  struct Input {
    let fetchMovies: Driver<Void>
  }

  struct Output {
    let movieSection: Driver<MoviesViewModelState>
  }

  var repository: SyncRepository
  private var names: [String] = []
  private let disposeBag = DisposeBag()

  init(repository: SyncRepository) {
    self.repository = repository
  }

  func transform(input: Input) -> Output {
    let movieSection = PublishSubject<MoviesViewModelState>()

    input.fetchMovies
      .asObservable()
      .flatMapLatest { [unowned self] _ -> Observable<[String]> in
        if self.names.count > 0 {
          movieSection.onNext(.loadRemaining)
        } else {
          movieSection.onNext(.loading)
        }
        return self.repository.fetchNames(for: self.names.count) // returns Observable<[String]>
    }.subscribe(onNext: { [unowned self] (names: [String]) in
      self.names.append(contentsOf: names)
      movieSection.onNext(.loaded(self.names))
    }).disposed(by: disposeBag)

    return Output(movieSection: movieSection.asDriverOnErrorJustComplete())
  }
}

extension ObservableType {
  func asDriverOnErrorJustComplete() -> Driver<Element> {
    return asDriver { _ in
      return Driver.empty()
    }
  }
}


texts: Getting integer values and one CSS class name

texts:
Here, my function is getting four integer values and one CSS class name. Based on their equality I'm creating few more CSS proprties. If all four elements passed are different then I'm using default CSS properties.

How can make this code elegant? I wanted to get rid of if else conditions.

Note: I tried with switch statements too but I felt it's the same as if else loops.

twoEqualElementsCss(cssClass1, cssClass2) {
var dict = {};
dict[cssClass1] = { padding: '12, 17' };
dict[cssClass2] = { padding: '12, 17', offset: '-2' };
return dict;
}

threeEqualElementsCss(cssClass1, cssClass2, cssClass3) {
var dict = {};
dict[cssClass1] = { padding: '12, 30', offset: '1' };
dict[cssClass2] = { padding: '12, 30', offset: '-14' };
dict[cssClass3] = { padding: '12, 30', offset: '-28' };
return dict;
}

 fourEqualElementsCss(cssClass1, cssClass2, cssClass3, cssClass4) {
var dict = {};
dict[cssClass1] = { padding: '12, 30', offset: '1' };
dict[cssClass2] = { padding: '12, 30', offset: '-14' };
dict[cssClass3] = { padding: '12, 30', offset: '-28' };
dict[cssClass3] = { padding: '12, 30', offset: '-42' };
return dict;
}

  //drawSomething is called this way from other function, which pass four values(integer) and one of the elements css class
 drawSomething(23, 26, 26, 26, element2-css);
 drawSomething(23, 26, 26, 26, element3-css);
 drawSomething(23, 26, 26, 26, element4-css);
 drawSomething(23, 26, 26, 26, element1-css);

 drawSomething(element1,element2, element3, element4, cssClassName) {

let padding = '5, 3' //default value  when all four elements are different
let offset = 100 //default value when all four elements are different
var equalElementDictionary = {}

// when 4 elements are same integer value
if (element1 == element2 && element2 == element3 && element3 == element4)
{
    //Note that each element has it's own predefined css class e.g element1 has element1-css class
    equalElementDictionary = this.fourEqualElementsCss('element1-css', 'element2-css', 'element3-css', 'element4-css')
}
else if ((element1 == element2 && element2 === element4)) { // when 3 elements are equal.
    equalElementDictionary = this.threeEqualElementsCss('element1-css', 'element2-css', 'element4-css')
}
else if ((element1 == element3 && element3 === element4)) {
    equalElementDictionary = this.threeEqualElementsCss('element1-css', 'element3-css', 'element4-css')
}
else if ((element2 == element3 && element3 === element4)) {
    equalElementDictionary = this.threeEqualElementsCss('element2-css', 'element3-css', 'element4-css')
}
else if (element4 == element1) { // when 2 elements are equal.
    equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element1-css')
}
else if (element2 == element1) {
    equalElementDictionary = this.twoEqualElementsCss('element2-css', 'element1-css')
}
else if (element4 == element3) {
    equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element3-css')
}
else if (element4 == element2) {
    equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element2-css')
}

// when dicitionary does not have cssClassName that means all four elements are different and default values are passed to testFunction
if (equalElementDictionary[cssClassName] != undefined) {
      padding = equalElementDictionary[cssClassName].padding
  if (equalElementDictionary[cssClassName].offset != undefined) {
    padding = equalElementDictionary[cssClassName].offset
  }
}

testFunction(offset, padding)
}


texts:
I want to write a program to work out how many semi-magic squares there are.

Here is the definition of semi-magic squares

  If we define \$H_n(t)\$ is the number of semi magic squares which satisfy:

  The square is \$n*n\$ dimension
  The sum of each row elements and sum of each column elements equal to \$t\$

The first idea came to me is brute force searching. I know backtracing may be better, but I don't know how to write the program.

For example, when \$n = 3\$, \$t = 1\$.

The third constraint:

I need to clearly point out that all the matrix elements are non-negative integers. Apparently, we can get that elements \$\in[0,t]\$

According to this, we can get this table:

n\t      | 1|2|3|4|5|6|7|8
---------| -----
1        | 1|1|1|1|1|1|1|1
2        | 2|3|4|5|6|7|8|9
3        | 6|21|55|120|231|406|666|1035
4        | 24|282|2008|10147|40176|132724|381424|981541

When \$n = 3\$, it's something like this sequence.

#include<iostream>
using namespace std;
int square[3][3];

//check whether it is a semi-square
bool final_check(int n,int t)
{
    for(int i=0;i<n;i++)
    {
        int sum_col=0;
        int sum_row=0;
        for(int j=0;j<n;j++)
        {
            sum_row+=square[i][j];
            sum_col+=square[j][i];
        }
        if(sum_col!=t||sum_row!=t)
            return false;
    }
    return true;
}
void display(int n)
{
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            cout<<square[i][j]<<"\t";
        cout<<endl;
    }
    cout<<"************"<<endl;
}

//count \$H_3(1)\$
int main()
{
    int n=3,t=5;
    int total_num=0;
    for(int a=0;a<=t;a++)
    {
        square[0][0]=a;
        for(int b=0;b<=t;b++)
        {
            square[0][1]=b;
            for(int c=0;c<=t;c++)
            {
                square[0][2]=c;
                for(int d=0;d<=t;d++)
                {
                    square[1][0]=d;
                    for(int e=0;e<=t;e++)
                    {
                        square[1][1]=e;
                        for(int f=0;f<=t;f++)
                        {
                            square[1][2]=f;
                            for(int g=0;g<=t;g++)
                            {
                                square[2][0]=g;
                                for(int h=0;h<=t;h++)
                                {
                                    square[2][1]=h;
                                    for(int i=0;i<=t;i++)
                                    {
                                        square[2][2]=i;
                                        if(final_check(n,t))  //check
                                        {
                                            display(n);
                                            total_num++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    cout<<"total number of semi magic square: "<<total_num<<endl;
    getchar();
    return 0;
}

I know that my code is very bad. Could anyone help me improve the code?  There are so many for loops. If \$n = 5\$, I would have to write 25 for loops.

Does anyone have a better solution?


texts: Is ToEnumerable for multiple items a good practice?

texts:
In the similar vein as ToIEnumerable and FromSingleItem

Is this a good improvement for making lists on the fly?

SyntaxSugar.ToIEnumerable("test1","test2","test3");

vs.

new []{"test1","test2","test3"};

Code:

 public static class SyntaxSugar
{
    public static IEnumerable<T> ToIEnumerable<T>(params  T[] items)
    {
        return items;
    }
}

not technically an extension to prevent T clutter

Cons:

longer codefragment

Pros:

more finger friendly- no [] or {}
Encapsulates the collection away from being treated as an array.


texts:
I'm playing with unit-testing in Ruby. There is a situation that I don't know if is good enough or if I am doing the wrong abstraction.

I have two classes: Transaction and Account. An Account could have 0..* Transactions. The only constraint is shall not have duplicated transactions for an Account.

it "add a duplicated transaction will fails" do
  transaction = double(:transaction, id: '124-acd-345')
  expect(transaction).to receive(:==).and_return true

  subject.add_transaction transaction
  subject.add_transaction transaction.clone

  expect(subject.transactions.count).to eq 1
end

Account#add_transaction piece:

def add_transaction(transaction)
  @transactions << transaction if transactions.select { |t| t == transaction }.empty?
end

Transaction#== piece:

def ==(other)
  other.id == self.id
end

The point is: Transaction#== is already unit tested in their test class. I know that transaction == works properly. So, my approach in Account#add_transaction was Test Behavior (with that expect(transaction) ...) and Test Value, checking if there is only one transaction into object.

IMO, I didn't like this solution, but I can't find anything better to do. Tips?


texts:
I am trying to write a version of Task.WhenAll for .NET 3.5 using the "Task Parallel Library for .NET 3.5". This is what I came up with. Is there a better way of doing this?

    public static Task WhenAll(IEnumerable<Task> tasks)
    {
        var tcs = new TaskCompletionSource<object>();

        var remainingTasks = tasks.ToList();
        int count = remainingTasks.Count();
        var exceptions = new List<Exception>();

        foreach (var task in remainingTasks)
        {
            task.ContinueWith(t =>
            {
                if (Interlocked.Decrement(ref count) == 0)
                {
                    foreach (var task1 in remainingTasks)
                    {
                        if (task1.IsFaulted)
                        {
                            exceptions.Add(task1.Exception);
                        }
                    }

                    if (exceptions.Any())
                    {
                        tcs.SetException(new AggregateException(exceptions));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                }
            });
        }

        return tcs.Task;
    }


texts: Knuth–Morris–Pratt string match algorithm

texts:
The Knuth–Morris–Pratt string search algorithm is described in the paper Fast Pattern Matching in Strings (SIAM J. Computing vol. 6 no. 2, June 1977). The initial step of the algorithm is to compute the next table, defined as follows:

  The pattern-matching process will run efficiently if we have an auxiliary table that tells us exactly how far to slide the pattern, when we detect a mismatch at its jth character pattern[j]. Let next[j] be the character position in the pattern which should be checked next after such a mismatch, so that we are sliding the pattern j − next[j] places relative to the text.

The authors give the example of the pattern abcabcacab. If there is a mismatch at j=7:

abcabcacab
abcabca?

Then the pattern should be moved 3 places to the right and matching should continue with the 4th character of the pattern:

   abcabcacab
abcabca?

so next[7] = 4. In some cases we know we can skip the mismatched character entirely, for example if there is a mismatch at j=3:

abcabcacab
abc?

then the search should continue from the character after the mismatch:

    abcabcacab
abc?

These special cases are indicated by next[j] = −1.

(If you're reading the paper, note that the authors use indexes starting at 1 as in Fortran, but the Python convention is to use indexes starting at 0, so that's what I'm giving here.)

This is the code that computes the next table. Please review.

def findPattern(pattern):

    j = -1
    next = [-1] * len(pattern)
    i = 0 # next[0] is always -1, by KMP definition

    while (i+1 < len(pattern)):
        if (j == -1) or (pattern[j] == pattern[i]):
            i += 1
            j += 1
            if pattern[i] != pattern[j]:
                next[i] = j
            else:
                next[i] = next[j]
        else:
            j = next[j]

    return next

if __name__ == "__main__":

    print findPattern("aaaab")
    print findPattern("abaabc")

Output:

[-1, -1, -1, -1, 3]
[-1, 0, -1, 1, 0, 2]


texts:
What do you think about this code? Do you have some advices and remarks for me about them? I have started learning python recently.

types = {
    "str": str,
    "int": int,
    "float": float,
    "complex": complex
}

def my_input(kind, msg, msg_wrong, detail):
    """ Add-in for input(). Performs validation of the data entered.
    :param kind: data type. The keys of the dictionary types.
                 If an error occurs, a str is expected.
    :param msg: a welcome message, such as "Enter a number -> "
    :param msg_wrong: own message in case of error
    :param detail: detailed error description (True or False)
    :return: entered value with type kind
    """
    method = types.get(kind, str)
    while True:
        try:
            value = method(input(msg))
            break
        except ValueError as e:
            print(msg_wrong, detail * str(e))
    return value

msg = "-> "
msg_wrong = "Error"

print(my_input("int", msg, msg_wrong, False))
print(my_input("hello", msg, msg_wrong, True))  # wrong type, will str
print(my_input("complex", msg, msg_wrong, True))

"""
-> hi
Error
-> 15
15
-> some text
some text
-> some text 2
Error complex() arg is a malformed string
-> 4-j
(4-1j)
"""


texts:
I am trying to write a program to find the practical numbers, from an input from \$1\$ to \$n\$.

Practical numbers

My code is running correctly but it is extremely slow when calculating numbers around 50 - it gets stuck at 44.

import Foundation

func getInteger() -> Int {
    var firstNum:Int = 0
    while true {
        // get value from user. Using optional input since readLine returns an optional string.
        let input = readLine()
        // ensure string is not nil
        if let unwrappedInput = input {
            if let unwrappedInt = Int(unwrappedInput) {
                firstNum = unwrappedInt
                break
            }
            else { // the input doesn't convert into an int
                print("`\(unwrappedInput)` is not an integer. Please enter an integer")
            }
        }
        else { // did not enter anything
            print("Please enter an integer")
        }
    }

    return firstNum
}
func addOne(signArray: [Int]) -> [Int] { // finds the combinations
    var signArray2 = [Int]()
    for i in 0...signArray.count-1 {
        signArray2.append (signArray[i])
    }

    for i in 0...signArray2.count-1 {
        if signArray2[i] == 1 {
            signArray2[i] = 0
        }
        else {
            signArray2[i] = 1
            break
        }
    }
    return signArray2
}
func signEval (signArray: [Int], divArray: [Int], inNum: Int) -> Bool  {// changes 2nd
  var counts = 0
    for i in 0...divArray.count-1 {
        if signArray[i] == 0 {
counts = divArray[i] + counts        }
        if counts == inNum {
            return true
        }
    }
        return false
}
print("Please enter a number to find the summable numbers up to that number:")
var input2 = getInteger()// if num = 1 print 1 if num = 2 print 1 and 2 else print >2 1, 2
var inNum = 0
var numHalf = 0.0
var numRound = 0.0
var numCheck = false
var numCheck2 = false
var numQuarter = 0.0
var numSixth = 0.0
var divArray:[Int] = []
var theirArray = [Int]()
var signArray = [Int]()// array of 0s and 1s
var summableArray:[Int] = [1,2] // need to check if num is bigger than 2!
for input in 1...input2 {
        numHalf = Double (input) / 2.0
        numRound = round(numHalf)
        if numRound == numHalf {
            numCheck = true }
        if input > 2 && numCheck == false { // odd numbers greater than one are not summable
        }
        else { // these are possible summable nums
            numQuarter = Double (input) / 4.0
            numRound = round(numQuarter)
            if numRound == numQuarter {
                numCheck = true
            }
            else {
                numCheck = false
            }
            numSixth = Double(input) / 6.0
            numRound = round(numSixth)
            if numRound == numSixth {
                numCheck2 = true }
            else { numCheck2 = false}
            if numCheck == true || numCheck2 == true {
        theirArray = []
        divArray = []
        signArray = []
        summableArray = []
for i in 1...input {
    theirArray.append (i)
    }
for i in 1...input { // creates an array of all the diviors of inputted number
    if input%i == 0 {
        divArray.append (i)
    }
}
        for j in 1...divArray.count {//
            signArray.append(0)
        }

for i in 1...input{
let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1
    var Boolcheck = false

    for q in 1...x-1 { // i to 2^n -1 (sequence to check)
    Boolcheck = (signEval(signArray: signArray, divArray: divArray, inNum: i))// checks
        signArray = addOne(signArray: signArray)// adding the ones to the array
        if Boolcheck == true {
        summableArray.append(i)// creates array of mini summable numbers
        break
    }
        }
   if summableArray.count == input {
      print ("\(input)")
    }
}
    }
}
}


texts: Printing a sequence of numbers using two alternating threads

texts:
I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?

Main Class

public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();

}
}

Thread Class

public class MyThread1 implements Runnable{
int i = 0;
@Override
public synchronized void run() {
    while(i<10)
    {
        if(i%2==0)
        {
try{
                notify();
                System.out.println(Thread.currentThread().getName()+" prints "+i);
                i++;
                wait();

             }catch(Exception e){ e.printStackTrace(); }
        }else
        {
            try{
                notify();
                System.out.println(Thread.currentThread().getName()+" prints "+i);
                i++;
                wait();
            }catch(Exception e){ e.printStackTrace(); }
        }
    }
}
}

Can there be a better usage of wait() and notify() instead of using it in both the if conditions?


texts:
I was curious to implement something similar to SharedMutex concept.
So far only 4 methods implemented. I decided to omit try_lock, try_lock_shared and native_handle for the sake of simplicity.

#ifndef READ_WRITE_MUTEX_H__
#define READ_WRITE_MUTEX_H__

#include <atomic>
#include <mutex>
#include <condition_variable>

struct ReadWriteMutex {

  void lock() { // block everyone
    std::unique_lock<std::mutex> lock(_mutex);

    if (_writing || _readers > 0) {
      // wait while writer and/or reader(s) have finished
      _cv_writing.wait(lock, [this] {return !_writing && _readers == 0;});
    }

    _writing = true;  // set flag to block everyone
                      // current thread continue run
  }

  void unlock() {
    std::lock_guard<std::mutex> lock(_mutex);
    _writing = false;
    _cv_writing.notify_all();
    _cv_reading.notify_all();
  }

  void lock_shared() { // block writers, allow readers
    std::unique_lock<std::mutex> lock(_mutex);
    if (_writing) { // we should wait : writer is working
      _cv_reading.wait(lock, [this] {return !_writing; });
    }

    ++_readers;
  }

  void unlock_shared() {
    std::lock_guard<std::mutex> lock(_mutex);
    if (--_readers == 0) {
      _cv_writing.notify_all();
    }

  }

private:
  mutable std::mutex _mutex;
  mutable std::condition_variable _cv_writing;
  mutable std::condition_variable _cv_reading;

  std::atomic<bool> _writing = false;
  std::atomic<int> _readers = 0;

};

#endif // READ_WRITE_MUTEX_H__

C++11 support assumed.


texts: Checking if an array is initialized and allocated in VB.NET

texts:
I am creating an add-in for a piece of software our company uses, so I'm working pretty extensively with that program's API.  There are many COM object members which return or contain an array that I need to work with. Sometimes functions will return an uninitialized array (Null or "Nothing" return) or sometimes they may return an initialized array that is not allocated.  My goal is to eliminate redundant code in the form of If/Else blocks before using each array, or Try/Catch blocks to handle exceptions thrown by the array being un-initialized or un-allocated.

Note:  I'm not trying to validate any data here - that can be done in the calling code or in a function or whatever - I'm simply looking to determine if an array is in a usable state (e.g. initialized and allocated with at least one member)

I've created a member extension for arrays to check if the array is both initialized and allocated.

I'd like to get some input on whether or not this is a well designed solution or if it's total bupkis, if I'm missing anything else I should be checking for, and if improvements can be made in terms of robustness, efficiency, or general best practices; I would like to make it as fast as possible for dealing with large arrays.

Imports System.Runtime.CompilerServices

Module Module1
#Region "Extension Methods"
    <Extension()>
    Public Function IsAllocated(ByVal inArray As System.Array) As Boolean
        Dim FlagEx As Boolean = True
        Try
            If inArray Is Nothing Then
                FlagEx = False
            ElseIf inArray.Length <= 0 Then
                FlagEx = False
            ElseIf inArray(0) Is Nothing Then
                FlagEx = False
            End If
        Catch ex As Exception
            FlagEx = False
        End Try
        Return FlagEx
    End Function

#End Region
End Module


texts: Combining multiple masses to obtain a desired total mass

texts:
Here is my code. Let me describe what I do here. I have 7kg soaps, and 2kg soaps. And I have total kg that mean how many kg soaps I need. I should use 7kg soaps first, if there is no need I shouldn't use 2 kg soaps. If I don't use any 2kg soaps, it must return -1, if I use 2 kg soaps it must return the amount of how many of them I use. I have prepareCargoPacket(int 7kg soap, int 2 kg soap, int totalKg).
For example, prepareCargoPacket(2,2,16); return 1s since I use 2kg soaps one time. prepareCargoPacket(1,3,10); returns -1 because I can't get 10kg from these values, and I can't use 2kg soaps
package com.bit32.cargocalculation;

public class CargoCalculation {

/**
 * Returns how many 2Kgs soap we need to use
 *
 * @param count7Kg -> count of how many 7Kgs soaps we have
 * @param count2Kg -> count of how many 2Kgs soaps we have
 * @param totalKg  -> the needed Kg I have to get
 * @return
 */

public int prepareCargoPacket(int count7Kg, int count2Kg, int totalKg) {

int solution = -1; // if there is no answer, or no need for 2Kgs soaps, the answer is -1

// if we have 7Kg ones many more than totalKg, we should decrease it to get from 2Kgs.
if (7*count7Kg > totalKg) {
    return prepareCargoPacket(count7Kg-1, count2Kg, totalKg);

// if we have enough 7Kgs that are equal to totalKg, we will not use 2Kgs.
} else if (7*count7Kg == totalKg) {
    return solution; // solution = -1

// if we have 7Kgs less than totalKg
} else {

// currentTotalKg is equal to the amount of Kg that we can use for 2Kgs
    int currentTotalKg;
    for (int i = count7Kg; i>=0; i--) {

        currentTotalKg = totalKg - 7*i;

        if (currentTotalKg % 2 == 0 && count2Kg*2 >= currentTotalKg) {
            solution = currentTotalKg/2;
            break;

        }
        return solution;
    }

}

return solution;

}


texts:
The following stored procedure allows me to write in a file stored on my SQL Server:

CREATE PROCEDURE [dbo].[spWriteToFile]
(
  @PATH_TO_FILE nvarchar(MAX),
  @TEXT_TO_WRITE nvarchar(MAX)
)
AS
BEGIN
  DECLARE @OLE int
  DECLARE @FileID int

  EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
  EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, @PATH_TO_FILE, 8, 1
  EXECUTE sp_OAMethod @FileID, 'WriteLine', NULL, @TEXT_TO_WRITE
  EXECUTE sp_OADestroy @FileID
  EXECUTE sp_OADestroy @OLE
END

In order to grant all the needed permissions, I had to execute the following query:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Here is an exemple to execute the stored procedure:

-- NB: The folder "D:\test\" has to be created before
EXEC dbo.spWriteToFile N'D:\test\t1.txt', N'Hello World !'

My problem is that I have to run this stored procedure a lot and therefore I have some performance issues. Is there something I can improve in my implementation to improve performance ? Is there another way to write in a file using SQL Server that could be faster ? If not, I think I'll have to try to call it less often.

NB: I'm using SQL Server Express Edition 2014 in case it could be relevant to my issue.


texts: Check whether a string contains exactly one distinct vowel

texts:
Over on Stack Overflow, someone asked a simple Haskell question: how to test whether there is exactly one distinct vowel in a given string. To clarify, there can be any number of non-vowel characters, and the vowel may be repeated any number of times (at least once!), but no other vowels may occur.

I proposed the below solution, and am feeling fairly proud of it: it seems clean, short, general, and readable. I have a hard time imagining an improvement to it, but I know there is still plenty of room for me to get better at Haskell, so there is probably something cool I'm missing. Would someone please look over this, and tell me what could be better, or confirm that it truly has reached Nirvana?

exactlyOne :: Eq a => (a -> Bool) -> [a] -> Bool
exactlyOne pred [] = False
exactlyOne pred (x:xs)
  |    pred x = not . any pred . filter (/= x) $ xs
  | otherwise = exactlyOne pred xs

exactlyOneVowel :: String -> Bool
exactlyOneVowel = exactlyOne (`elem` "aeiouAEIOU")


texts:
I have the following method in a web service class.  I'm a little unhappy about the big block of new JProperty(...) calls in the for loop.  Is there a way to simplify that?

public string UserCatalog(string numericSessionId, JObject incomingRequestJson)
{
        JObject json = new JObject();
        JObject returningJson = new JObject();
        JArray userCatalogArray = new JArray();

        string deviceId = incomingRequestJson.SelectToken("deviceId", true).ToString();
        string version = getOptionalData(incomingRequestJson, "version", "1.0.0");
        requireMinVersion(incomingRequestJson);

        IEnumerable<Bookcard> catalog = readerBLL.UserCatalog(numericSessionId, deviceId);
        var publicKeyRSA = readerTools.GetPublicKey(HttpUtility.HtmlDecode(numericSessionId), HttpUtility.HtmlDecode(version));

        //Build the userCatalog json array
        foreach (Bookcard card in catalog)
        {
            JObject arrayEntry = new JObject(
                new JProperty("bookThumbnailUrl", card.bookThumbnailUrl),
                new JProperty("bookId", card.bookId),
                new JProperty("bookTitle", card.bookTitle),
                new JProperty("titlePrefix", card.titlePrefix),
                new JProperty("author", card.author),
                new JProperty("annotation", card.annotation),
                new JProperty("publisher", card.publisher),
                new JProperty("numPages", card.numPages),
                new JProperty("returnDate", card.returnDate),
                new JProperty("downloaded", card.downloaded),
                new JProperty("deviceId", card.deviceId),
                new JProperty("currentPageLabel", card.currentPageLabel),
                new JProperty("furthestPageLabel", card.furthestPageLabel),
                new JProperty("currentReadPosition", card.currentReadPosition),
                new JProperty("furthestReadPosition", card.furthestReadPosition),
                new JProperty("lastReadTimestamp", card.lastReadTimestamp),
                new JProperty("bookLength", card.bookLength),
                new JProperty("ttsEnabled", card.ttsEnabled),
                new JProperty("mackinCheckoutID", card.mackinCheckoutID),
                new JProperty("runtime", card.runtime),
                new JProperty("readerType", card.readerType),
                new JProperty("dop", card.dop),
                new JProperty("externalId", card.externalId),
                new JProperty("externalSessionKey", card.externalSessionKey),
                new JProperty("externalCheckoutSessionKey", card.externalBookSessionKey),
                new JProperty("externalCheckoutId", card.externalCheckoutId),
                new JProperty("externalAccountId", card.externalAccountId + findawayBLL.AccountSuffix)
                );
            if (card.printAllowed && !readerTools.isOldVersion(1, 3, 0, version))
            {
                arrayEntry.Add(new JProperty("printAllowed", readerTools.EncryptRSA("print_OK_" + card.bookId, publicKeyRSA)));
            }
            userCatalogArray.Add(arrayEntry);
        }

        returningJson.Add("userCatalog", userCatalogArray);
        return returningJson.ToString();
    }


texts: Creating a definition text from 3 string arguments

texts:
Here is my code to create a definition text from 3 arguments. Is there any way to make it work with better performance and look nicer?

 private const string IllegalCharacters = "\\" + "\"" + "'#,.[]{}" + " ";

 public static string CreateDefText(string mainId, string     secondaryId,    string extraText)
    {
        var sb = new StringBuilder();
        sb.Append(mainId);
        if (sb.Length > 0 && !string.IsNullOrEmpty(secondaryId))
        {
            sb.Append("_");
        }
        sb.Append(secondaryId);
        sb.Append(extraText);
        if (sb.Length > 0 && (char.IsNumber(sb[0]) || '+'.Equals(sb[0]) || '-'.Equals(sb[0])))
        {
            sb.Insert(0, "N");
        }
        foreach (var illegalChar in IllegalCharacters)
        {
            sb.Replace(illegalChar.ToString(CultureInfo.InvariantCulture), string.Empty);
        }
        return sb.ToString();
    }


texts: Swift append an array when it's been declared as Any

texts:
I'm learning Swift and I have a following problem: I create a dictionary containing some data, one of which is stored as an array. I want make an operation on this array to add some info. Currently I have managed to achieve this by writing this code:

var myDictionary = [String: Any]()

myDictionary = [
    "name": "Wiktor",
    "age": 25,
    "scores": [1, 2, 3, 4, 5, 6],
]

var l = myDictionary["scores"] as? [Int] ?? [Int]()
l.append(100)
myDictionary["scores"] = l
print("\(myDictionary["scores"]!)")

This works, meaning an array with value 100 is printed out, but this solution seems a little bit over engineered to me. Can I do it easier, more like:

myDictionary["scores"].append(100)

in python?


texts: Putting data from 3 text files into 3 variables

texts:
I have the following code, which gets the data from 3 text files and puts them into 3 variables. How can I refactor this to make it smaller?

$handle = fopen($template_filename, "r");
if (filesize($template_filename) > 0)
{
    $email_template = fread($handle, filesize($template_filename));
}
fclose($handle);

// get the subject from a text file
$handle = fopen($subject_filename, "r");
if (filesize($subject_filename) > 0)
{
    $subject_template = fread($handle, filesize($subject_filename));
}
fclose($handle);

// get the footer from a text file
$handle = fopen($footer_filename, "r");
if (filesize($footer_filename) > 0)
{
    $footer_template = fread($handle, filesize($footer_filename));
}
fclose($handle);


texts: Color swatch selector with multiple mouseover and mouseout functions

texts:
I am working on a simple mouseout and mouseover functions. Basically, I have color boxes (or swatches) and I have to get the color of the specific box when hovered and when selected. You can see how it works in the fiddle.

So I came out with a working script. But I am not sure how I can optimize or shorten the script since I will be having several color swatches. I made 2 samples swatches in this demo.

The question: is there a way to optimize/shorten it? Contents in the script were almost the same for each functions. The class names were the only ones changed.

/* COLOR SWATCH 1*/

$(".color").mouseover(function() {
   var hex = $( this ).css("background-color");
   var hexVal = $( this ).attr("value");
   var styles = {
      backgroundColor : hex
    };
    $('.selected-color').css(styles);
    $('.selected-color').text(hexVal);
});

$(".color").mouseout(function() {
    var hex = $('.active').css( "background-color");
    var hexValue = $('.active').attr("value");
    var styles = {
      backgroundColor : hex
    };
    $('.selected-color').empty();
    $('.selected-color').css(styles);
    $('.selected-color').text(hexValue);
});

$('.color').on('click', function() {
   $(this).addClass('active').siblings().removeClass('active');
    var hex = $(this).css("background-color");
    var hexVal = $('.active').attr("value");
    var styles = {
      backgroundColor : hex
    };
    $('.selected-color').css(styles);
    $('.selected-color').text(hexVal);
});

/* COLOR SWATCH 2*/

$(".color-2").mouseover(function() {
   var hexs = $( this ).css("background-color");
   var hexVal = $( this ).attr("value");
   var styles = {
      backgroundColor : hexs
    };
    $('.selected-color-2').css(styles);
    $('.selected-color-2').text(hexVal);
});

$(".color-2").mouseout(function() {
    var hex = $('.active-2').css( "background-color");
    var hexValue = $('.active-2').attr("value");
    var styles = {
      backgroundColor : hex
    };
    $('.selected-color-2').empty();
    $('.selected-color-2').css(styles);
    $('.selected-color-2').text(hexValue);
});

$('.color-2').on('click', function() {
   $(this).addClass('active-2').siblings().removeClass('active-2');
    var hex = $(this).css("background-color");
    var hexVal = $('.active-2').attr("value");
    var styles = {
      backgroundColor : hex
    };
    $('.selected-color-2').css(styles);
    $('.selected-color-2').text(hexVal);
});
.color-swatch div {
    width: 25px;
    height: 25px;
    float: left;
    border: 1px solid #313131;
    margin-right: 5px;
  }

.selected-color, .selected-color-2 {
    width: 90px;
    height: 20px;
    color: #FFF;
    text-align: center;
    padding: 2px;

}
.active, .active-2 {
    border: 3px solid #151515 !important;
}

SELECTED COLOR 1: Pink

SELECTED COLOR 2: Aqua


texts: Check of a traffic light sequence using an array and if statements

texts:
I have create a functioning automated traffic light sequence using an array and if statements. It all work correctly but I am wondering if there is anything more I can do to improve my code without changing to structure or way it works, so without the use of dictionary's etc.

<!DOCTYPE html>

    <title> Traffic Light</title>

Traffic Light

    <canvas id="myCanvas" width="200" height="300"
    style="border:1px solid #000000;">
    Your browser does not support the HTML5 canvas tag.
    </canvas>

    <button onclick="changelight()">Click</button>


texts:
Okay, I am wanting to expand my armoury within PHP, so I've been researching OO PHP. With my researched knowledge I went on to create a quick script that reads a CSV file and outputs the results.

CSV Class:

class CSV {

    private $file;

    public function __construct($filename, $mode) {
        $this->file = fopen($filename, $mode);
        return $this->file;
    }

    public function endFile() {
        return feof($this->file);
    }

    public function getCSV($mode) {
        return fgetcsv($this->file, $mode);
    }

    public function close() {
        fclose($this->file);
    }
}

The test file:

require('class.csv.php');

$csv = new CSV('postcodes.csv', 'r');

while(!$csv->endFile()) {

    $postcode = $csv->getCSV(1024);
    echo $postcode[0] . "<br />";

}

$csv->close();

I am just wondering if there are... or what are the improvements I could make in regards to the OO approach. This is purely a script for me to put the knowledge i've learnt together. I'm not another 'following the crowd person' who creates every script in an OO approach because they 'can'.

I understand it is a short script but I am wanting to make sure I have the correct approach before moving forward.


texts:
I have the following left join LINQ query that is returning the results that I expect, but it does not "feel" right. I need ALL records from the UserProfile table.

Then the LastWinnerDate is a single record from the winner table (possible multiple records) indicating the DateTime the last record was entered in that table for the user.

WinnerCount is the number of records for the user in the winner table (possible multiple records).
Video1 is basically a bool indicating there is, or is not a record for the user in the winner table matching on a third table Objective (should be 1 or 0 rows).
Quiz1 is same as Video1 matching another record from Objective Table (should be 1 or 0 rows).
Video and Quiz is repeated 12 times because they're used for a report, which is to be displayed to a user listing all user records and indicate if they have met the objectives.

var objectiveIds = new List<int>();
objectiveIds.AddRange(GetObjectiveIds(objectiveName, false));

var q =
    from up in MetaData.UserProfile
    select new RankingDTO
    {
        UserId = up.UserID,
        FirstName = up.FirstName,
        LastName = up.LastName,
        LastWinnerDate = (
            from winner in MetaData.Winner
            where objectiveIds.Contains(winner.ObjectiveID)
            where winner.Active
            where winner.UserID == up.UserID
            orderby winner.CreatedOn descending
            select winner.CreatedOn).First(),
        WinnerCount = (
            from winner in MetaData.Winner
            where objectiveIds.Contains(winner.ObjectiveID)
            where winner.Active
            where winner.UserID == up.UserID
            orderby winner.CreatedOn descending
            select winner).Count(),
        Video1 = (
            from winner in MetaData.Winner
            join o in MetaData.Objective on winner.ObjectiveID equals o.ObjectiveID
            where o.ObjectiveNm == Constants.Promotions.SecVideo1
            where winner.Active
            where winner.UserID == up.UserID
            select winner).Count(),
        Quiz1 = (
            from winner2 in MetaData.Winner
            join o2 in MetaData.Objective on winner2.ObjectiveID equals o2.ObjectiveID
            where o2.ObjectiveNm == Constants.Promotions.SecQuiz1
            where winner2.Active
            where winner2.UserID == up.UserID
            select winner2).Count(),
    };


texts: Controller method to update properties of a request

texts:
I have a view that displays details of a work order request submitted by a user. As far as security and database querying is concerned, which one of the following options would be better if I'm going to update a table named "Requests" with some changes to the properties? Is the extra query to the dbcontext in option 2 worth the security benefit?

Note: some properties omitted to reduce code.

Option 1:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(DetailsViewModel request)
{

    var model = new Request
    {
        Id = request.Id,
        RequestDate = request.RequestDate,
        Status = request.Status,
        FirstName = request.FirstName,
        LastName = request.LastName,
        LastModificationDate = DateTime.Now,
        AffiliationId = request.AffiliationId,
        IssueId = request.IssueId,
        RequestTypeId = request.RequestTypeId,

    };

    _context.Requests.Attach(model);
    var entry = _context.Entry(model);
    entry.Property(e => e.Status).IsModified = true;
    entry.Property(e => e.AffiliationId).IsModified = true;
    entry.Property(e => e.IssueId).IsModified = true;
    entry.Property(e => e.RequestTypeId).IsModified = true;
    entry.Property(e => e.LastModificationDate).IsModified = true;

    _context.SaveChanges();

    return RedirectToAction("Requests");

Option 2:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(DetailsViewModel request)
{
    var model = _context.Requests.Find(request.Id);

    model.Status = request.Status;
    model.AffiliationId = request.AffiliationId;
    model.IssueId = request.IssueId;
    model.RequestTypeId = request.RequestTypeId;
    model.LastModificationDate = DateTime.Now;

    _context.Requests.Attach(model);
    var entry = _context.Entry(model);
    entry.Property(e => e.Status).IsModified = true;
    entry.Property(e => e.AffiliationId).IsModified = true;
    entry.Property(e => e.IssueId).IsModified = true;
    entry.Property(e => e.RequestTypeId).IsModified = true;
    entry.Property(e => e.LastModificationDate).IsModified = true;

    _context.SaveChanges();

    return RedirectToAction("Requests");


texts: Empty an array on focusout - jQuery UI Autocomplete

texts:
Is it good to empty an array on focusout?

var arr = [];
$("#automobil").focus(function() {
    $.getJSON("auto.json", function(data) {
        $.each(data, function(key, value) {
            if ($.inArray(value.name, arr) === -1) {
                arr.push(value.name)
            }
        })
    });
}).autocomplete({
    source: function (request, response) {
        var term = $.ui.autocomplete.escapeRegex(request.term)
            , startsWithMatcher = new RegExp("^" + term, "i")
            , startsWith = $.grep(arr, function(value) {
                return startsWithMatcher.test(value.label || value.value || value);
            })
            , containsMatcher = new RegExp(term, "i")
            , contains = $.grep(arr, function (value) {
                return $.inArray(value, startsWith) < 0 &&
                    containsMatcher.test(value.label || value.value || value);
            });

        response(startsWith.concat(contains));
    }
}).focusout(function() {
    arr = [];
});

In this case, auto.json isn't big, so arr[] isn't big either. But, in "real world examples", there can be large amounts of data, so the array needs to be empty on focusout (after the job is done), because of resources.


texts: Check Is Anagram Scala HashMap based implementation

texts:
Here is the HashMap based implementation of the function checking whether two strings are anagrams:

Example:

isAnagram("SAVE", "VASE") // returns true
isAnagram("SAV",  "VASE") // returns false
isAnagram("SAVE", "VAS")  // returns false
isAnagram("SAVE", "VAEE") // returns false

My implementation:

def isAnagram(value1: String, value2: String): Boolean = {
  value1.length == value2.length && {
    val index = new mutable.HashMap[Char, Int]()

    def addToIndex(c: Char) = index(c) = index.getOrElse(c, 0) + 1

    value1.foreach(c => addToIndex(c))

    def decrementAndCheckInIndex(c: Char): Boolean = index.get(c) match {
      case None => false
      case Some(count) => index(c) = count - 1; true
    }

    value2.forall(decrementAndCheckInIndex) && index.forall { case (key, value) => value == 0 }
  }
}

Could you please provide feedback on this code. I am interested in the mutable data structure use here, is it ok? And in general, what can I make better?


texts: Project Euler 18/67: Maximum Path Sum Solution

texts:
I wrote my solution to Project Euler #18 and #67 in C++ (which I'm relatively new to), and was just wondering what everyone else thinks of it. It executes in 3-4ms and works flawlessly (even for triangles not given by the website). But I'm not a professional programmer or anything, so I wouldn't know if it's necessarily good or not. Anyone have any potential improvements?

The website's instructions:

  By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

   3
  7 4
 2 4 6
8 5 9 3

  That is, 3 + 7 + 4 + 9 = 23.

  Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one   hundred rows.

My code:

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
#include <vector>

int main()
{
    using namespace std;

    clock_t starttim = clock();
    //prog
    vector<vector<int>> lines;

    ifstream istrm("triangle.txt");
    string line;
    while (getline(istrm, line))
    {
        int num;
        stringstream ss(line);
        vector<int> curvec;
        while (ss >> num)
        {
            curvec.push_back(num);
        }
        lines.push_back(curvec);
    }

    for (int currow = lines.size() - 1; currow >= 0; currow--)
    {
        if (currow != 0)
        {
            for (int curidx = 0; curidx <= lines[currow].size() - 2; curidx++)
            {
                int num1 = lines[currow][curidx];
                int num2 = lines[currow][curidx + 1];
                int greater = (num1 > num2 ? num1 : num2);
                lines[currow - 1][curidx] += greater;
            }
        }
        else cout << lines[0][0] << endl;
    }

    //endprog
    cout << "Execution time - " << (((clock() - starttim) / (double)CLOCKS_PER_SEC) * 1000) << "ms." << endl;
    system("PAUSE");
    return 0;
}


texts:
This is my attempt for C# navigation with arrow keys. Basically, when the arrow down/up key is pressed, the specified option is highlighted (so it's like a WPF/WinForms ComboBox). However, I think it looks a bit ugly, and I think many things can be made better.

I put some comments into the code, to understand better what it does.

using System;

namespace Test
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            ConsoleKeyInfo consoleKeyInfo;
            int[] intArray = new int[5];
            // Index is -1 by default. That means nothing is selected.
            // I use this variable to determine, which option is selected.
            // Then I'm calling it when moving the cursor down/up.
            int index = -1;

            for (int x = 0; x < 5; x++) intArray[x] = x;
            foreach (var i in intArray) Console.WriteLine(i);
            Console.SetCursorPosition(0, 0);

            while ((consoleKeyInfo = Console.ReadKey()).Key != ConsoleKey.Enter)
            {
                if (consoleKeyInfo.Key == ConsoleKey.DownArrow)
                {
                    index++;
                    if (index == 0) // When the arrow down key is pressed first time
                    {
                        Console.SetCursorPosition(0, index);
                        Console.ResetColor();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.Write("\r" + new string(' ', Convert.ToString(intArray[index]).Length) + "\r"); // Clear current line
                        Console.Write(intArray[index]); // Rewrite it with matching index array item
                    }
                    else if (index >= 0 && index < intArray.Length)
                    {
                        Console.SetCursorPosition(0, index - 1);
                        Console.ResetColor();
                        Console.Write("\r" + new string(' ', Convert.ToString(intArray[index - 1]).Length) + "\r"); // Clear previous line
                        Console.Write(intArray[index - 1]); // Rewrite it

                        Console.SetCursorPosition(0, index);
                        Console.ResetColor();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.Write("\r" + new string(' ', Convert.ToString(intArray[index]).Length) + "\r"); // Clear current line
                        Console.Write(intArray[index]); // Rewrite it
                    }
                    // When the index is same/greater than intArray length, keep it with the same value
                    // So the index doesn't increment
                    else if (index >= intArray.Length) index = intArray.Length - 1;
                }
                else if (consoleKeyInfo.Key == ConsoleKey.UpArrow) // Up arrow is intended to work only, when the index is greater than 0 (so the second or greater option is selected)
                {
                    if (index > 0) index--;
                    if (index >= 0 && index < intArray.Length)
                    {
                        // Same as above
                        Console.SetCursorPosition(0, index + 1);
                        Console.ResetColor();
                        Console.Write("\r" + new string(' ', Convert.ToString(intArray[index + 1]).Length) + "\r");
                        Console.Write(intArray[index + 1]);

                        Console.SetCursorPosition(0, index);
                        Console.ResetColor();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.Write("\r" + new string(' ', Convert.ToString(intArray[index]).Length) + "\r");
                        Console.Write(intArray[index]);
                    }
                }
            }
        }
    }
}


texts: Testing async method call from constructor

texts:
I have a project where I want to build a more sophisticated ToDo list - basically a personal project management system. I'm just starting out with the project, and I'd like some feedback on whether my test methods are OK, as I'm pretty new to TDD. So far, for the main page that lists the daily ToDo items, I've got the following ViewModel:

public class MainVM : ViewModelBase
{
    private IEnumerable<ToDoItem> _toDoItems;
    private IRepository<ToDoItem> _toDoItemRepo;
    private bool _dataIsLoaded;

    public bool DataIsLoaded
    {
        get { return _dataIsLoaded; }
        set { Set(ref _dataIsLoaded, value, true); }
    }

    public IEnumerable<ToDoItem> ToDoItems
    {
        get { return _toDoItems; }
        set { Set(ref _toDoItems, value); }
    }

    public MainVM(IRepository<ToDoItem> toDoItemRepo)
    {
        _toDoItemRepo= toDoItemRepo;
        LoadData().ContinueWith(t => FinishedLoadingData(t));
    }

    private void FinishedLoadingData(Task loadTask)
    {
        switch (loadTask.Status)
        {
            case TaskStatus.RanToCompletion:
                DataIsLoaded = true;
                break;
            default:
                DataIsLoaded = false;
                break;
        }
    }

    public async Task LoadData()
    {
        if (!DataIsLoaded)
            ToDoItems= await _toDoItemRepo.GetAsync();
    }
}

As you can see, I want to load my data when the ViewModel is created.

I'm using the Set method from the MVVMLight toolkit to set the DataIsLoaded property- it sets the field behind and raises the PropertyChanged event for me.

I have the following test set up to test for a successful load:

    public void DataIsLoaded_is_true_if_loading_task_ran_to_completion()
    {
        AutoResetEvent testTrigger = new AutoResetEvent(false);

        TaskCompletionSource<IEnumerable<ToDoItem>> taskCompletion = new TaskCompletionSource<IEnumerable<ToDoItem>>();
        taskCompletion.SetResult(null);

        Mock<IRepository<ToDoItem>> repoMock = new Mock<IRepository<ToDoItem>>();
        repoMock.Setup(s => s.GetAsync()).Returns(taskCompletion.Task);

        MainVM vm = new MainVM(repoMock.Object);
        vm.PropertyChanged += (s, e) =>
        {
            if (e.PropertyName == nameof(MainVM.DataIsLoaded))
                testTrigger.Set();
        };

        testTrigger.WaitOne(5000);

        Assert.IsTrue(vm.DataIsLoaded);
    }

Now, I can see that there is a potential race condition here. The LoadData method could complete before the event handler is attached. As an alternative, I could use the Set method that broadcasts a message to MVVMLight's message handler in my ViewModel, and change my test method to this:

    [Test]
    public void DataIsLoaded_is_true_if_loading_task_ran_to_completion()
    {
        AutoResetEvent testTrigger = new AutoResetEvent(false);

        TaskCompletionSource<IEnumerable<ToDoItem>> taskCompletion = new TaskCompletionSource<IEnumerable<ToDoItem>>();
        taskCompletion.SetResult(null);

        Mock<IRepository<ToDoItem>> repoMock = new Mock<IRepository<ToDoItem>>();
        repoMock.Setup(s => s.GetAsync()).Returns(taskCompletion.Task);

        Messenger.Default.Register<PropertyChangedMessage<bool>>(
           this,
           message =>
           {
               if (message.PropertyName == nameof(MainVM.DataIsLoaded))
               {
                   testTrigger.Set();
               }
           });
        MainVM vm = new MainVM(repoMock.Object);

        testTrigger.WaitOne(5000);

        Assert.IsTrue(vm.DataIsLoaded);
    }

Now I don't have a race condition, but I'm a bit annoyed that I'm broadcasting a message that I don't really need for my code to work. I could wrap the whole thing in an pre-processor directive, of course, but that's just clunky.

Is there a better way to go about the whole thing?


texts: Interactive command-line binary to decimal converter

texts:
Is this the most efficient way to write this piece of code? Is there a better way of handling errors inside of a while/for loop, instead of calling back to the original function? I have tried using break or continue, but it breaks the functionality of my program. Any help would be awesome, thanks.

## calculate binary to decimal ##

def binaryToDecimal(binary):
    ### reverse the number
    decimal_num = 0
    reverse_binary = binary[::-1]
    for x in range(7,-1,-1):
        if len(binary) <= x:
            continue
        if int(reverse_binary[x]) == 1:
            decimal_num += 2**x
    print(f"Your binary number converts to {str(decimal_num)}. ")
    binaryToDecimal(checkUI())

def getUserInput():
    return input("Please enter a binary number that you "
                 "want to convert into a decimal.\n Type 'quit' to quit program.\n")

def checkUI():
    userInput = getUserInput()
    if userInput == "quit" or userInput == "q":
        quit()
    for character in userInput:
        try:
            if len(userInput) > 8:
                print("Binary numbers are a maximum of 8 digits. Please try again")
                binaryToDecimal(checkUI())
            val = int(character)
            if val != 1 or 0:
                print("Invalid binary number. Please enter a 1 or 0 (binary numbers: 11110000)")
                binaryToDecimal(checkUI())
        except ValueError:
            print("You did not enter a binary number. (11110000) Please try again.")
            binaryToDecimal(checkUI())

    return str(userInput)

binaryToDecimal(checkUI())


texts: Is coding to an interface with regards to PDO the right thing to do?

texts:
Am I on the right lines for connecting to my Database? If not could somebody help me improve it or point me in the right direction?

Index.php:

use Acme\Foo\Database\Connector;
use Acme\Foo\Database\MySQLConnector;

$obj = new Connector(new MySQLConnector);
echo $obj->db->connect();

DatabaseInterface.php:

interface DatabaseInterface {
    public function connect();
}

MySQLConnector.php:

use Acme\Foo\Database\DatabaseInterface;
use PDO;

class MySQLConnector implements DatabaseInterface
{
    public function connect()
    {
        $user = 'root';
        $pass = 'root';
        try {
        return new PDO('mysql:host=localhost;dbname=test', $user, $pass);
        }
        catch (\PDOException $e)
        {
            throw new \Exception($e->getMessage());
        }
    }
}

Connector.php:

class Connector
{
    public function __construct(DatabaseInterface $db)
    {
        $this->db = $db;
        $this->db->connect();
    }
}


texts: Jvector Map add/remove function shorten code

texts:
I am achieving a hover state per continent through:

var continentId =""
function getID(continentId){
    jQuery.each(mapObject.mapData.paths, function(i, val) {
            if (val.continent == continentId){
                continentCodes[i] = "#3e9d01";
                mapObject.series.regions[0].setValues(continentCodes);
            }
    });
}

function removeGetID(continentId){
    jQuery.each(mapObject.mapData.paths, function(i, val) {
            if (val.continent == continentId){
                continentCodes[i] = "#128da7";
                mapObject.series.regions[0].setValues(continentCodes);
            }
    });
}

//LIST COUNTRIES & CONTINENTS TEMP
jQuery('.continentLink').hover(function(e) {
    continentId = this.id;
    getID(continentId);
}, function(){
    removeGetID(continentId);
});

Is there any way to shorten this so that I don't have to have multiple each statements?  I'm really trying to learn to write efficient code.

Here's the full code if it helps: JSFIDDLE

jQuery(function(){
//JSON MARKERS
var markers = [{latLng: [-34.033333300000000000, 23.066666700000040000], name: 'Knysna', info:'its got a lake...'},
    {latLng: [-33.924868500000000000, 18.424055299999963000], name: 'Cape Town', info:'its nice...'}];
//JSON MARKERS

//JSON STYLING
var markerStyle = {initial: {fill: '#F8E23B',stroke: '#383f47'}};
var regionStyling = {initial: {fill: '#128da7'},hover: {fill: "#A0D1DC"}};
//JSON STYLING

//GLOBAL VARIABLES
var countryList = "", continentList = "";
var resultsDup = {};
var continentCodes = {};
//GLOBAL VARIABLES

//INIT MAP PLUGIN
jQuery('#world-map').vectorMap({
    map: 'world_mill_en',
    normalizeFunction: 'polynomial',
    markerStyle:markerStyle,
    regionStyle:regionStyling,
    backgroundColor: '#383f47',
    series: {regions: [{values: {},attribute: 'fill'}]},
    markers: markers,
    onRegionClick:function (event, code){
        jQuery('#world-map').vectorMap('set', 'focus', code);
    },
    onMarkerClick: function(events, index){
        jQuery('#infobox').html(markers[index].name);
    }
});
//INIT MAP PLUGIN

var mapObject  = jQuery('#world-map').vectorMap('get', 'mapObject');

//LIST COUNTRIES & CONTINENTS
jQuery.each(mapObject.mapData.paths, function(i, val) {

    countryList += '
'+val.name+'
';

    //remove duplicate continents
    var resultsList = val.continent;
    if (resultsDup[resultsList]) {
        jQuery(this).remove();
    }else{
        resultsDup[resultsList] = true;
        continentList += '
'+val.continent+'
';
    }
    //remove duplicate continents

});
//display countries
jQuery('#countryList').html(countryList);

//display continents
jQuery('#continentList').html(continentList);

var continentId =""
function getID(continentId){
    jQuery.each(mapObject.mapData.paths, function(i, val) {
            if (val.continent == continentId){
                continentCodes[i] = "#3e9d01";
                mapObject.series.regions[0].setValues(continentCodes);
            }
    });
}

function removeGetID(continentId){
    jQuery.each(mapObject.mapData.paths, function(i, val) {
            if (val.continent == continentId){
                continentCodes[i] = "#128da7";
                mapObject.series.regions[0].setValues(continentCodes);
            }
    });
}

//LIST COUNTRIES & CONTINENTS TEMP
jQuery('.continentLink').hover(function(e) {
    continentId = this.id;
    getID(continentId);
}, function(){
    removeGetID(continentId);
});

//Zoom to Country Function
jQuery('.countryLink').click(function(e) {
    jQuery('#world-map').vectorMap('set', 'focus', this.id);
});

//Continent Hover function

});