texts: Handling CRUD methods with gorm and go-swagger

texts:
I've an application that uses gorm and go-swagger for a simple API.

One of the route's handlers bloated to 66 lines, being quite straightforward by performing the basic sanity-checks:

// CreateJWToken will create a JWToken based on credentials
func (u *Users) CreateJWToken(params users.CreateJWTokenParams) middleware.Responder {
    if params.Body == nil || params.Body.Email == nil || params.Body.Password == nil {
        message := "Email or password invalid"
        return users.NewCreateJWTokenUnauthorized().WithPayload(&models.Error{Message: &message})
    }

    var user types.User
    err := u.DB.First(&user, "email = ?", params.Body.Email).Error
    if err != nil {
        message := "Failed to create the token"
        return users.NewCreateJWTokenDefault(500).WithPayload(&models.Error{Message: &message})
    }

    if user.ID == 0 {
        message := "User not found"
        return users.NewCreateJWTokenUnauthorized().WithPayload(&models.Error{Message: &message})
    }

    if !u.checkPasswordHash(*params.Body.Password, *user.Password) {
        message := "Unauthorized"
        return users.NewCreateJWTokenUnauthorized().WithPayload(&models.Error{Message: &message})
    }

    // Generate JWToken
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "user_id": user.ID,
        "nbf":     time.Date(2018, 11, 21, 12, 0, 0, 0, time.UTC).Unix(),
    })

    // Decode the HMAC secret
    hmacSecret, err := hex.DecodeString(u.Config.JWTHmacSecret)
    if err != nil {
        message := "Failed to decode HMAC secret"
        log.Fatal(message, err.Error())
        return users.NewCreateJWTokenDefault(500).WithPayload(&models.Error{Message: &message})
    }

    // Sign and get the complete encoded token as a string using the secret
    tokenString, err := token.SignedString(hmacSecret)
    if err != nil {
        message := "Failed to sign the token"
        return users.NewCreateJWTokenUnauthorized().WithPayload(&models.Error{Message: &message})
    }

    // Store the JWToken in the database
    var dbToken types.JWToken
    dbToken.User = user
    // Hash the token, we don't want to store it in plain text
    hash := utils.HashFromString(&tokenString)
    dbToken.Token = &hash

    // Save to the database
    err = u.DB.Create(&dbToken).Error
    if err != nil {
        message := "Failed to create the token"
        return users.NewCreateJWTokenDefault(500).WithPayload(&models.Error{Message: &message})
    }

    // Build the response
    payload := models.JWToken{
        Token: &tokenString,
    }

    return users.NewCreateJWTokenCreated().WithPayload(&payload)
}

Most of the code are the sanity-checks and there doesn't seem to be much to refactor into generalized functions.

Is this length fine? How could this be structured this better?


texts:
I'm new to React and started this project as a sandbox to experiment with it. I implemented a main page wich has a header and some content. The content is selected on the header. I'm wondering how it stands on the react best practices and other ways it could be implemented.

On the main app, we hold as state the index of the content we want to show, and we pass to the header as a property a reference to the funtion that handles the index state, like so

 class App extends Component {
  constructor() {
    super();
    this.state = {
      cidx: 0,
      //content:[<Heroes/>, <Teams/>]
    }

    this.updateContent = this.updateContent.bind(this);
    this.getContent = this.getContent.bind(this);
  }

  updateContent(idx) {
    this.setState({cidx:idx});
  }

  getContent() {
    //return this.state.content[this.state.cidx];
    switch(this.state.cidx) {
      case 0:
        return <Heroes/>
      case 1:
        return <Teams/>
    }
  }

  render() {
    const Content = this.getContent();
    return (

        {Content}

    );
  }
}

export default App;

Like that we can inject the content in our render function based on user interaction with the header. I used a switch statement in getContent to avoid having an array of objects in memory all the time. Is it actually better performance-wise ?

This is the header code

class Header extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const items = this.props.textItems.map(
      (item, index)=>{
        return <NavItem key={index} onClick={()=>{this.props.updateContent(index)}}>{item}</NavItem>
      }
    );
    return (

        <Navbar className="deep-purple" brand='Dota Wizard' right>
          {items}
        </Navbar>

    );
  }
}

export default Header;

A working version of the project is found on https://glitch.com/~absorbing-buzzard


texts:
From Hacker Earth:

Problem Statement:
Chotu's father is the owner of a Vada Pav shop. One Sunday, his father takes him to the shop. Father tells him that at the end of the day, Chotu has to give him a list consisting of the names of all the customers on that day who bought Vada Pav(s) from the shop. The list should not have the names of any of the customers being repeated and it should be such that the lexicographically smallest name comes first, ie., the names should be sorted in dictionary order.
As and when a particular customer buys a Vada Pav, Chotu writes down the name of that particular customer. Chotu's initial list is ready, but, he is confused as to how to make the list Father expects from him. Chotu comes to you for help. Your job now is to create the final list, as Father expects from Chotu.
Input :
First line consists of N, the number of names of customers in Chotu's initial list. The next N lines are such that each line consists of a customer's name.
Output :
On the first line, print the total number of names appearing in Chotu's final list. Then print the list such that every customer's name is printed on a new line.
Example
Sample Input:
11
babu
anand
rani
aarti
nandu
rani
rani
ap
anand
babu
nandu

Sample Output:
6
aarti
anand
ap
babu
nandu
rani

For above problem I've submitted the following code:
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
  Scanner in = new Scanner(System.in);
    Set<String> set = new TreeSet<>();
    int n = in.nextInt();
    for(int i=0;i<n;i++){
        set.add(in.next());
    }
    System.out.println(set.size());
    Iterator i = set.iterator();
    while(i.hasNext()){
        System.out.println(i.next());
    }
}
}

But from 7 test cases, it passed 4 test cases but in rest of the test cases, the time limit exceeds. So my questions is how can I reduce time for this? I was thinking to use BufferedReader to read the whole input as a single String and than splitting it into a String array but the input is new-line separated not space separated. So I can't understand how to use fast I/O method here.


texts: Classifying files in a directory by file extension

texts:
I have the following code:

resolved = []
rejected = []
for file in files_within("./_input/"):
    file = File(file)
    if file.extension.lower() == "gdb":
        resolved.append(file)
    else:
        rejected.append(file)
MAP["resolved"] = resolved
MAP["rejected"] = rejected

And i would like to improve it to avoid this part:

MAP["resolved"] = resolved
MAP["rejected"] = rejected

But without affecting the performance.

I was thinking about that:

MAP["resolved"] = []
MAP["rejected"] = []
for file in files_within("./_input/"):
    file = File(file)
    if file.extension.lower() == "gdb":
        MAP["resolved"].append(file)
    else:
        MAP["rejected"].append(file)

But i don't know if is a good practice.

Python version 2.6.


texts: Returning rental invoice data transfer object

texts:
When trying to follow single responsibility principle, I often find myself in a position where there is so much to do that I do not know where to start. Maybe there is there a rule of thumb that I could use?

A concrete example originating from my test project.

    // doing way too many things
    public InvoiceDto GetInvoice(CartDto cart)
    {
        if (cart == null)
            throw new ArgumentNullException(nameof(cart));                                      // validation

        var cartequipments = _carts.GetById(cart.CartId).CartEquipments.ToList();               // quering
        var rentals = cartequipments.Select(o =>                                                // mapping
            new RentalDto                                                                       // object creation
            {
                Name = o.Equipment.EquipmentName,
                Price = _mapPriceCalculatorLogic                                                // buisiness logic
                    .Create(o.Equipment.EquipmentType)
                    .Calculate(o.RentDurationDays)
            }).ToList();
        var loyaltyPoints = _loyaltyPointsService                                               // buisiness logic
            .GetLoyaltyPoints(cartequipments.Select(o => o.Equipment.EquipmentType));
        var total = rentals.Sum(o => o.Price);                                                  // aggregation

        var invoiceDto = new InvoiceDto                                                         // object creation
        {
            Title = $"Invoice id : {cart.CartId}",
            Rentals = rentals,
            LoyaltyPoints = loyaltyPoints,
            TotalPrice = total
        };

        return invoiceDto;
    }

My question is how would you clean this up and if possible what would the result look like (helper methods sources not needed).


texts: Autoloading Class files and instantiating a class - Admin backend

texts:
At the moment I am auto loading my classes with:

spl_autoload_register(function ($class) {
    require_once 'classes/class.'. $class .'.php';
});

And instantiating the class with:

$backend = new backend();
$dashboard = new dashboard();
$article = new article();
$video = new video();
$theme = new theme();

These are in a config file required on every action page of my admin section.

backend is my main class holding database functions and other global functions.

The other classes all extends backend.

As I understand it, I could call backend functions through for example article, as it is an extension of the class.

Is this a good method for instantiating the classes, or is there a way I can call them automatically without having to write these in the config file at all?


texts: Finding the shortest path (between source and destination) with the least number of edges

texts:
I wrote a program which finds the shortest path between a source and a destination in a graph, so that the path will be to one with th least number of edges. In order to write it, I used Dijkstra's algorithm with several modifications.

Is there any way to improve or modify my code?

#include<stdio.h>
#include<string.h>
#define INFINITY 9999
#define n 5
#define s 0
#define d 4

void Dijkstra(int Graph[n][n], int _n,int _s, int _d);

int main()
{
    int Graph[n][n]={{0,6,5,1,INFINITY},{6,0,3,INFINITY,INFINITY},{5,3,0,2,5},{1,INFINITY,2,0,6},{INFINITY,INFINITY,5,6,0}};

    Dijkstra(Graph,n,s,d);
    getchar();
    return 0;

}

void Dijkstra(int Graph[n][n], int _n,int _s, int _d)
{

    int distance[n],pred[n] ,visited[n],edge[n]={0},count,mindistance,nextnode=_s,i,j;

    //pred[] stores the predecessor of each node
    //count gives the number of nodes seen so far
    //edge[] stores the number of edged of every vertex's shortest path
      from the source

    //initialize pred[],distance[] and visited[]
    for(i=0;i<n;i++)
    {
        distance[i]=Graph[_s][i];
        pred[i]=_s;
        visited[i]=0;
        if(distance[i]>0 && distance[i]<INFINITY)
            edge[i]++;        //the neighbours of the source
    }

    distance[_s]=0;
    visited[_s]=1;
    count=1;

    while(count<n-1 && nextnode!=_d )
    {
        mindistance=INFINITY;

        //nextnode gives the node at minimum distance
        for(i=0;i<n;i++)
            if(distance[i]<mindistance && !visited[i])
            {
                mindistance=distance[i];
                nextnode=i;

            }

            //check if a better path exists through nextnode
            visited[nextnode]=1;

            if (nextnode!=_d)
            for(i=0;i<n;i++)
                if(!visited[i])
                {
                    if(mindistance+Graph[nextnode][i]<distance[i] )
                    {
                        distance[i]=mindistance+Graph[nextnode][i];

                        pred[i]=nextnode;
                        edge[i]=edge[nextnode]+1;

                    }

                    if(mindistance+Graph[nextnode][i]==distance[i] )
                    {
                        if(edge[i] >= edge[nextnode]+1)

                        {pred[i]=nextnode;

                        edge[i]=edge[nextnode]+1;
                        }
                    }
                }

                count++;
    }

    //print the path

    i=nextnode;

printf("\n%d",_d);

j=_d;
do
{
  j=pred[j];
  printf("<-%d",j);
} while(j!=_s);

}


texts:
I'm teaching myself programming, using Python as my initial weapon of choice.

I have learnt a few basics and decided to set myself the challenge of asking the user for a list of names, adding the names to a list and then finally writing the names to a .csv file.

What would you do differently, i.e. how could this code be improved for readability and efficiency? Would you approach the situation differently, structure it differently, call different functions? I am interested in, and would appreciate a great deal, the feedback from more experienced programmers.

In particular, I find certain parts clunky; such as having to specify to the user the required format for data entry. If I were to simply request the data (name age location) without the commas however, then each record, when written to .csv, would simply end up as one record per cell (Excel) – this is not the desired result.

guestNames = ""
guestList = []
number = 0
guestNumber = ["second","third","fourth","fifth","sixth"]
finalList = ""

#Requesting user input.
guestNames = input("Please enter the names of your guests, one at a time.\n"\
    "Once you have finished entering the information, please type the word \"Done\".\n"\
    "Please enter your names in the following format (Name, Age, Location). ").capitalize()

guestList.append(guestNames)

while guestNames.lower() != "done".lower() :
    guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
    guestList.append(guestNames)
    number += 1

#Sorting the list.
guestList.sort()
guestList.remove("Done")

#Creating .csv file.
guestFile = open("guestList.csv","w")
guestFile.close()

#Writing to file.
for entries in guestList :
    guestFile = open("guestList.csv","a")
    guestFile.write(entries)
    guestFile.write("\n")
    guestFile.close()


texts: What is the best way to call two async functions, one after another in spring?

texts:
Very new to spring and spring boot here... What would be the best practice for calling two async functions one after another? If I have three functions like this :
@Async
public CompletableFuture<String> function1(String input){
     return CompletableFuture.completedFuture("result1");
}

@Async
public CompletableFuture<String> function2(String input){
     return CompletableFuture.completedFuture("result2");
}

 @Async
 public CompletableFuture<String> function3(String input){
      return CompletableFuture.completedFuture("result3");
 }

All of them do pretty heavy and slow tasks, so, I'd like them to be running on a separate thread. I also read that it's a bad practice in spring boot to run your own completable futures. ( read on this article https://stackoverflow.com/questions/533783/why-is-spawning-threads-in-java-ee-container-discouraged ). So, this is what I came up with:
CompletableFuture
  .supplyAsync(() -> function1(initInput))
  .thenSupplyAsync( output1 -> function2(output1.get()))
  .thenSupplyAsync( output2 -> function3(output2.get()))
  .exceptionally((output, ex ) -> handleException)

Is this a good coding practice? Or is there a better more recommended way to get it done?


texts: Queuing outgoing packets to fix server lag issues

texts:
I have been developing a game lately, my first multiplayer game. I am using Netty and LibGDX.

So previously, before this update I added, I was only queuing incoming packets, I had to do this because  I did not want to process packets on the netty thread, and instead process them on the game logic thread. So I had to add the incoming Packet to a queue, and then every game service tick execute them.

Now, I was not queuing outgoing packets server->client, it will just instant write and flush no matter where. On localhost, it worked very well, but once it was live with a few players, my game was having big delays, and mostly disconnects because of timeouts.

After adding an outgoing packet queuing, if absolutely fixed the lag, example:

Player#sendPacket(OutgoingPacket p):

/**
 * Sends a packet
 *
 * @param packet The packet to send
 */
public void sendPacket(OutgoingPacket packet) {
    packetQueue.add(packet);
}

This takes the outgoing packet that was constructed, and adds it to the outgoing packets queue, which is local in every Player object.

And then in my game service loop I have the following:

@Override
public void run() {
    try {
        context.getPackets().queuePackets(); // incoming packets
        context.getTimeMachine().tick();
        context.getPlayerManager().tick();
        context.getPlayerManager().queueOutgoingPackets(); // outgoing packets
    } catch (Exception e) {
        e.printStackTrace();
        ServerContext.log(e.getMessage());
    }
}

And the following method context.getPlayerManager().queueOutgoingPackets():

public void queueOutgoingPackets() {
    for (Player p : players) {
        p.queueOutgoingPackets();
    }
}

Which happens to do this for every player:

public void queueOutgoingPackets() {
    while(!packetQueue.isEmpty()) {
        packetQueue.poll().send(this);
    }
}

And simply send:

public void send(Player p) {
    encode();
    p.getChannel().writeAndFlush(this);
}

Now this fixed my lag issues, completely, I would really like to know, why and how did this affect my networking performance? Is that because write and flush slowing down Netty thread, so when I send packets casually in middle of the game logic?

Now someone told me that I have to limit the outgoing packets queue per tick, per player, in case of a packets spam that comes from a player, think that it makes sense to do so? Should it also be done for incoming packets?


texts: Function that enables fields based on checkbox state

texts:
I have simple code that just has to check if a checkbox is checked and if so enable some fields that, by default, should be disabled.

I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.

$(function(){
$('#amount').attr('disabled','disabled');
            $('#period').attr('disabled','disabled');
            $('#key').attr('disabled','disabled');
            $('#api').change(function(){
                if($('#apiEnabled').is(':checked')){
                    $('#amount').attr('disabled','');
                    $('#period').attr('disabled','');
                    $('#key').attr('disabled','');
                }else{
                    $('#amount').attr('disabled','disabled');
                    $('#period').attr('disabled','disabled');
                    $('#key').attr('disabled','disabled');
                }
            });
});


texts: Hide content unless an array contains at least one non-empty string

texts:
I have an array of hints. Sometimes, this array could contain an empty string. Occasionally, the array might contain only empty strings, in which case I want the whole block to be skipped. This is what I came up with:

<% @hints.each do |hint| %>
    <% unless hint.empty? %>

Please observe the following hints:

        <% @hints.each do |hint| %>
            <% unless hint.empty? %>

<%= hint %>

            <% end %>
        <% end %>

        <% break %>
    <% end %>
<% end %>

An example of @hints:

["", "", "Have you tried turning it off and on again?"]

Or:

[""]

Anyone know a better way?


texts: Given a string of brackets, return the count of brackets that are properly matched

texts:
A string of brackets is considered correctly matched if every opening bracket in the string can be paired up with a later closing bracket, and vice versa. For instance, “(())()” is correctly matched, whereas “)(“ and “((” aren’t. For instance, “((” could become correctly matched by adding two closing brackets at the end, so you’d return 2.

Given a string that consists of brackets, write a function bracketMatch that takes a bracket string as an input and returns the minimum number of brackets you’d need to add to the input in order to make it correctly matched.

My approach:

 import java.io.*;
 import java.util.*;

 class Solution {

  static int bracketMatch(String text) {
    // your code goes here
    //Maintain 2 variables
    int ob = 0;//ob
    int cb = 0;//cb
    int wb= 0;//wb

    for( int i = 0; i < text.length(); i++ )
      {
          //Check for openBracket
          if( text.charAt(i) == '(')
             ob++;

          //Check for closeBracket
          if( text.charAt(i) == ')')
             cb++;

          //Check if closeBracketct > openBracketct
          if( cb > ob )
          {
            wb++;
            ob = 0;
            cb = 0;
          }
      }
    return (wb + (ob - cb));
  }

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

}

I have a few questions regarding the above code:

1) How can I further optimize this code?

2) Am I using too many variables?

3) Is there a better approach than mine?

Reference


texts: Extract cell values from multiband rasters

texts:
I have the following function and code snippet to extract cell values for multiple years, format it, and save to a list. Each raster has 365 bands — one for each day. A separate operation is performed on each flattened list pr_flt which contains daily cell values of XY for 1991-2015. The cursor contains XY coordinates for each cell. The following code works but it takes hours to finish due to the huge amount of data and possible use of lists instead of multidimensional arrays. I am wondering if there are any suggestions to reduce the runtime of the code, if possible.

import arcpy

def row_to_values(row):
    values = []
    for col in row:
        if isinstance(col, unicode) and col != u'f':
            # split and convert all entries to float
            values += (float(v) for v in col.split(','))
        else:
            values.append(col)
    return values

with arcpy.da.SearchCursor(fc, fields) as cursor:
    for idx, row in enumerate(cursor):
        pt_annual_lists = []
        pt_loc = str(row[0]) +  str(" ") + str(row[1])
        for y in xrange(1991,2016,1):
            pt_year_list = []
            result = arcpy.GetCellValue_management(in_raster = "D:/temp/ras" + str(y) + ".tiff", location_point = pt_loc, band_index="")
            cell_value = result.getOutput(0)
            pt_year_list.append(cell_value)
            cell_value = [s.replace('\\n', ',') for s in pt_year_list]
            pt_annual_lists.append(row_to_values(cell_value))

        # flatten list of lists
        pr_str = [val for sublist in pt_annual_lists for val in sublist]
        pr_flt = [float(i) for i in pr_str]


texts: Find the minimum value in a circular list of integers

texts:
I was looking up some coding challenges and this looked like a fun one to solve. I tested it with the following values and it seems to work for those at least:

[ 5, 7, 8, 9, 11, 2, 3 ]
[ 5, 7, 1, 4]
[ 5, 7, 8, 1, 5]
[ 5, 1, 2, 3, 5]
[ 5, 5, 5]
[ 1 ]
[ 1, 2 ]
[ 2, 1 ]

My solution was to implement a binary search to try and find the smallest value, and if both ends of the sub-list have the same value then I will increment from the lowest value to try and work out if the lowest value lies in the first or second half of the sublist. I am not 100% confident that this part of the solution is bug free, so would appreciate any feedback on that.

I am mostly looking for feedback on my logic, as the coding standard doesn't matter to me too much in this case.

public static int findMinimum(List<Integer> input) {
  return findMinRecursive(input, 0, input.size() - 1);
}

public static int findMinRecursive(List<Integer> input, int lowestIndex, int highestIndex) {
  if (lowestIndex == highestIndex) {
    return input.get(lowestIndex);
  }
  boolean lastCheck = highestIndex - lowestIndex == 1;

  int offset = (highestIndex - lowestIndex) / 2;
  if (input.get(highestIndex) > input.get(lowestIndex)) {
    if (lastCheck) {
      return input.get(lowestIndex);
    }
    return findMinRecursive(input, lowestIndex, highestIndex / 2);
  } else if (input.get(highestIndex) < input.get(lowestIndex)) {
    if (lastCheck) {
      return input.get(highestIndex);
    }
    return findMinRecursive(input, lowestIndex + offset, highestIndex);
  } else {
    // If the numbers are equal we need to find out which direction has the minimum
    for (int i = lowestIndex; i < highestIndex; i++) {
      if (input.get(i) > input.get(lowestIndex)) {
        return findMinRecursive(input, lowestIndex + offset, highestIndex);
      } else if (input.get(i) < input.get(lowestIndex)) {
        return input.get(i);
      }
    }
    return input.get(lowestIndex);
  }
}


texts:
I wrote this sieve of Eratosthenes with MPI, but I'm not sure if it's good enough. Should I use MPI_Scatter and MPI_Gather instead of collecting arrays of separate processes in the root process?

Also, I'm not sure if I call

printArray(myArray, (N/size)-1);

right, where myArray is an array of pointers. GCC gives a warning at this point.

#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define N 60

int main(int argc, char *argv[])
{
long timeCPU;
int rank, size, k, i, v, n, scatterSize;
int **tmpArray, *myArray, firstElement, lastElement;

MPI_Init(&argc,&argv);

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if(N%size != 0)
{
    MPI_Finalize();
    printf("ERROR!");
    exit(0);
}

firstElement = (rank*N)/size;
lastElement = floor(((rank+1)*N)/size);
myArray = (int*) (malloc(((N/size)-1)*sizeof(int)));

for(i=0, v=firstElement+2; i<=(N/size)-1; i++, v++)
{
    myArray[i] = v;
}
    printArray(myArray, (N/size)-1);
/* All processes have to execute above code first */
MPI_Barrier(MPI_COMM_WORLD);

k = 2;

do
{
    markMultiples(k, myArray, lastElement-firstElement);
    k = nextNumber(k, myArray, lastElement-firstElement);
    MPI_Bcast(&k, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
while(k*k <=N);

MPI_Send(myArray, (N/size)-1, MPI_INT, 0, 50, MPI_COMM_WORLD);

MPI_Barrier(MPI_COMM_WORLD);

if (rank == 0)
{
    // Initialize 2D array
    tmpArray = (int**) (malloc(size*sizeof(int)));
    for(i=0;i<size;i++)
    {
        tmpArray[i] = (int*) (malloc(((N/size)-1)*sizeof(int)));
    }

    // Gather from every process his own array
    for (i=0; i<size;i++)
    {
        MPI_Recv(tmpArray[i], (N/size)-1, MPI_INT, i, 50, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printArray(tmpArray[i], (N/size)-1);
        printf("-----------------------------------------\n");
    }

    // Build 1d array with primes - TODO

}

//printArray(array, lastElement-firstElement);
free(myArray);
MPI_Finalize();
return 0;
}

int nextNumber(int k, int *array, int n)
{
int i;

for(i=0; i<=n; i++)
{
    if(array[i] > k)
        return array[i];
}
return -1;
}

void markMultiples(int k, int *array, int n)
{
int i;

for (i=0; i<=n; i++)
{
    if(array[i] % k == 0 && array[i] != k)
    {
        array[i] = -1;
    }
}
}

void printArray(int *array, int n)
{
int i;

for(i=0; i<=n; i++)
{
    printf("array[%d] = %d\n", i, array[i]);
}
}


texts: Initializing immutable objects with a nested builder

texts:
I need to initialize several parameters of an object but I also wanted to make it immutable. At the same time I don't want the constructor to take all several parameters because some of them are optional and have default values that the user can change during initialization like an IReadOnlyDictionary so I was experimenting with different patterns.

I found out that there is an interesting fact that if you make the builder nested inside the actual immutable class it then has still access to its private setters. This means you can build the actual object using the actual object without having to create copies in the builder itself and it still is immutable after exporting it, isnt't it?

This is how it looks like:

class Foo
{
    private IDictionary<string, string> _corge =
        new Dictionary<string, string>();

    public Foo() { }

    public string Bar { get; private set; }

    public IReadOnlyDictionary<string, string> Corge =>
        (IReadOnlyDictionary<string, string>)_corge;

    // API v3
    public static Foo Build(Action<Builder> build)
    {
        return Builder.Build(build);
    }

    public class Builder
    {
        private Foo _foo = new Foo();

        private Builder() { }

        // API v1
        public static Builder Create()
        {
            return new Builder();
        }

        // API v2
        public static Foo Build(Action<Builder> build)
        {
            var builder = new Builder();
            build(builder);
            return builder.ToFoo();
        }

        public Builder Bar(string bar)
        {
            _foo.Bar = bar;
            return this;
        }

        public Builder AddCorge(string key, string value)
        {
            _foo._corge.Add(key, value);
            return this;
        }

        public Foo ToFoo()
        {
            // prevents from reusing the builder after "ToFoo"
            var result = _foo;
            _foo = null;
            return result;
        }
    }
}

Usage with API v1:

var fooBuilder = Foo.Builder.Create();
fooBuilder.Bar("baz");
var foo = fooBuilder.ToFoo();
fooBuilder.Bar("QUUX"); // bam!

or with API v2:

var foo2 = Foo.Builder.Build(b => b.Bar("baz"));

or even shorther with API v3:

var foo2 = Foo.Build(b => b.Bar("baz"));


texts: Diff Two Arrays - return the symmetric difference of the two arrays

texts:
This is my challenge using JavaScript -> Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

My code works, but I think that it can be better.

function diffArray(arr1, arr2) {
 var newArr = [];

  arr1.map(function(val){
   arr2.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  arr2.map(function(val){
   arr1.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  return newArr;
}

diffArray([1, 2, 3, 5, 6, 7], [1, 2, 3, 4, 5]);

What do you think?


texts: Rock-Paper-Scissors with the revealing module pattern

texts:
In my ongoing effort in learning advanced JavaScript I tried to develop the traditional rock paper scissors game by using the famous revealing module pattern. I'm not comfortable yet with what has to be Private/Public. In my solution, I decided to have a single public function: Game. It uses a lot of private stuff and organizes the global game behavior. Everything else is private and not available to the caller. I'm not sure if it's a correct use of that pattern ?

Anyway I commented my code a lot I hope it will explain my intent correctly. I'm looking for any advices I can get, even if not directly related to the pattern I used.

var roshambo = (function() {

  // We will add +1 for each human victory
  var privateGameDB = 0;
  // We will add +1 for each human or robot victory
  var privateGameCount = 0;

  // Get human input with validation, returns a number between 1 and 3
  function privateGetInput() {
    var choice = prompt('Rock: 1, Paper: 2, Scissors: 3');

    // Input validation
    while (parseInt(choice) <= 0 || parseInt(choice) >= 4 || isNaN(parseInt(choice))) {
      choice = prompt('Rock: 1, Paper: 2, Scissors:3 (your choice vas not valid)');
    }

    return parseInt(choice);
  }

  // Generate robot's play, randomize a number between 1 and 3
  // Also includes a display box alerting the robot's play
  function privateGetRobotPlay() {
    var play = Math.floor(Math.random() * 3) + 1;

    switch (play) {
      case 1:
        alert('Robot played Rock');
        break;
      case 2:
        alert('Robot played Paper');
        break;
      case 3:
        alert('Robot played Scissors');
        break;
    }

    return play;
  }

  // Check who wins the round, by comparing the two numbers.
  // Returns 0 on draw, 1 on loss and 2 on win
  function privateComparePlays(human, robot) {
    var humanPlay = human;
    var robotPlay = robot;

    // Tie
    if (robotPlay == humanPlay) {
      return 0;
    }

    // Robot wins
    if (robotPlay == 1 && humanPlay == 3 || robotPlay == 2 && humanPlay == 1 || robotPlay == 3 && humanPlay == 2) {
      return 1;
    }

    // Defaults to player's victory
    return 2;
  }

  // Update game database and game counter, do nothing if the round is a tie
  function privateUpdateDB(check) {
    switch (check) {
      case 1:
        privateGameCount++;
        break;
      case 2:
        privateGameDB++;
        privateGameCount++;
        break;
    }
  }

  // Display a message depending on round result
  function privateAlertRoundResults(results) {
    switch (results) {
      case 0:
        alert('Draw !');
        break;
      case 1:
        alert('You lose !');
        break;
      case 2:
        alert('You win !');
        break;
    }
  }

  // Display a message with total winrate from 0 to 100% (rounded)
  function privateAlertTotalResults() {
    var results = Math.floor((privateGameDB / privateGameCount) * 100);
    alert('You won ' + results + '% of total games !');
  }

  // Check if the player wants to play again
  function privatePlayAgain() {
    var choice = confirm('Play again ?');
    return choice;
  }

  // Manage the whole game
  function publicGame() {
    // First we check who wins the round
    var humanPlay = privateGetInput();
    var robotPlay = privateGetRobotPlay();
    var roundResults = privateComparePlays(humanPlay, robotPlay);

    // Then display result to the user
    privateAlertRoundResults(roundResults);

    // If it's a tie, we do nothing.
    // If it's not : update database, display total winrate
    if (roundResults != 0) {
      privateUpdateDB(roundResults)
      privateAlertTotalResults();
    }

    // We end by asking the user if he wants to play again
    // If he does, we use a recursion to start the game again
    if (privatePlayAgain() == true) {
      publicGame();
    }
  }

  // The only function available to the user is the whole game
  return {
    play: publicGame
  };

})();

// Init a game
roshambo.play();


texts:
I decided to split the SQL Part away from This Question.
Before we get started I need to let you know a critical piece of information: Due to permissions within an offsite database I am NOT allowed to create tables even temporary ones within the database that I am getting the data from.

With that being said: All of the code below works as expected, but I would like a review of it because I know that there has to be a cleaner way of writing the SQL String.

SELECT CONCAT(cfcif#,cfalta) AS Customer_Number,
                 cffna AS First_Name,
                 cfmna AS Middle_Name,
                 COALESCE(NULLIF(cflna,''),cfna1) AS Last_Name,
                 COALESCE(NULLIF(RTRIM(LTRIM(cfpfa1))|| ' '|| RTRIM(LTRIM(cfpfa2)),''),RTRIM(LTRIM(cfna2),'')|| ' ' || RTRIM(LTRIM(cfna3),'')) AS Street_Address,
                 COALESCE(NULLIF(cfpfcy,''),cfcity) AS Street_City,
                 COALESCE(NULLIF(cfpfst,''),cfstat) AS Street_State,
                 COALESCE(NULLIF(LEFT(cfpfzc, 5), 0), LEFT(cfzip, 5)) AS Street_Zip,
                 CONCAT(RTRIM(LTRIM(cfna2)),RTRIM(LTRIM(cfna3))) AS Mailing_Address,
                 cfcity AS Mailing_City,
                 cfstat AS Mailing_State,
                 LEFT(cfzip, 5) AS Mailing_Zip,
                 NULLIF(cfhpho,0) AS Home_Phone,
                 NULLIF(cfbpho,0) AS Business_Phone,
                 NULLIF(cfssno,0) AS TIN,
                 (CASE
                    WHEN cfindi = 'Y' THEN '1'
                    WHEN cfindi = 'N' THEN '2'
                   END) AS Customer_Type,
                 (CASE
                    WHEN cfdob7 = 0 THEN NULL
                    WHEN cfdob7 = 1800001 THEN NULL
                    ELSE cfdob7
                  END) AS Date_of_Birth,
                 cfeml1 AS Email_Address
    FROM bhschlp8.jhadat842.cfmast cfmast
    WHERE cfdead = 'N'
    ORDER BY cfcif#


texts:
Please review my code for scanning active IP address . Please Suggest improvements ...

import socket
import threading
import sys

ip0=input('STARTING IP  : ')
ip1=input('ENDING IP    : ')
port=int(input('PORT NUMBER  : '))
timeout=int(input('TIMEOUT      :'))
timeout=timeout/1000
print()
ip0=list(map(int,ip0.split(".")))
ip01=list(map(int,ip1.split(".")))
class IpAddr:
    def __init__(self,d,c,b,a):
        self.a=a
        self.b=b
        self.c=c
        self.d=d
    def increase(self):
        self.a+=1
        if self.a>255:
            self.a=0
            self.b+=1
        if self.b>255:
            self.b=0
            self.c+=1
        if self.c>255:
            self.c=0
            self.d+=1
        return str(self.d)+"."+str(self.c)+"."+str(self.b)+"."+str(self.a)
    def data(self):
        return str(self.d)+"."+str(self.c)+"."+str(self.b)+"."+str(self.a)
    def next(self):
        self.b+=1
        if self.b>255:
            self.b=0
            self.c+=1
        if self.c>255:
            self.c=0
            self.d+=1
        return str(self.d)+"."+str(self.c)+"."+str(self.b)+"."+str(self.a)
    def diff(self,x,y,z,w):
        return (x-self.d)*256**2+(y-self.c)*256+z-self.b

def find(z,i):
    i=list(map(int,i.split(".")))
    ip=IpAddr(i[0],i[1],i[2],i[3])
    global cnt
    while i!=z:
        i=ip.data()
        s=socket.socket()
        s.settimeout(timeout)
        try:
            s.connect((i,port))
            print('[*] ACTIVE HOST',i)
            cnt+=1
        except:
            pass
        s.close()
        i=ip.increase()
ip=IpAddr(ip0[0],ip0[1],ip0[2],ip0[3])
n=ip.diff(ip01[0],ip01[1],ip01[2],ip01[3])-1
cnt=0
d={}
for i in range(n):
    p,q=ip.data(),ip.next()
    d[i]=threading.Thread(target=lambda:find(q,p))
    d[i].daemon=True
    d[i].start()
find(ip1,ip.data())


texts:
I'm learning Ruby and as an exercise I decided to build this little temperature converter app (C to F, F to C, F to K, etc). Looking back at it, it's pretty much just a bunch of boilerplate code. Any ideas on how I could shorten this up and make it a little more dynamic would really be appreciated!

#!/usr/bin/ruby
# My project: temperature converter (temp_conv.rb)
# start date: 10-26-2016
# finish date:
# A simple program to convert either from C to F, or F to C depending on the user's choice.

def c_to_f(c)
    ans = c*1.8+32
    puts "#{c}C = #{ans}F"
end

def f_to_c(f)
    ans = (f-32)/1.8
    puts "#{f}F = #{ans}C"
end

def f_to_k(f)
    ans = (f+459.65)*5/9
    puts "#{f}F = #{ans}K"
end

def k_to_f(k)
    ans = k * 9/5 - 459.67
    puts "#{k}K = #{ans}F"
end

def c_to_k(c)
    ans = c + 273.15
    puts "#{c}C = #{ans}K"
end

def k_to_c(k)
    ans = k - 273.15
    puts "#{k}K = #{ans}C"
end

again = nil
while again != "n"
    puts "welcome to Temp Converter 1.0!
          Please select an option from the following menu:
    1) Convert Celsius to Fahrenheit
    2) Convert Fahrenheit to Celsius
    3) Convert Fahrenheit to Kelvin
    4) Convert Kelvin to Fahrenheit
    5) Convert Celsius to Kelvin
    6) Convert Kelvin to Celsius
    0) Quit
    "
    m_choice = nil
    loop do
        print ":> "
        m_choice = gets.chomp.to_i
        break if m_choice >= 0 && m_choice <= 6
        puts "Invalid input. Please enter a choice between 0 and 6."
    end
    case m_choice
    when 1
        puts "Celsius to Fahrenheit"
        print "enter Temperature:> "
        cel = gets.chomp.to_i
        c_to_f(cel)
    when 2
        puts "Fahrenheit to Celsius"
        print "Enter Temperature:> "
        fah = gets.chomp.to_i
        f_to_c(fah)
    when 3
        puts "Fahrenheit to Kelvin"
        print "Enter Temperature:> "
        fah = gets.chomp.to_i
        f_to_k(fah)
    when 4
        puts "Kelvin to Fahrenheit"
        print "Enter Temperature:> "
        kel = gets.chomp.to_i
        k_to_f(kel)
    when 5
        puts "Celsius to Kelvin"
        print "Enter Temperature:> "
        cel = gets.chomp.to_i
        c_to_k(cel)
    when 6
        puts "Kelvin to Celsius"
        print "Enter Temperature:> "
        kel = gets.chomp.to_i
        k_to_c(kel)
    else
        puts "Thank you for using, Temperature Converter!"
        sleep(1)
        exit(0)
    end

    print "would you like to run again? (Y/N)"
    loop do
        print ":> "
        again = gets.chomp.downcase
        break if again == 'y' || again == 'n'
        puts "Invalid Input. Please choose either 'y' or 'n'"
    end
end


texts: (How) should I avoid writing procedural code in Haskell?

texts:
I'm trying to implement a left leaning red black tree as described here. This is their snippet for insert

private Node insert(Node h, Key key, Value value) {
    if (h == null) return new Node(key, value);

    if (isRed(h.left) && isRed(h.right)) colorFlip(h);

    int cmp = key.compareTo(h.key);
    if (cmp == 0) h.val = value;
    else if (cmp < 0) h.left = insert(h.left, key, value);
    else h.right = insert(h.right, key, value);

    if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
    if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);

    return h;
}

My attempt at a port in Haskell is... quite ugly, with a lot of repetition. I think it's because I'm still thinking procedurally. Any feedback on what I should do differently? Or is there no way around having many next-state variables (x', x'', x''')? Should I be approaching this completely differently?

data Colour = Red | Black deriving (Show)

data Tree a
    = Branch (Tree a) a (Tree a) Colour
    | Leaf
    deriving (Show)

add :: (Ord a) => Tree a -> a -> Tree a
add tree val
    = let
        (Branch left' node' right' _) = fix_up $ do_add tree val
    in (Branch left' node' right' Black) -- root always black

do_add :: (Ord a) => Tree a -> a -> Tree a
do_add (Branch left node right colour) val
    | val < node = (Branch (add left val) node right colour)
    | val > node = (Branch left node (add right val) colour)
    | otherwise = (Branch left node right colour)
do_add Leaf val = (Branch Leaf val Leaf Black)

get_left_node :: Tree a -> Tree a
get_left_node (Branch left _ _ _) = left
get_left_node Leaf = Leaf

fix_up :: Tree a -> Tree a
fix_up (Branch left node right colour)
    = let
        branch' = if ((not (is_red left)) && (is_red right)) then (rotate_left (Branch left node right colour)) else (Branch left node right colour)
        (Branch left' _ right' _) = branch'
        branch'' = if ((is_red left') && (is_red (get_left_node left'))) then (rotate_right branch') else branch'
        (Branch left'' _ right'' _) = branch''
        branch''' = if ((is_red left'') && (is_red right'')) then (flip_colours branch'') else branch''
    in branch'''

rotate_left :: Tree a -> Tree a
rotate_left (Branch left node (Branch right_left right_node right_right right_colour) colour)
    = let
        left' = (Branch left node right_left Red)
        centre' = (Branch left' right_node right_right colour)
    in centre'

rotate_right :: Tree a -> Tree a
rotate_right (Branch (Branch left_left left_node left_right left_colour) node right colour)
    = let
        right' = (Branch left_right node right Red)
        centre' = (Branch left_left left_node right' colour)
    in centre'

flip_colours :: Tree a -> Tree a
flip_colours (Branch (Branch left_left left_node left_right left_colour) node (Branch right_left right_node right_right right_colour) colour) = let
        left' = (Branch left_left left_node left_right (invert_colour left_colour))
        right' = (Branch right_left right_node right_right (invert_colour right_colour))
        centre' = (Branch left' node right' (invert_colour colour))
    in centre'

is_red :: Tree a -> Bool
is_red (Branch _ _ _ Red) = True
is_red _ = False

is_black :: Tree a -> Bool
is_black node = not $ is_red node


texts: Checking if the access token is valid or expired

texts:
Basically, the server gives me a token object. I am planning to check the token on the client if it is expired/valid before making a request to the server.
The function below works as expected. I just want to know if my code catch-all edge cases? I don't want, even 1 second that will request will fail due to an expired access token.
I am using moment for comparing dates. I also converted the current date and expiry date to UTC so that I'm making sure that they are in the same timezone before comparing them.
const moment = require('moment');

/**
The token object passed in the function looks like this:
{
  access_token: '2hbssMdXDpwQX5WcnZ-iJlO754MLkEeDCmF-f1A-MaU',
  token_type: 'Bearer',
  expires_in: 604800,
  refresh_token: 'VxnN9uBVIcNMpuwRVpvXo2YxWuNFEayHqfnCM7aCTSI',
  scope: 'public',
  created_at: 1603604241
}
*/

export default function tokenValid(token = {}) {
  const currentDate = moment().utc();
  const expiryDate = moment.unix(token.created_at).add(token.expires_in, 'seconds').utc();

  return currentDate < expiryDate;
}

EDIT (based on @hjpotter92's comment)
export default function tokenValid(token = {}) {
  const currentDate = moment().unix();
  const expiryDate = token.created_at + token.expires_in;

  return currentDate < expiryDate;
}


texts: Find All Numbers Disappeared in an Array

texts:
The task
is taken from leetcode

  Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
  some elements appear twice and others appear once.

  Find all the elements of [1, n] inclusive that do not appear in this
  array.

  Could you do it without extra space and in O(n) runtime? You may
  assume the returned list does not count as extra space.

  Example:

  Input:

  [4,3,2,7,8,2,3,1]

  Output:

  [5,6]

My solution

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
  return nums
    .reduce((arr, x) => {
      arr[x - 1] = null;
      return arr;
    }, Array.from({length: nums.length}, (v, k) => k+1))
    .filter(Boolean);
};

There has to be a more elegant solution to that.


texts:
Here is the description of the problem.

  Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations in order using command/arg pairs starting with the initial value of value. If you encounter an unknown command, return -1.

  Example:
  interpret(1, ["+"], [1]) → 2
  interpret(4, ["-"], [2]) → 2
  interpret(1, ["+", "*"], [1, 3]) → 6

I'm trying to implement this function using recursion. Here is my implementation.

public int interpret(int value, String[] commands, int[] args) {
  // base case
  if (commands.length == 0 && args.length == 0) {
    return value;
  }

  // Get top command and arg to calculate value
  final String cmd = commands[0];
  final int arg = args[0];

  // Construct remaining commands and args for recursion
  final int[] remainArgs
          = Arrays.copyOfRange(args, 1, args.length);
  final String[] remainCommands
          = Arrays.copyOfRange(commands, 1, commands.length);

  switch (cmd) {
    case "*":
      return interpret(value * arg, remainCommands, remainArgs);
    case "+":
      return interpret(value + arg, remainCommands, remainArgs);
    case "-":
      return interpret(value - arg, remainCommands, remainArgs);
    default:
      // unknown command return -1
      return -1;
  }
}

Please comment on my implementation in regarding to code readability and efficiency. Please also share your implementation if you have a better idea. Thanks.


texts:
I wrote this program for the Google Code Jam problem, "Recycled numbers."

It took around 2 and half minutes to solve the small input set on my dual core, 1GB RAM system. But for the large input set it took around 25 minutes(processor usage was 100% for those 25 mins) to solve the problem.

Problem

  Let's say a pair of distinct positive integers (\$n\$, \$m\$) is recycled if
  you can obtain m by moving some digits from the back of n to the front
  without changing their order.

  For example, (12345, 34512) is a recycled pair since you can obtain
  34512 by moving 345 from the end of 12345 to the front. Note that n
  and m must have the same number of digits in order to be a recycled
  pair. Neither n nor m can have leading zeros.

  Given integers \$A\$ and \$B\$ with the same number of digits and no leading
  zeros, how many distinct recycled pairs (\$n\$, \$m\$) are there with \$A ≤ n <
> m ≤ B\$?

How can I make my program fast enough to solve the large input set within 8 minutes?

f=open('C-large.in')
noi=int(f.readline().rstrip('\r\n'))
i=1
ou=open('jam.out','w')
while i<=noi:
  re=f.readline().rstrip('\r\n')
  rs=re.split()
  a=int(rs[0])
  b=int(rs[1])
  ans=0
  c=[x for x in range(a,b+1)]
  for ind,x in enumerate(c):
      for y in c[ind+1:]:
          n=str(x)
          m=str(y)
          if len(n)==len(m) and len(n)>1 and len(m)>1:
             ki=1
             while ki <len(n):
                 temp=n[-1:-(ki)-1:-1][::-1]+n[:-(ki)]
                 if temp[0]!='0':
                  if temp==m:
                     ans+=1
                     break
                 ki+=1
          else :
              break

  print("Case #%s:"%(i),ans,file=ou)
  i+=1
ou.close()
f.close()

Small input:

50
156 927
167 978
484 954
160 990
135 916
160 939
103 914
173 958
100 101
124 945
181 976
101 932
101 935
170 928
171 984
126 973
283 788
667 667
384 750
153 934
173 993
185 930
100 100
178 993
21 31
178 970
168 958
170 992
104 989
34 70
162 935
289 289
185 993
10 99
120 953
184 917
179 936
108 967
6 7
160 958
115 925
137 972
188 921
10 99
118 966
100 972
167 944
136 983
107 926
118 996

Large input:

50
10000 10001
1781 7688
1007465 1919027
100000 100000
1032122 1995680
1216257 1504628
1216908 1951709
1021619 1930030
15048 53617
1007458 1962726
388 869
1067361 1995135
46739 73395
1077614 1958584
1031957 1958036
72634 74120
1063961 1954135
274937 720742
1 8
1057393 1928164
28 93
1000000 2000000
1032073 1940559
1089798 1970754
100000 999999
1434814 1780702
1072799 1964898
1059864 1967119
155569 345355
2578 4229
72 95
552 553
601415 711929
1275115 1433162
688042 856983
594203 673506
1172008 1490273
180289 925799
354653 354653
1195595 1669305
5908 5967
2083 7987
339 670
1015539 1982001
29229 96206
1006167 1522491
1117646 1117646
1021936 1950412
41215 83080
1033077 1969448


texts: Locating matching files with input folder and file prefix

texts:
This is my first more-than-1-line script. It takes an input folder and a file prefix and gets all the matching files. For the first of the files, the script grabs the first line and appends an extra label string and puts that into $data. For all files (including the first), it takes the second line, adds the timestamp found from the filename, and appends a that as new line to $data. When it's done, it writes the output.

The problem is it's pretty slow. 1 directory might have 10,000 files. In that case, the script takes about 3-4 minutes to complete. When doing this over 10 such directories, it begins to get quite annoying.

So, I'm hoping someone here could help speed things up, preferably with explanations so I also get better.

for cs in {47..52}; do
  csdirnm="CASE$cs";
  tsdirnm="eta_at_x2";
  label='flow-time';
  dir="$csdirnm/$tsdirnm/";
  files=$(ls -tr $dir); # -tr sort on time created, reversed (newest last).
  i=0;
  for f in $files ; do
    fn=$dir$f;
    if [[ $i = 0 ]]; then
      data="$(sed -n 1p $fn) $label";
      ((i++));
    fi
    d=$(sed -n 2p $fn);
    t=$(echo $fn | perl -pe 's|.*?(\d+\.\d+)|\1|');
  data+="\n$d $t";
  done;
  echo -e "$data">"$csdirnm/${csdirnm}_${tsdirnm}_20T.time-series";
done;


texts:
I have a binary file input.hgt from the Shuttle Radar Topography Mission.  It contains a 3601✕3601 matrix, stored as 2-Byte big-endian integer numbers.  My code converts it to a readable text file output.csv.

How can I make it better?

Here is my code:

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

const int SRTM_SIZE = 3601;
static int height[SRTM_SIZE][SRTM_SIZE] = {{0},{0}};

int main() {

ifstream file("/storage/emulated/0/input.hgt", ios::in | ios::binary);

if(!file) {
cout << "Error opening file!" << endl;
return -1;
}

unsigned char buffer[2];

for (int i = 0; i < SRTM_SIZE; ++i) {

for (int j = 0; j < SRTM_SIZE; ++j) {

if(!file.read(reinterpret_cast<char*>(buffer), sizeof(buffer) )) {

    cout << "Error reading file!" << endl;

return -1; }

height[i][j] = (buffer[0] << 8) | buffer[1];

} }

ofstream meinFile;

meinFile.open ("/storage/emulated/0/output.csv");

    for(int x = 0; x < SRTM_SIZE; x++)
    { // from row 1 to row SRTM size

        for(int y = 0; y < SRTM_SIZE; y++)
        {// from column 1 to SRTM_Size

        meinFile << height[x][y] << ",";

        }

        meinFile << endl;
    }

            meinFile.close();
    cout<< "Gratulations!" <<endl;
    cout<< "Your file has been converted sucessfully" <<endl;
    return 0;
}


texts: Python 'check if number is divisible by 2' program

texts:
I have written a simple python program which takes a number from the user and checks whether that number is divisible by 2:

# Asks the user for a number that is divisible by 2
# Keep asking until the user provides a number that is divisible by 2.
print 'Question 4. \n'

num = float(raw_input('Enter a number that is divisible by 2: '))

while (num%2) != 0:
    num = float(raw_input('Please try again: '))
print 'Congratulations!'

I would appreciate any feedback on this code, areas for improvement and/or things that I could have done differently.


texts: Converting from std::wstring to std::string in Linux

texts:
I was bothered by inability of C++ to mix cout and wcout in the same program - so I've found this question:

Converting between std::wstring and std::string

It didn't help me because it was mostly about MS Windows (I'm on Linux), but thanks to it I've found something similar to the WideCharToMultiByte functions in the C++ standard library.

My goal was just to output wide strings to cout intermittently with regular strings. I've written two variants of conversion function, which take wide string as an argument and return a regular string, containing multi-byte characters, ready to be sent to the cout (provided that the locale is appropriate).

#include <iostream>
#include <string>

using std::cout;
using std::endl;

struct T
{
  std::string a;
  std::wstring b;
};

std::string Convert1(const std::wstring& WS)
// ------ conversion using the wcstombs function
{
  const unsigned wlen = WS.length();
  char buf[wlen * sizeof(std::wstring::value_type) + 1];
  const ssize_t res = std::wcstombs(buf, WS.c_str(), sizeof(buf));
  return (res >= 0) ? buf : "?";
}

std::string Convert2(const std::wstring& WS)
// ------ conversion using the wcsrtombs function
{
  mbstate_t st = {};
  const unsigned wlen = WS.length();
  wchar_t wbuf[wlen + 1];
  const size_t copied = WS.copy(wbuf, wlen);
  wbuf[copied] = L'\0';
  const wchar_t* wptr = wbuf;
  char buf[wlen * sizeof(std::wstring::value_type) + 1];
  const ssize_t res = std::wcsrtombs(buf, &wptr, sizeof(buf), &st);
  return (res >= 0) ? buf : "?";
}

int main()
{
  T t = {"Hello", L"Привет"};
  std::setlocale(LC_ALL, "en_US.utf8");
  cout << t.a << endl;
  cout << Convert2(t.b) << endl;
}

It works for me now... Will it work in other setups?


texts: Draw the tiles of the islands that are within bounds, using LibGDX

texts:
I am new person regarding LibGDX. I have written the below render method. I have a randomly generations oceans (where there are islands at random positions). Within the below code, focusedMapRectangle refers to the focused part of this map. The task is to draw the tiles of the islands that are within focusedMapRectangle.

I would like some feedback regarding:

conversion from my own algorithms/code to LibGDX features (i.e. how can I use existing LibGDX features as opposed to doing the the calculations myself directly).
code style / variable names (and whether others are preferred)
inefficient calculations that I can do in more efficient ways (speed)

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.5f, 0.5f, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClear(GL20.GL_ALPHA_BITS);
    getBatch().begin();

    Rectangle focusedMapRectangle = new Rectangle(
            getMatchMap().getBottomLeft().x,
            getMatchMap().getBottomLeft().y,
            Gdx.graphics.getWidth() / 16,
            Gdx.graphics.getHeight() / 16
    );

    getMatchMap().getIslands().forEach((island, point) -> {
        Rectangle islandRectangle = new Rectangle(
            point.x,
            point.y,
            island.getMaxWidth(),
            island.getMaxHeight()
        );

        // Signifies that the island is indeed present in the focused part of the map
        if (focusedMapRectangle.overlaps(islandRectangle)) {
            for (int islandTileX = 0; islandTileX < islandRectangle.getWidth(); islandTileX++) {
                for (int islandTileY = 0; islandTileY < islandRectangle.getHeight(); islandTileY++) {

                    // These refer to the absolute positions that each tile of the island has
                    // within the WHOLE map (not just focused)
                    int absoluteTileX = islandTileX + (int) point.x;
                    int absoluteTileY = islandTileY + (int) point.y;

                    // These refer to the position that each tile of the island has
                    // relative to the bottom left of the focused part of the map.
                    int relativeXToFocusPoint = absoluteTileX - (int) getMatchMap().getBottomLeft().x;
                    int relativeYToFocusPoint = absoluteTileY - (int) getMatchMap().getBottomLeft().y;

                    // Though we have verified that some part of the island is within the
                    // focused part of the map, it is is still possible that SOME of the island's tiles
                    // are NOT in focus.
                    boolean isXOutOfFocus = relativeXToFocusPoint < 0;
                    boolean isYOutOfFocus = relativeYToFocusPoint < 0;

                    // No need to render these said tiles of the island
                    if (isXOutOfFocus || isYOutOfFocus)
                        continue;

                    IslandTileType islandTileType = island.getRepr()[islandTileX][islandTileY];

                    // Do not go into statement if island tile type is water i.e null
                    if (islandTileType != null) {
                        Texture islandTexture = getIslandTextures().get(islandTileType);

                        int relativeCoordXToFocusPoint = relativeXToFocusPoint * 16;
                        int relativeCoordYToFocusPoint = relativeYToFocusPoint * 16;

                        getBatch().draw(islandTexture, relativeCoordXToFocusPoint, relativeCoordYToFocusPoint);
                    }
                }
            }
        }
    });

    getBatch().end();
}


texts: Constraint Algorithm Optimization in C++

texts:
I'm especially interested in ways to further optimize a constraint algorithm. So far I've switched to SIMD sse4 vector operations which nearly doubled the performance. I'm hoping there is more performance to squeeze out that I simply don't see.

Here is the algorithm:

FVector4 rest(REST_DISTANCE); // Set the constant simd vector outside the loop
FVector4 stiffness(STIFFNESS);

for (int i = 0; i < TEST_SIZE; i++)
{
    const auto& constraint = Constraints[i];
    auto& position1 = Particle[constraint.first].Position;
    auto& position2 = Particle[constraint.second].Position;

    for (int j = 0; j < ITERATION_COUNT; j++)
    {
        auto delta = position2 - position1;
        auto distance = delta.norm();

        auto correctionDistance = (distance - rest) / distance;
        auto pCorrection = correctionDistance * delta * stiffness;

        position1 += pCorrection;
        position2 -= pCorrection;
    }
}

Constraints is an array of a simple struct that holds two unsigned int's, Particle is an array of FParticle structs which holds three FVector4 fields and a Fvector4 simply wraps a __m128 and provides operators and functions like norm() which utilize _mm_* intrinsic functions.

Currently the algorithm takes 55 cycles per Constraint per Iteration, this is with TEST_SIZE of 150,000 and ITERATION_COUNT at 16. I know there is performance to gain from making it parallel but I'm hoping to get more performance out of the single threaded version specifically.

I can post the actual structs if needed.

FVector4 code:

struct FVector4
{
    FVector4()
    {}
    explicit FVector4(const __m128& InitData) : Data(InitData)
    {
    }
    explicit FVector4(__m128&& InitData) : Data(InitData)
    {
    }
    explicit FVector4(float InitValue)
    {
        Data = _mm_set_ps1(InitValue);
    }
    explicit FVector4(float X, float Y, float Z, float W = 0.f)
    {
        Data = _mm_setr_ps(X, Y, Z, W);
    }

    __forceinline float& operator[](int index)
    {
        return Data.m128_f32[index];
    }
    __forceinline const float& operator[](int index) const
    {
        return Data.m128_f32[index];
    }
    __forceinline __m128 squaredNorm() const
    {
        return _mm_dp_ps(Data, Data, 0x7F);
    }
    __forceinline __m128 norm() const
    {
        auto sqNorm = squaredNorm();
        return _mm_mul_ps(sqNorm, _mm_rsqrt_ps(sqNorm));
    }
    __forceinline __m128 normalized() const
    {
        auto dp = _mm_dp_ps(Data, Data, 0x7F);
        dp = _mm_rsqrt_ps(dp);
        return _mm_mul_ps(Data, dp);
    }
    __forceinline void normalize()
    {
        Data = normalized();
    }
    __m128 Data;
};

Operators as used in the algorithm:

__forceinline FVector4 operator-(const FVector4& a, const FVector4& b)
{
    return FVector4(_mm_sub_ps(a.Data, b.Data));
}
__forceinline FVector4 operator*(const FVector4& a, const FVector4& b)
{
    return FVector4(_mm_mul_ps(a.Data, b.Data));
}
__forceinline FVector4 operator/(const FVector4& a, const FVector4& b)
{
    return FVector4(_mm_mul_ps(a.Data, _mm_rcp_ps(b.Data)));
}
__forceinline FVector4& operator+=(FVector4& a, const FVector4& b)
{
    a.Data = _mm_add_ps(a.Data, b.Data);
    return a;
}
__forceinline FVector4& operator-=(FVector4& a, const FVector4& b)
{
    a.Data = _mm_sub_ps(a.Data, b.Data);
    return a;
}


texts:
In my last post, I wrote a long, non-general tail-merging† facility for insertion sort. I thought I should instead write a general-purpose tail-merging function, that works even when the two lists are of different lengths. So here it is (requires SRFI 1):

;;; Returns a list that has the same content as `lst`, sharing tail with `base`.
;;; Element comparisons use `eqv?`.
(define (merge-tail lst base)
  ;; `uniq1` and `uniq2` are guaranteed not to be `eqv?` to anything else.
  ;; This ensures that `breakpoint` always has a value, without any hacks.
  (define uniq1 (list 'uniq1))
  (define uniq2 (list 'uniq2))
  (define breakpoint (list-index (lambda (x y) (not (eqv? x y)))
                                 (reverse (cons uniq1 base))
                                 (reverse (cons uniq2 lst))))
  (append (drop-right lst breakpoint) (take-right base breakpoint)))

(In Racket, you can replace (list 'uniq1) with (box 'uniq1) (and similarly for uniq2), and (lambda (x y) (not (eqv? x y))) with (negate eqv?).)

Is there a more stylish or performant way to write this code? (Note, I'm trying to not mutate either list. If the lst list is linear-update, then of course you can use append! and drop-right!.)

† The process of merging tails is to ensure that two lists share the longest tail possible. This is especially useful for immutable lists.


texts: Creating consecutive words from a string

texts:
This is a method which creates an array of all possible consecutive substrings from a string:

def get_seperated_tokens(query)
  result = []
  length = query.split.count
  tokens = query.downcase.strip.split(' ')
  length.times do |i|
    length.times do |j|
      result << tokens[i..j].join(' ') if j >= i
    end
  end
  result
end

To get a better idea I have added rspec for it:

describe "#get_seperated_tokens" do
  it "returns an array of seperated tokens" do
    query = 'ruby is awesome'
    result = ['ruby','is', 'awesome', 'ruby is', 'is awesome','ruby is awesome']
    expect(get_seperated_tokens(query)).to include(*result)
  end
  it "returns an array of seperated tokens" do
    query = 'red blue iphones'
    result = ['red','blue', 'iphones', 'red blue', 'blue iphones','red blue iphones']
    expect(get_seperated_tokens(query)).to include(*result)
  end
end

How can this be made more idiomatic?


texts: SEDE query to find users with exactly one post in a particular tag

texts:
I'm doing some research for a meta post on Gardening.SE (where I'm a pro tempore moderator). I'm using the Stack Exchange Data Explorer (SEDE) to find information about first time users who post questions in our [identification] tag, and how they subsequently interact with the people who respond to their question, whether that's comments on the post, comments on answers, editing the post to provide more information, and so on.

I have the following query which gives me the list of people with no answers and one question that includes the [identification] tag. I plan to refine it by adding extra criteria, e.g. to find instances where the OP leaves a comment replying to someone else.

-- Find users who have exactly one post
-- with that post being a question
-- and the question has the [identification] tag
SELECT
  Users.Id AS [User Link], Posts.Id AS [Post Link]
FROM
  Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
        INNER JOIN PostTags ON Posts.Id = PostTags.PostId
        INNER JOIN Tags ON Tags.Id = PostTags.TagId
WHERE
  Tags.TagName LIKE 'identification' AND
  Posts.ParentId IS NULL AND   -- ParentId is NULL if post is a question
  Users.Id in (
    -- Users with exactly one question
    SELECT Users.Id
    FROM
      Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
    WHERE
      Posts.ParentId IS NULL
    GROUP BY
      Users.id
    HAVING
      Count(Posts.Id) = 1
    ) AND
  Users.Id NOT IN (
      -- Users with 1 or more answers
    SELECT Users.Id
    FROM
      Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
    WHERE
      Posts.ParentId IS NOT NULL
    GROUP BY
      Users.id
    HAVING
      Count(Posts.Id) > 0
    )
ORDER BY
  Users.Id DESC  -- newest users first.

My concern is that this SQL is far from optimal. I'm looking especially at the repeated inner joins between the Users and Posts tables, and the similarity between the sub-queries to find users with one question and users with at least one answer.

Gardening.SE is a small site, so this query consistently takes less than 75ms to return its 101 records, but even so I'd like to make it run more efficiently, if possible. As I said, I plan to enhance this query, which will mean pulling in more tables, so I'm also concerned about it scaling that way.

Data Explorer links:

Users with one [identification] question and no answers — the above query.
Drive-by users with one [identification] question — a derived query for users who post and are never seen again.


texts: Find the first repeating sequence in digits of pi

texts:
I wrote a function to return the first n length sequence which occurs twice in the digits of pi. Along with the repeated sequence, I want the indices of the first and second occurrences. For example, if n is 1, code returns (1, 0, 2) and if n is 2, (26, 5, 20).
For reference, here are the first digits of pi:
3.141592653589793238462643383279502884197169399375105820974944592...

The code uses a breadth-first search (as opposed to a depth-first search, which I coded up to be faster, but isn't what I'm looking for). I realize code below is convoluted and inefficient because it checks same digits multiple times.
How do I make it simpler and faster?
code
from mpmath import mp

mp.dps = 1000
pi = mp.pi

def repeats(n):
    pi_list = [int(x) for x in str(pi)[2:]]
    breadth = range(n + n, len(pi_list))

    for breadth_level in breadth:

        pattern_starts = range(breadth_level - 2 * n + 1)
        for p_s in pattern_starts:

            test_starts = range(n, breadth_level - n + 1)
            for t_s in test_starts:
                candidate = pi_list[p_s:p_s + n]
                test_start = max(p_s + n, t_s)
                test = pi_list[test_start:test_start + n]
                if candidate == test:
                    return candidate, p_s, t_s

print(repeats(1))
print(repeats(2))
print(repeats(3))

output
([1], 0, 2)
([2, 6], 5, 20)
([5, 9, 2], 3, 60)


texts: java if `String` begins with "red" or "blue"

texts:
Given a String, if the String begins with "red" or "blue" return that color String, otherwise return the empty String

public String seeColor(String str) {
  if(str.length() <= 3){
    if(str.equals("red")){
      return "red";
    }
    return "";
  }
  else if(str.substring(0, 3).equals("red")){
    return "red";
  }
  else if(str.substring(0, 4).equals("blue")){
    return "blue";
  }
  return "";
}

I really don't like the fact that I'm using same code for "red" twice but I can't get to think out another way. If str is equal to 3, I have to make the check for "red", right?
Example input: "redxx" - output "red",
"xxred" - output "",
"blueAvenue" - output "blue"


texts:
I'm working on my way to write most efficient, reusable and robust code, and this is why I'd like to receive some support. I've written a datetimepicker script that allows datetime chosing, and a shortcut button that will subtract from higher date (the right input) a variable number of minutes:

Is there a way to simplify my code even more?

<form>
  <input type="text" name="poczatek" id="od" />
  <input type="text" name="koniec" id="do" />
  <input type="button" value="10" class="odejmijCzas"/>
  <input type="button" value="20" class="odejmijCzas"/>
  <input type="button" value="30" class="odejmijCzas"/>
</form>

JavaScript

dateTimeFormat = new Object();
dateTimeFormat.dwucyfrowa = function(m) {
    return m < 10 ? '0' + m : m;
}
dateTimeFormat.format = function(date) {
    return date.getFullYear() + '-' + dateTimeFormat.dwucyfrowa(date.getMonth() + 1) + '-' + dateTimeFormat.dwucyfrowa(date.getDate()) + ' ' + dateTimeFormat.dwucyfrowa(date.getHours()) + ':' + dateTimeFormat.dwucyfrowa(date.getMinutes());
}
$(document).ready(function() {
    inputOd = $("#od");
    inputDo = $("#do");

    inputOd.add(inputDo).datetimepicker({
        changeMonth: 'true'
    });

    currentTime = new Date();
    inputOd.add(inputDo).val(dateTimeFormat.format(currentTime));

    $('.odejmijCzas').click(function() {
        odejmijCzas($(this).attr('value'));
    });
});

function odejmijCzas(liczbaMinut) {
    czasDo = new Date(inputDo.val());
    roznicaCzasu = czasDo.getTime() - liczbaMinut * 1000 * 60;
    czasOd = new Date();
    czasOd.setTime(roznicaCzasu);
    inputOd.val(dateTimeFormat.format(czasOd));
}


texts:
I've created a caching service using OOP techniques combined with the revealing module pattern and the angular-cache library. New CacheDataClass objects are instantiated using the Factory pattern with RequestFactory. It has generic methods for get, set and reset data. It can be extended to override those methods. I would be very grateful if this can be reviewed and for any suggestions for improvement.

The factory itself:

(function() {
    'use strict';

    angular
    .module('dataservices')
    .factory('CacheDataClass', CacheDataClass);

    CacheDataClass.$inject = ['CacheFactory'];

    function CacheDataClass(CacheFactory) {

        var CacheData = function(uid) {
            this.uid = uid;
            this.newData = null;
            this.cache = this.initCache();
        };

        CacheData.prototype = {
            constructor: CacheData,
            initCache: function() {
                var self = this;

                if (!CacheFactory.get(self.uid + '/cache')) {
                    CacheFactory.createCache(self.uid + '/cache', {
                        maxAge: 24 * 60 * 60 * 1000,
                        deleteOnExpire: 'aggressive'
                    });
                }
                var cache = CacheFactory.get(self.uid + '/cache');

                self.cache = cache;
                return cache;
            },
            getData: function() {
                var self = this;

                self.newData = self.cache.get(self.uid) ?
                    self.cache.get(self.uid) :
                    {};

                return self.newData;
            },
            setData: function(data) {
                var self = this;
                var cache = self.initCache();

                cache.put(self.uid, data);
                self.cache = cache;
            },
            resetData: function() {
                var self = this;

                self.cache.remove(self.uid);
                self.newData = {};
                return self.newData;
            }
        };

        return CacheData;

    }
})();

Request factory:

(function() {
    'use strict';

    angular
    .module('dataservices')
    .factory('RequestFactory', RequestFactory);

    RequestFactory.$inject = ['CacheDataClass'];

    function RequestFactory(CacheDataClass) {
        return {
            createCache: function(uid) {
                return new CacheDataClass(uid);
            }
        };
    }
})();

Example implementation:

(function() {
    'use strict';

    angular
    .module('cacheExample')
    .controller('CacheExampleController', CacheExampleController);

    CacheExampleController.$inject = ['CacheFactory', 'RequestFactory', '$stateParams'];

    function CacheExampleController(CacheFactory, RequestFactory, $stateParams) {
        var vm = this;

        activate();

        function activate() {
            vm.paramsCache = RequestFactory.createCache($location.path() + userID);
        }

        function setCache() {
            vm.paramsCache.setData({
                userID: $stateParams.userID,
                email: $stateParams.email,
            });
        }
    }
})();


texts: Some questions about a simple asynchronous socket client

texts:
I am having a hard time to come up with a simple TCP client, that should use one socket and two threads (one for sending and one for receiving).

As using TPL tasks is the way asynchrony should be handled in C#, I am trying to use the *Async methods provided by the SocketTaskExtensions class.

This is what my class looks so far:

public class TcpConnector
{
    private readonly Socket socket;

    public bool IsConnected => this.socket.Connected;

    public TcpConnector()
    {
        this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }

    public async Task ConnectAsync(IPEndPoint endpoint)
    {
        await this.socket.ConnectAsync(endpoint);
    }

    public async Task<int> SendAsync(string message)
    {
        if (!this.IsConnected)
        {
            throw new SocketException((int) SocketError.NotConnected);
        }

        ArraySegment<byte> buffer = Encoding.UTF8.GetBytes(message);

        return await this.socket.SendAsync(buffer, SocketFlags.None);
    }

    public async Task ReceiveAsync()
    {
        if (!this.IsConnected)
        {
            throw new SocketException((int) SocketError.NotConnected);
        }

        var segment = new ArraySegment<byte>(new byte[4]);

        while (true)
        {
            var receiveTask = this.socket.ReceiveAsync(segment, SocketFlags.None);
            receiveTask.Wait();

            var message = Encoding.UTF8.GetString(segment.Array, 0, receiveTask.Result);
        }
    }
}

And this is one of my unit tests:

[Fact]
[Trait("Category", "UnitTest")]
public async Task Should_Successfully_ReceiveAsync()
{
    // Arrange
    var client = new TcpConnector();
    var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

    // Act
    await client.ConnectAsync(endpoint);

    var receiveTask = client.ReceiveAsync();
    await receiveTask;

    // Assert
    ...
}

Notes

I intentionally choose the buffer to be that small to test/learn about the behaviour if received data doesn't fit into the buffer.
The code works so far, in that it keeps receiving and that sending is possible from another thread.
When starting to receive, the client doesn't notice when the server shuts down, while waiting for data.

Questions

From what I understand is that a TCP socket provides a way of a bidirectional and asynchronous communication. Which means a client should be able to send and receive at the same time. Is that assumption correct?
How can I properly use ArraySegment here? Should the data to be send and received be hold in one (private) ArraySegment<byte> buffer? What are the benefits of using this struct over a plain byte buffer?
Using a while(true) loop somehow feels wrong, although ReceiveAsync seems to block the thread and therefor no CPU cycles are getting wasted. What would be a more TPL-like approach to this?
Microsoft's documentation is mentioning socket.Available, which (according to the doc) should be used especially in conjunction with the ReceiveAsync method. But replacing the while(true) with while(socket.Available != 0) will prematuraly end my receiving thread, when no data is available. So how would one use that properly?
How should I handle socket errors? E.g. when the server side closes the connection or something else occurs while receiving?
How should I properly handle/implement timeouts?


texts:
I am new to C and I am trying to implement a mutex.

The idea of the program is:

main() will create three threads.
Each thread will read one character each from individual files in serial, i.e. thread 1 will read one character store in global and then wait for thread 2 & 3 to complete the same tasks, until the end of the file.
main() will then write all the data from single character global to output file.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

pthread_t tid[3];
pthread_mutex_t lock;

char characters[1024] = "";

readFromFile(int fileNumber)
{
    pthread_mutex_lock(&lock);

    char* firstPart = "file";
    char *secondPart = ".in";

    char fileN[1];

    sprintf(fileN, "%d", fileNumber);

    char * fileName = malloc(1 + strlen(firstPart) + strlen(fileN) + strlen(secondPart));
    strcpy(fileName, firstPart);
    strcat(fileName, fileN);
    strcat(fileName, secondPart);

    FILE *fp;
    int c;

    if (!(fp = fopen(fileName, "rt")))
    {
         printf("\nError Opening File\n");
         exit(1);
    }
    while ((c = fgetc(fp)) != EOF)
    {
         strcat(characters, c);
    }
   fclose(fp);

   pthread_mutex_unlock(&lock);
}

int main(int argc, char** argv) {
    int i = 0;
    int err;

    if (pthread_mutex_init(&lock, NULL) != 0) {
        printf("\n Mutex Init Failed\n");
        return 1;
    }

    while (i < 3) {
        err = pthread_create(&(tid[i]), NULL, readFromFile(i), NULL);
        if (err != 0) {
            printf("\nCan't Create thread :[%s]", strerror(err));
        }
        i++;
    }

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_join(tid[2], NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}


texts:
Here is the chunk of the code that hogs the maximum time:

   double m_compute__(int xi, set_type pa_set) {
        // no negative or floating numbers to be handled
        if (pa_set == 0) { return m_compute__(xi); }

        // Bitwise representation of a set of numbers
        std::vector<int> pa_vec = as_vector(pa_set);
        //  Number of elements in the set
        int pa_sz = pa_vec.size();

        // Creating a place for storing the key & values
        // max_index_[pa_sz] some pre-computed and non-changing value
        std::vector<std::vector<int>> vec(max_index_[pa_sz] + 1, std::vector<int>(r_[xi]+1, 0));

        int start = m_;
        int last = 0;

        for (int i = 0; i < m_; ++i) {
            int index = 0;
            index = D_[i * n_ + pa_vec[0]];
            for (int j = 1; j < pa_sz; ++j) { index += r_[pa_vec[j]] * D_[i * n_ + pa_vec[j]]; }
            ++vec[index][0];
            ++vec[index][D_[i * n_ + xi] + 1];
            start = start < index ? start : index;
            last = last > index ? last : index;
         }

        int qi = 0;
        double score = 0.0;
        for (; start <= last; ++start) {
            double nij = vec[start][0];
            if (nij > 1) {
                double nijk = -1;
                for (int i = 1; i <= r_[xi]; ++i) {
                    nijk = vec[start][i];
                    score += (nijk == 0) ? 0 : nijk * (std::log2(nij) - std::log2(nijk));
                }
            }
            if (nij >= 1) { ++qi; }
        }
        score += cons_ * qi * (r_[xi] - 1);
        return score;
    }// m_compute__

    int n_ = -1;
    int m_ = -1;
    set_type X_ = 1;

    double cons_ = -1;
    // vector for storing n_ positive (> 1) numbers and with each number < 127
    std::vector<int> r_;
    std::vector<data_type> D_;
    int max_index_[SET_MAX_SIZE];

D_ is a container used to store table of elements of type signed char (n_ * m_) where m_ represents the number of rows and n_ the number of columns.

Here is the output obtained from using gprof. I am trying to figure out what all changes I can make to improve the performance. Or I am finding it hard to interpret the output of gprof to know where I am losing maximum time and how to improve it.

Compiled using: g++ -std=c++11 -pg test.cpp
Profiler output: gprof ./a.out

Compiled using the optimization flags:
g++ -std=c++11 -O3 -pg test.cpp
Profiler output:
 gprof ./a.out
But when this "-O3" is used the output of profile does not seems to contain any information.


texts: Simple Registration Form. I would like to get rid of code duplications

texts:
I don't like my current code, because of duplications. What's the best way to leverage Kotlin to make it more concise. I have simple registration form

data class RegisterForm @JvmOverloads constructor(
        val email: String = "",
        val emailError: String = "",

        val lastName: String = "",
        val lastNameError: String = "",

        ...
)

In my ViewModel I'm reacting to my TextWatcher. I set my state by updating my RegisterForm data class

fun onEmailChanged(email: String) {
    setState {
        copy(registerForm = registerForm
                .copy(email = email, emailError = validateEmail(email))
        ) }
}

fun onFirstNameChanged(text: String) {
    setState {
        copy(registerForm = registerForm
                .copy(firstName = text, firstNameError = validateFirstName(text))
        ) }
}

As you can see, I need to copy paste the code in my ViewModel every time I'm adding the new input field. How can I leverage Kotlin to get rid of these duplications?


texts:
I have an PHP endpoint used to mail me feedback or error logs from my sites here: https://github.com/kaihendry/vanilla-php-feedback-form/blob/master/feedback/feedback.php

<?php
switch ($_SERVER['HTTP_ORIGIN']) {
    case "https://example.com":
        header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
        break;
    default:
        die("Bad origin: " . $_SERVER['HTTP_ORIGIN']);
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit;
}
$subject = 'Feedback from ' . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['HTTP_REFERER'];
$input = json_decode(file_get_contents('php://input'), true);
if(empty($input["msg"])) { http_response_code(400); die(); }
$message = json_encode($input, JSON_PRETTY_PRINT) . "\n\n--\n" . json_encode($_SERVER, JSON_PRETTY_PRINT);
if(empty($input["from"]) || !filter_var($input["from"], FILTER_VALIDATE_EMAIL)) {
    mail('me@example.com', $subject, $message);
} else {
    $headers = 'From: ' . $input["from"];
    mail('me@example.com', $subject, $message, $headers);
}
?>

There are a couple of problems:

It's slow. I suspect it's mail(), which is used with ssmtp & AWS SES. It's fast when I comment the mail line out. Can it be backgrounded somehow?
Should I be returning JSON like status OK or not OK if mail() fails? What is best practice?
Is there an easy way of compiling them into a digest or maybe better alternatives to email I may have missed? I'm a bit worried someone can abuse this script using cURL. How can I prevent that sanely?


texts:
Although there are several implementations of binary search tree, I have made my own implementation for practice. The following code does the followoing operation
- Create a binary tree
- search through a binary tree
- inorder traversal
- preorder traversal
- breadth first traversal
- depth first traversal(post order)

Please suggest improvements or possible short comming in the code

import static org.junit.Assert.assertEquals;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import org.junit.Test;

public class BST {
public TreeNode root = null;

public TreeNode get(int element){
    if(root == null){
        return null;
    }
    TreeNode runner = root;
    while (true){
        if(runner.data > element){
            if(runner.leftNode == null){
                return null;
            }
            runner = runner.leftNode;
        } else if(runner.data < element) {
            if(runner.rightNode == null){
                return  null;
            }
            runner = runner.rightNode;
        } else {
            return runner;
        }
    }
}

public void insert(int element){
    if(root == null){
        root = new TreeNode(element);
        return;
    }
    TreeNode runner = root;
    while (runner.data != element){
        if(runner.data > element){
            if(runner.leftNode == null){
                runner.leftNode = new TreeNode(element);
                return;
            }
            runner = runner.leftNode;
        } else {
            if(runner.rightNode == null){
                runner.rightNode = new TreeNode(element);
                return;
            }
            runner = runner.rightNode;
        }
    }
}

public static void breathFirstSearch(TreeNode root){
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    TreeNode runner = root;
    while(!queue.isEmpty()){
    runner = (TreeNode)queue.remove();
    if(runner.leftNode != null){
        queue.add(runner.leftNode);
    }
    if(runner.rightNode != null){
        queue.add(runner.rightNode);
    }
    System.out.println("visited node " + runner.data);
    }
}

public static void depthFirstSearch(TreeNode root){
    Stack<TreeNode> stack = new Stack<TreeNode>();
    if(root == null){
        return;
    }
    TreeNode runner = null;
    stack.add(root);
    while(!stack.empty()){
        runner = stack.peek();
        if(runner.leftNode != null && !runner.leftNode.visited){
            stack.add(runner.leftNode);
            continue;
        }
        if(runner.rightNode != null && !runner.rightNode.visited){
            stack.add(runner.rightNode);
            continue;
        }
        stack.pop();
        runner.visited = true;
        System.out.println("visited node " + runner.data);
    }
}

public static void preOrderTraversal(TreeNode root){
    if(root == null){
        return;
    }
    System.out.print(root.data + " ");
    preOrderTraversal(root.leftNode);
    preOrderTraversal(root.rightNode);
}

public static void inOrderTraversal(TreeNode root){
    if(root == null){
        return ;
    }
    inOrderTraversal(root.leftNode);
    System.out.print(root.data + " ");
    inOrderTraversal(root.rightNode);
}

private class TreeNode {
    public int data;
    public TreeNode leftNode;
    public TreeNode rightNode;
    public boolean visited;
    TreeNode(int data){
        this.data = data;
    }
}

@Test
public void basicTest(){
BST tree = new BST();
int[] data = {9, 5, 3, 1, 4, 8, 15, 11, 21, 20, 29};
for (int i : data){
    tree.insert(i);
}
assertEquals(tree.get(3).data, 3);
}

}


texts: Review of my CSS for aligning the navigation icons and text in a footer menu

texts:
The navigation in my footer menu looks like this

It works, but I get a feeling that using spans the way I did was a bit of a hack. So I would also like to know how to maximize compatibility as used media queries.

I created it using the following

HTML

        HOME&raquo;

        FEATURES&raquo;

        VIDEOS&raquo;

        CASES&raquo;

        TESTIMONIALS&raquo;

        BLOG&raquo;

        AUTHORIZED BRUXZIR LABS&raquo;

CSS

.footer {
  background-color: #111;
  text-align: center;
  width: 100%;
  min-height: 120px;
  padding: 24px 0;
}

.footer a {
  color: #fff;
  text-decoration: none;
}

.footer ul { list-style: none; }

@media only screen and (min-width: 1px) and (max-width: 479px) {
  .footer { text-align: left; }
  .footer ul li {
    display: block;
    padding: 12px;
  }
  .footer ul li a { }
  .footer ul li a span:nth-of-type(2) {
    padding:9px;
    background-color: rgb(202, 0,0 );
    float: right;
    border-radius:2px;
  }
}

@media only screen and (min-width: 480px) {
  .footer { text-align: center; }
  .footer ul li { display: inline; }
  .footer ul li:not(:last-of-type) { margin-right: 12px }
  .footer ul li a span:nth-of-type(2) { display: none; }
}


texts: Exercise: Reading doubles from a file and printing mean, max and min (from Programming Principles and Practice using C++)

texts:
Read a sequence of double values into  a vector. Think of each value as the distance between two cities along a given route.  Compute and print the total distance (the sum of all distances). Find and print the smallest and greatest distance  between two neighboring cities. Find and print the mean distance between two  neighboring cities.

from Programming Principles and Practice using C++ by Bjarne Stroustrup

Since always entering values seems stupid, I decided to read the values from a file named "distances.txt".

print_distances_mean_max_min is what concerns me, how could I split the computing of min,max,mean and printing it while not spreading the code too thinly? Or is it fine as it is?

main.cpp

#include <iostream>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <algorithm>

using std::vector;
using std::string;
using std::fstream;
using std::ios_base;
using std::runtime_error;
using std::cout;
using std::max_element;
using std::min_element;

const string distances_file_name = "distances.txt";

vector<double> load_file_of_doubles_to_vector ( string file_name )
{
    vector<double> distances;
    fstream my_file ( file_name, ios_base::in );
    double temporary_number;
    while ( my_file >> temporary_number )
    {
        distances.push_back ( temporary_number );
    }
    if ( !my_file.is_open() )
    {
        throw runtime_error ( string ( "Failed to load " ) + file_name );
    }
    return distances;
}

void print_distances_mean_max_min ( const vector<double>& distances_vector )
{
    if ( distances_vector.empty() )
    {
        throw runtime_error ( string ( "There are no entries in " ) + distances_file_name );
    }
    double total_distance = 0;
    for ( auto& n : distances_vector )
    {
        total_distance += n;
    }
    cout << "The sum of all distances is: " << total_distance << "\n";
    double max_distance = 0;
    max_distance = *max_element ( distances_vector.begin(), distances_vector.end() );
    cout << "The maximum distance is: " << max_distance << "\n";
    double min_distance = 0;
    min_distance = *min_element ( distances_vector.begin(), distances_vector.end() );
    cout << "The minimum distance is: " << min_distance << "\n";
    double mean_distance = 0;
    mean_distance = total_distance / distances_vector.size();
    cout << "The average(mean) distance is: " << mean_distance << "\n";
}

int main()
{
    print_distances_mean_max_min ( load_file_of_doubles_to_vector ( distances_file_name ) );
    return 0;
}

distances.txt

8.7
6.3
9.0
3.142
2.7


texts: Implementing `dropJ` to Drop `JoinList` Elements

texts:
In the same vein as the (+++) function on JoinList and indexJ on JoinList, I implemented dropJ to drop elements from a JoinList.

Here's my attempt:

dropJ ::(Sized b, Monoid b) => Int -> JoinList b a -> JoinList b a
dropJ _ Empty = Empty
dropJ i jl | i <= 0           = jl
dropJ _ (Single _ _)          = Empty
dropJ i (Append _ left right)
  | i >= leftHt               = dropJ (i-leftHt) right
  | otherwise                 = dropJ i left
    where leftHt = (getSize. size . tag) left

Testing

*JoinList>jlIndex2
Append (Size 3)
               (Single (Size 1) "foo")
               (Append (Size 2)
                   (Single (Size 1) "bar")
                   (Single (Size 1) "baz"))

*JoinList> dropJ 1 jlIndex2
Append (Size 2) (Single (Size 1) "bar") (Single (Size 1) "baz")

*JoinList> dropJ 2 jlIndex2
Single (Size 1) "baz"

*JoinList> dropJ 3 jlIndex2
Empty

*JoinList> dropJ 0 jlIndex2
Append (Size 3)
               (Single (Size 1) "foo")
               (Append (Size 2)
                   (Single (Size 1) "bar")
                   (Single (Size 1) "baz"))


texts:
I am more or less a Java noob and wanted some feedback on a method I wrote. I wanted to avoid the pattern of checking if a key exists before accessing the value and throw an exception if the key does not exist.

Instead of doing this:

if (map.containsKey(key)) {
    return map.get(key)
}
else {
    throw new IllegalArgumentException();
}

everywhere in the code, I came up with the following solution:

class Utils {
    public static <K, V> V safeGet(final K key, Map<K,V> map) {
        if (map.containsKey(key)) {
            return map.get(key);
        } else {
            throw new IllegalArgumentException();
        }
    }
}

Is there anything wrong with this method? Do you see any problems with this approach?


texts:
I want to create an like button like on Twitter. I used Twitter bootstrap and this code:

$(document).ready(function(){
  $('.btn-follow').on('mouseover', function(e){
    if ($(this).hasClass('following')){
      $(this).removeClass('btn-primary').addClass('btn-danger').text('UnFollow');
    }
  })
  $('.btn-follow').on('mouseleave',function(e){
    if ($(this).hasClass('following')){
      $(this).text('Following').removeClass('btn-danger').addClass('btn-primary');
    }
  })
  $('.btn-follow').on('click',function(e){
    $(this).toggleClass('following follow')
    if ($(this).hasClass('follow')){
      alert('unfollow')
      $(this).text('Follow').removeClass('btn-danger')
    }else{
      alert('follow')
      $(this).text('Following')
    }
  })
});

And in HTML I have this:

  <button class="btn btn-primary btn-follow following">Following</button>

  <button class="btn btn-follow follow">Follow</button>

But I think it's very dirty code and has some bugs. How can I summarize this code?

This code has a bug. When I click on click of the follow button, the text is changed to "Following", but the color of the button is not changed while the mouse leave from the button area. How I can fix it?


texts:
I am using the function inputSetup to prepare an array for a multi-select directive. I am passing in an array with the existing selections ($scope.item.categories), an array with all the available categories, and a string the carries the context of the values "category".

Formatting the array to add the value "ticked" = true; on each object, so that the multi-select understand which options are selected.
Concatenating the arrays.
Sorting the arrays.
Using a for loop to iterate through the array and removing any duplicates that have the same "category" key... then removing the one that has "ticked" = false.

This code feels like it can be improved.

Should the .concat and .sort be chained together?
Should the for loop be replaced with an array.filter()?

$scope.categories = inputCategories($scope.item.categories, $scope.settings.categories, "category");

function inputSet (input, settings, category) {
  var updatedSettings = [];

  angular.forEach(input, function(obj) {
    var setting = { "ticked": true };
    setting[category] = obj;
    updatedSettings.push(setting);
  });

  var list = updatedSettings.concat(settings);

  list.sort(function(a, b) {
    return (a[category] > b[category]) - (a[category] < b[category]);
  });

  for ( var i = 1; i < list.length; i++ ){
    if(list[i-1][category] == list[i][category]) {
      list.splice(i,1);
    }
  }
  return list;
};


texts: Displaying a user's social media information

texts:
This is for a page where it displays some social media information for that user.

I would like to improve the following code that I posted below.  It does the job perfectly, but I just feel like it could definitely be improved.  I could easily leave it the way it is but I am trying to learn and that's why I would like to get suggestions from experienced programmers.

<?php
if($facebook && !$twitter_username || !$facebook && $twitter_username) {
    $width = "490";
} else {
    $width = "930";
}
?>

<div style="width:<?=$width;?>px;margin:auto;">
    <?php if($facebook) { ?>

Like Us
on Facebook

<?php } ?>
    <?php if($twitter_username) { ?>

Follow Us
on Twitter
@<?=$twitter_username;?>
<?php } ?>

<?php
if($twitter_username) {
    if($display_tweets) {
 ?>

Latest Tweet

<?php
    }

}
if(!$display_tweets || !$twitter_username) {
    if($website_url) {
?>

Visit Our Website
www.<?=$website_url;?>

<?php
    }
}
?>

In the database there are 4 fields:

Facebook (NULL or 1)
Twitter username (NULL or username)
display_feed (NULL or 1)
Website URL (NULL or URL domain.com format)