texts: PHP script that combines data from two CSV files to produce two new files

texts:
I've spent some time looking at various posts on Stack Overflow regarding PHP CSV file manipulation and have devised a script that combines data from two CSV files to create two new files.

The aim of the task was to combine voucher numbers from one file to the customer data in another, along with the current date. I achieved this by extracting all the necessary data and writing it to a new file.

As some additional security/record keeping I've also combined the voucher data with the customer ID and current date to another file, for reference if needed.

I'm relatively new to PHP so your feedback would be greatly appreciated so that I might improve my code/logic:

// Open files for reading
$customers = fopen("customerTest1.csv", "r");
$vouchers = fopen("vouchersExtra.csv", "r+");

// Create new files to write data
$customerOutput = fopen("customerUpdated.csv", "w");
$voucherOutput = fopen("vouchersUpdated.csv", "w");

// Get columns from customer data and voucher data
$customerColumns = fgetcsv($customers, 1000);
$voucherColumns = fgetcsv($vouchers, 1000);

// Add extra columns for the output files
array_push($customerColumns, "voucherNumber", "dateApplied");
array_push($voucherColumns, "id", "dateUsed");

// Write the column headers to both customer and voucher output files
if (!$voucherOutput && !$customerOutput) {
    die("$voucherOutput and $customerOutput BROKE");
} else {
    fputcsv($customerOutput, $customerColumns);
    fputcsv($voucherOutput, $voucherColumns);
}

// Open the input
if (!$customers) {
    die("$customers BROKE");
} else {

    while (!feof($customers)) {

        // Extract current customer row of data
        $currentCustomer = fgetcsv($customers, 1000);

        // Only run the code if a current customer row exists
        if ($currentCustomer != false) {

            // Extract current voucher row of data
            $currentVoucher = fgetcsv($vouchers, 1000);

            // Get current customer's ID
            $customerId = $currentCustomer[0];

            // Merge customer and voucher data and push a date string to the end of the array
            $newCustomerRow = array_merge($currentCustomer, $currentVoucher);
            array_push($newCustomerRow, date("l jS \of F Y h:i:s A"));

            // Merge voucher data, customer ID and push a date string to the end of the array
            $newVoucherRow = [];
            array_push($newVoucherRow, $currentVoucher[0], $customerId, date("l jS \of F Y h:i:s A"));

            // Write new customer data to output file
            fputcsv($customerOutput, $newCustomerRow);

            // Write new voucher data to output file
            fputcsv($voucherOutput, $newVoucherRow);

        }

    }

}


texts: identifying pairwise groups from dictionary

texts:
I have a dictionary that looks like this

masterdict = {'a':['b','c','d','e'],
         'b':['c','d','e'],
         'c':['d','e'],
         'd':['e']
         'e':[]}

where the list has all the values that are 'compatible' with the key and vice-versa. Since the dictionary is non-redundant, repeated compatiblities are not reported in the dictionary. For eg. 'e' is compatible with 'a','b','c' and 'd' but masterdict['e'] is empty since it is reported in the other lists. I would like to identify all groups of elements, such that all the elements are mutually compatible. Hence for the masterdict given above, the solution would be [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'e'], ['a', 'b', 'd', 'e'], ['a', 'c', 'd', 'e'], ['b', 'c', 'd', 'e']]. Not showing lists of smaller size.

masterdict = {'a':['b','d','e'],
         'b':['c','d'],
         'c':['e'],
         'd':['e'],
         'e':[] }

then the solution would be [['a', 'b', 'd'], ['a', 'd', 'e']]. I did write a recursive function to do this, but it is slow for larger dictionaries (len(list) > 1000). The code is given below. I would like some suggestions on how to write a faster version, maybe using itertools or some other module. Thanks alot

import sys
import os

def recursive_finder(p1,list1,masterdict,d,ans):
        # if lenght of d is more than 2, store that list in ans
        if len(d) >2 :
                ans.append(d)
        nextlist = []
        # if lenght of list is 0, do not do anythin
        if len(list1) == 0:
                pass
        else:
                other = []
                for i in list1:
                        if i in masterdict[p1]:
                                new = []
                                new.extend(d)
                                new.append(i)
                                other.append(new)
                                nextlist.append(i)
                for i in range(len(nextlist)):
                        p1 = nextlist[i]
                        dnew = other[i]
                        recursive_finder(p1,nextlist[i+1:],masterdict,dnew,ans)

masterdict = {'a':['b','d','e'],
         'b':['c','d'],
         'c':['e'],
         'd':['e'],
         'e':[] }

final = []
ans = []
for mainkey in masterdict:
        if len(masterdict[mainkey]) > 1:
                for i in range(len(masterdict[mainkey])):
                        p1 = masterdict[mainkey][i]
                        recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)

print(ans)


texts: Switching some text labels when the first image of a carousel is active

texts:
Is there any way I can simplify this inefficient piece of JavaScript?

$(function () {
    var $carousel = $('#carousel');
    var $switch = $('#switch');
    var $header = $('#header');
    var $submit = $('#submit');

    $carousel.bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        if (index == 0) {
            $header.text('Sign In');
            $switch.text('Sign Up');
            $submit.text('Sign In');
            $submit.attr('form', 'sign_in');
        } else {
            $header.text('Sign Up');
            $switch.text('Sign In');
            $submit.text('Sign Up');
            $submit.attr('form', 'sign_up');
        }
    });
});


texts:
I am trying to test #initialize of class Author:

# lib/author.rb
class Author
  attr_reader :name, :filename, :website

  def initialize(name, filename, website)
    @name = name
    @filename = filename
    set_filename_from_name if filename == :auto
    @website = website
  end
end

In reality there are 8-9 properties of Author, not just 3 and I've decided to require them all in #initialize.

I am trying to dry up my specs, but I have lots of repetitions.

I have created a helper module:

#spec/helpers/create_author.rb
module CreateAuthor
  # Creates author with default values except for those listed
  # under params.
  def create_author(params = {})
    defaults = {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    }
    opt = defaults.merge(params)

    Author.new(opt[:name],
      opt[:filename],
      opt[:website])
  end
end

But now I have untested code which I need to test. This is spec for that helper method:

# spec/authors_helper_spec.rb
require_relative 'helpers/create_author'

describe 'Create Author Helper' do
  # subject do
  #   Class.new { include CreateAuthor }
  # end
  include CreateAuthor

  let(:defaults) do
    {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    }
  end

  describe '#create_author' do
    it 'returns author with default values when called with no parameters' do
      author = create_author()

      expect(author.class).to eq(Author)
      expect(author.name).to eq(defaults[:name])
      expect(author.filename).to eq(defaults[:filename])
      expect(author.website).to eq(defaults[:website])
    end

    it 'returns author with custom name when specified' do
      author = create_author(name: 'New Name')

      expect(author.class).to eq(Author)
      expect(author.name).to eq('New Name')
      expect(author.filename).to eq(defaults[:filename])
      expect(author.website).to eq(defaults[:website])
    end
  end
end

I will need to do similar thing for other class, so I will just change create_author(options={}) to create_class(class, options={}) and test that.

How can I DRY this up and make it less verbose?


texts:
I wrote a function to replace color in a bitmap image. For beginners in image processing, it could be exclusively useful, since they could use it to replace the entire gamma of a color or to replace a color with gradient/abstract lines, following the function's logic.

The main problem of the function, according to performance, is that it isn't fast enough.
For larger images/replacing more then one color, this could take a minute or even more.
I am sure there is a huge room for improvement of this function, therefore speed-optimized.

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

#define IMAGE_WIDTH         500
#define IMAGE_OFFSET_SIZE   2
#define IMAGE_OFFSET_PIXELS 54

typedef unsigned char byte;
typedef unsigned long dword;

int main (int argc, char *argv[])
{
    dword bitmap_color_replace (char *, byte, byte, byte, byte, byte, byte);

    printf("Pixels successfully replaced: %i\n",
    bitmap_color_replace("sample.bmp", 255, 255, 255, 0, 200, 255));

    return EXIT_SUCCESS;
}

/**************************************************************************/

dword
bitmap_color_replace
(char *file_name, byte old_r, byte old_g, byte old_b, byte new_r, byte new_g, byte new_b)
{
    dword fp_height = 0;
    dword fp_size;
    FILE* fp = fopen(file_name, "r+b");
    dword i, pixels_replaced = 0;

    byte new_color[3];

    new_color[0] = new_b;
    new_color[1] = new_g;
    new_color[2] = new_r;

    fseek(fp, IMAGE_OFFSET_SIZE, SEEK_SET);
    fp_size = fgetc(fp) + fgetc(fp)*256 + fgetc(fp)*(256*256) + fgetc(fp)*(256*256*256);

    for(i = IMAGE_OFFSET_PIXELS; i < fp_size; i += sizeof(new_color))
    {
        byte current_r, current_g, current_b;

        fseek(fp, i, SEEK_SET);

        if(i == IMAGE_OFFSET_PIXELS + (IMAGE_WIDTH * (fp_height+1))) // skip padding
        {
            fp_height++;
            i += IMAGE_WIDTH % 4;
            fseek(fp, IMAGE_WIDTH % 4, SEEK_CUR);
        }

        current_b = fgetc(fp);
        current_g = fgetc(fp);
        current_r = fgetc(fp);

        if(current_b == old_b && current_g == old_g && current_r == old_r)
        {
            fseek(fp, i, SEEK_SET);
            fwrite(new_color, sizeof(new_color), 1, fp);
            pixels_replaced++;
        }
    }

    fclose(fp);
    return pixels_replaced;
}


texts: Count occurrences of date-time in large CSV

texts:
My input file is a CSV of varying size, up to around 10GB. The file has several fields, however I'm only interested in the third column, a date-time field. The date-times are in UTC timezone, and they are not ordered.

Example of values in column:

2017-08-03T10:22:31.000Z
2017-08-03T10:22:32.000Z
2017-08-03T10:22:37.000Z
2017-08-03T10:22:40.000Z
...

My desired output is a CSV which counts the number of date-times by hour, which have been converted to a specified user timezone.

example output file:

2017-08-01 05:00:00,230
2017-08-01 06:00:00,3340
2017-08-01 07:00:00,4362
2017-08-01 08:00:00,1747
2017-08-01 09:00:00,5676
2017-08-01 10:00:00,6955
...

Below is the working code I have written:

dates = {}
with open(myInputFile) as file:
    reader = csv.reader(file)
    for row in reader:
        row_date = datetime.datetime.strptime(row[2],"%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=tz.gettz('UTC'))
        row_date = row_date.astimezone(tz.gettz(newTimezone)).replace(tzinfo=None)
        row_date = row_date.strftime("%Y-%m-%d %H:00:00") #Strips minute and below info

        if row_date in dates:
            dates[row_date] += 1
        else:  #If date not in dictionary add entry
            dates[row_date] = 1

rows = zip([k for k in sorted(dates)],[dates[k] for k in sorted(dates)]) #changes dict to date ordered zip
with open('WaypointCount.csv'),'w', newline='') as output: #saves to csv
    wr = csv.writer(output)
    for row in rows:
        wr.writerow(row)

Basically I use the csv module to read each entry line by line.

I convert the string into a datetime, and set it's timezone to UTC.

I then convert the datetime to the new Timezone. The reason I do that at this step rather than later is because some timezones are offset from UTC by 30 minutes, which would mess up my hourly grouping.

I then convert it back into a string, stripping away the minute, second and microsecond information, and add a count to my dictionary.

Once I have looped through every row I convert my dictionary into two lists ordered by the Date key, zip them together, and write to a new csv.

I feel like I've probably converted between too many datatypes. How can I improve this code so it follows best practices, and runs optimally?


texts: Pythonic way of managing data for plotting 2D variance plots

texts:
I have collected large dataset of trajectories in 3D space. Below is the information about dataset-

Each trajectory (shape: n x 4) is saved into CSV file with the following header: time, p_x, p_y, p_z
The filenames are defined in following way: subject_i_trail_i.csv, where i starts from 1 to 10.

Below are first 10 lines from subject_1_trail_1.csv file-

time    p_x     p_y     p_z
0       0.4333  0.1107  0.1259
0.0103  0.4336  0.1106  0.126
0.02    0.4334  0.1108  0.1259
0.03    0.4333  0.1106  0.1259
0.04    0.4334  0.1107  0.1259
0.0501  0.4328  0.1103  0.126
0.06    0.4331  0.1107  0.1255
0.0703  0.4331  0.1103  0.126
0.08    0.4324  0.1102  0.126

For each subject, I want to plot the trajectory showing median and variance as shown below-

fill_between(x, perc_25, perc_75)

I am using NumPy but the code is relatively long. Below is the code snippet-

from pylab import *
import sys

# make a 3d numpy array (chop off the extra rows)
def load(location, subject, suffix):
    all_data = []
    min_rows = sys.maxint
    for i in range(1, 11):
        file_name = location + subject + '_trail_' + str(i) + '.csv'
        data = np.loadtxt(file_name, delimiter=',', skiprows=1)
        if data.shape[0] < min_rows:
            min_rows = data.shape[0]
        all_data.append(data)

    all_crop_data = []
    for data in all_data:
        all_crop_data.append(data[:min_rows,:])

    return np.array(all_crop_data)

def proc(data):
    t = data[:, :, 0] # first column is time
    x = data[:, :, 1] # second column is x
    y = data[:, :, 2] # third column is y
    z = data[:, :, 3] # fourth column is z

    t_median  = np.zeros(data.shape[1])
    t_perc_25 = np.zeros(data.shape[1])
    t_perc_75 = np.zeros(data.shape[1])

    x_median  = np.zeros(data.shape[1])
    x_perc_25 = np.zeros(data.shape[1])
    x_perc_75 = np.zeros(data.shape[1])

    y_median  = np.zeros(data.shape[1])
    y_perc_25 = np.zeros(data.shape[1])
    y_perc_75 = np.zeros(data.shape[1])

    z_median  = np.zeros(data.shape[1])
    z_perc_25 = np.zeros(data.shape[1])
    z_perc_75 = np.zeros(data.shape[1])

    for i in range(data.shape[1]): # for each timestamp
        t_median[i]  = np.median(t[:, i])
        t_perc_25[i] = np.percentile(t[:, i], 25)
        t_perc_75[i] = np.percentile(t[:, i], 75)

        x_median[i]  = np.median(x[:, i])
        x_perc_25[i] = np.percentile(x[:, i], 25)
        x_perc_75[i] = np.percentile(x[:, i], 75)

        y_median[i]  = np.median(y[:, i])
        y_perc_25[i] = np.percentile(y[:, i], 25)
        y_perc_75[i] = np.percentile(y[:, i], 75)

        z_median[i]  = np.median(z[:, i])
        z_perc_25[i] = np.percentile(z[:, i], 25)
        z_perc_75[i] = np.percentile(z[:, i], 75)

    all_median  = np.vstack((t_median, x_median, y_median, z_median)).T
    all_perc_25 = np.vstack((t_perc_25, x_perc_25, y_perc_25, z_perc_25)).T
    all_perc_75 = np.vstack((t_perc_75, x_perc_75, y_perc_75, z_perc_75)).T

    return all_median, all_perc_25, all_perc_75

s1 = load('/Desktop/', 'subject_1') # subject 1
s2 = load('/Desktop/', 'subject_2') # subject 2

x = np.arange(0, s1.shape[1])

s1_med, s1_perc_25, s1_perc_75 = proc(s1)
s2_med, s2_perc_25, s2_perc_75 = proc(s2)

# lets plot only x (second column)
index = 1
s1_med     = s1_med[:, index]
s1_perc_25 = s1_perc_25[:, index]
s1_perc_75 = s1_perc_75[:, index]

s2_med     = s2_med[:, index]
s2_perc_25 = s2_perc_25[:, index]
s2_perc_75 = s2_perc_75[:, index]

fill_between(x, s1_perc_25, s1_perc_75, alpha=0.25, linewidth=0, color='#B22400')
fill_between(x, s2_perc_25, s2_perc_75, alpha=0.25, linewidth=0, color='#006BB2')

plot(x, s1_med, linewidth=2, color='#B22400')
plot(x, s2_med, linewidth=2, color='#006BB2')

I am looking for a better, i.e., pythonic way to achieve the same. I am not sure if Pandas can be useful here. Looking for your suggestions, please.


texts: Conditional functions or multiple similar definitions?

texts:
In my program(C++), I'm going to use callback functions to process input from the keyboard and mouse and constantly draw a scene. How these functions process information will change depending on the state of the program; like I would have certain functionality assigned to several keys, say the arrow keys move the highlighter in the main screen, but I want their functionality to change in another screen. I'm using OpenGL with GLUT, and it's possible to change the keyboard function for example by assigning a different function pointer to it.

The method I used in the past was to define multiple processing functions, each one for a specific task. For example, I have a keyboard for the main menu, but when a different screen is viewed, the function is changed by assigning the appropriate function pointer:

glutKeyboardFunction(MainMenueKeyboardFuncPtr);

But now, I'm wondering if using conditional statements within one function is a better approach.

My question is: are there any performance issues with the conditional functions approach? I'm thinking to define a single function, say for the keyboard, to process keyboard input in all situations:

void KeyInputProcess(int key)
{
   select(SCREEN)
 {

   case MAIN_SCREEN:

  select(key)
   {
 /*process input*/
   }
   break;

    case OPTIONS_SCREEN:

     select(key)
     {
      /*process differently from MAIN_SCREEN*/
     }
     break;
 }

}

Would the checking that takes place every time the function is called have a significant impact on the performance? Which approach is better if I want to maximize performance?


texts:
I want to increase the efficiency and reduce the time complexity for the n-queen problem in n*n matrix chess. I am able to run only still (11*11) in normal time otherwise for the big number it is taking much more time. How can I improve performance?

import time

start_time = time.time()

def queensproblem(rows, columns):
    solutions = [[]]
    for row in range(rows):
        solutions = add_one_queen(row, columns, solutions)
    return solutions

def add_one_queen(new_row, columns, prev_solutions):
    return [solution + [new_column]
            for solution in prev_solutions
            for new_column in range(columns)
            if no_conflict(new_row, new_column, solution)]

def no_conflict(new_row, new_column, solution):
    return all(solution[row]       != new_column           and
               solution[row] + row != new_column + new_row and
               solution[row] - row != new_column - new_row
               for row in range(new_row))

count = 0
r = input("Enter number of ROWS for Chess/Matrix: ")
c = input("Enter number of COLUMNS for Chess/Matrix: ")

for solution in queensproblem(int(r), int(c)):
    count += 1
    print(solution)

print("\n Total number of solution is: ", count)

print("--- Time: %s seconds ---" % (time.time() - start_time))

Output

For a 4x4 matrix

Enter number of ROWS for Chess/Matrix: 4
Enter number of COLUMNS for Chess/Matrix: 4
[1, 3, 0, 2]
[2, 0, 3, 1]

 Total number of solution is:  2
--- Time: 2.3161020278930664 seconds ---

For a 12x12 matrix

Enter number of ROWS for Chess/Matrix: 12
Enter number of COLUMNS for Chess/Matrix: 12
[0, 2, 4, 7, 9, 11, 5, 10, 1, 6, 8, 3]
[0, 2, 4, 9, 7, 10, 1, 11, 5, 8, 6, 3]
<more output>

 Total number of solution is:  14200
--- Time: 29.522358894348145 seconds ---


texts:
I've started looking at Heroku for application hosting and deployment and it appears that my configuration constants need to be stored in environment variables. I can do this in Heroku, but my application might also be deployed to shared servers and it may not be secure according to this question.

Basically I want the information to be read from a configuration file if it is present, otherwise try to read from the environment variables (in the case of Heroku).

Is this the best way of doing it?
Are there security implications?

settings.php

<?php

define('DB_URL', 'mysql://root:password@localhost:3306/database');
define('APP_URL', '[::1]');
define('APP_URL_PATH', '/path/to/application');
define('FOO', 'more things');

config.php

<?php

if (!is_file('settings.php')) {
    require 'settings.php';
    return;
}

define('DB_URL', getenv('DB_URL'));
define('APP_URL', getenv('APP_URL'));
define('APP_URL_PATH', getenv('APP_URL_PATH'));
define('FOO', getenv('FOO'));

index.php (and other application files)

<?php

require 'config.php';

$app = new \Slim\Slim\App();

// code

$app->run();


texts: Pulling JSON using jQuery and manipulating the Front-end

texts:
My JavaScript is fairly new and want to learn new ways to create clean, fast code. Can you have a look at this code and guide me on how to optimise this code to improve my skills? I have provided the HTML even though I am not able to edit the actual html as its generated but lets pretend I could..

What I am doing is pulling data from a Product JSON file and manipulating the data to be shown in the website.

function Details(el){
    var sku = $(el).attr("data");
    $.getJSON("/micro/"+sku, function(json) {
        if (json.price!=null) {
          $(el+' .p_img img').attr({src:json.images[2].url, alt:json.images[2].altText});
          $(el+' .p_img_lrg').attr("src",json.images[1].url);
          $(el+' .p_name').text(json.name);
          $(el+' .p_url').attr("href",json.url);
          $(el+' .p_p').text("£"+Number(json.p.value).toFixed(2));
          $(el+' .p_pu').text(json.pu);
          $(el+' .p_b_name').text(json.categories[0].name);
          $(el+' .p_b_url').attr("href",json.categories[0].url);
        if (json.oldPrice != null) {
          var pWas = ' .p_was',
              pSave = ' .p_save';
          $(el+pWas).text("was £"+json.old.value);
          $(el+pSave).text("save £"+(json.old.value-json.value));
          $(el+pSave).hide();
          $(el+pWas).css('margin-left',0).css('padding-left',0).addClass('clr').removeClass('left').css('float','none');
        }else{
          $(el+pSave,el+pWas).hide();
        }
    }

    if (json.stockLevel==0) {
      $(el+' form.add').attr({'action':'/notification','method':'post'}).html('<input type=\"hidden\" name=\"productCodePost\" value=\"'+sku+'\"><input type="submit" value="Out">');
    } else {
      $(el+' form.add').attr({'action':'/add','method':'post'}).html('<input type=\"hidden\" name=\"productCodePost\" value=\"'+sku+'\"><input type=\"hidden\" name=\"maxOrderQuantity\" value=\"\"><input type="submit" value="Add">');
    }
});
}

HTML:

        #
        test

                    now
                    &pound;

        <form class="add_to_cart_form">&nbsp;</form>

View All  Products


texts: Attempt at checking whether two words are permutations

texts:
This is my first algorithm in C++ ever to check if two strings are permutations of each other. Please provide guidance on correctness of algorithm + ways to improve + thoughts on my use of the language itself.

The idea is two create two dictionaries which count the number of occurrences of each character using two for loops, and then we use a final for loop to check if the counts are equal.

void checkPermut(std::string &sentence1, std::string &sentence2)
{
    std::map<char, int> dict1;
    std::map<char, int> dict2;

    for (char & c : sentence1)
    {
        if (dict1.find(c) == dict1.end())
        {
            dict1.insert(std::pair<char, int>(c, 1));
        }
        else
        {
            dict1[c] == dict1[c] + 1;
        }
    }

    for (char & c : sentence2)
    {
        if (dict2.find(c) == dict2.end())
        {
            dict2.insert(std::pair<char, int>(c, 1));
        }
        else
        {
            dict2[c] == dict2[c] + 1;
        }
    }

    bool arePermut = true;

    for (char & c : sentence2)
    {
        if (dict1.find(c) == dict1.end())
        {
            arePermut = false;
            std::cout << "Not permutations." << std::endl;
            break;
        }
        else if (dict1[c] != dict2[c])
        {
            arePermut = false;
            std::cout << "Not permutations." << std::endl;
            break;
        }
    }

    if (arePermut)
    {
        std::cout << "Are permutations" << std::endl;
    }

}

int main()
{
    std::string somestring1;
    std::string somestring2;

    std::cin >> somestring1 >> somestring2;
    checkPermut(somestring1, somestring2);

    return 0;
}


texts:
#include <stdio.h>
#include <stdlib.h>

struct Stack {
  int value;
  int is_empty;
  struct Stack *next;
};

int pop(struct Stack **stack) {
  if ((*stack)->is_empty == 1) {
    printf("Stack is empty!\n");
    abort(); // not sure what this does
  } else {
    int value = (*stack)->value;
    // outer pointer (static) points to new stack now
    *stack = (*stack)->next;
    return value;
  }
}

void push(struct Stack **stack, int value) {
  // malloc is used so this memory can be accessed outside of scope
  struct Stack *head = malloc(sizeof(struct Stack*));
  if (head != NULL) {
    head->value = value;
    // head's next is pointer to stack
    head->next = *stack;
    head->is_empty = 0;
    // stack now holds pointer to head
    *stack = head;
  } else {
    printf("push memory no alloc");
  }
}

struct Stack *empty() {
  struct Stack *head = malloc(sizeof(struct Stack *));
  if (head != NULL) {
    head->value = 0;
    head->is_empty = 1;
    head->next = NULL;
    return head;
  } else {
    return NULL;
  }
}

int main() {
  struct Stack *init = empty();
  struct Stack **stack = &init;
  push(stack, 3);
  push(stack, 2);
  push(stack, 1);
  int one = pop(stack);
  printf("one: %d\n", one);
  int two = pop(stack);
  printf("two: %d\n", two);
  int three = pop(stack);
  printf("three: %d\n", three);
  //int hmm = pop(stack);
}

I'm not sure pointers to pointers is the best way to do this. I also feel like I'm writing code in a Java-y way, and would like to know how to improve my C style.

Also, are there any edge cases I am missing?


texts: Archiving an SQL table of sessions and statistics

texts:
What my query is doing:

I have two SQL tables and I want to copy datarows from the one table to the other table. I am doing this for statistics. The source table includes all current member-sessions/logins and with my statistics table I also want to see member-logins of the past. Thus I want to store these data into my bot_sessions_statistics table as well to make sure they are not being updated anymore:

The original query:

INSERT INTO bot_sessions_statistics (member_id, session_token, username, ip_address)
SELECT sessions.member_id, sessions.session_token, sessions.username, sessions.ip_address
FROM bot_sessions AS sessions
LEFT JOIN
(
    SELECT stats.member_id, stats.session_token, stats.username, stats.ip_address
    FROM bot_sessions_statistics as stats
    WHERE date_active >= date(NOW())
) AS stats
ON sessions.member_id = stats.member_id
WHERE latest_renewal >= date(NOW())
AND stats.member_id IS NULL

The performance of the original query:

Query_time: 86.364613  Lock_time: 0.000085 Rows_sent: 0  Rows_examined: 1088312551

The table structures:

Table bot_sessions:

Table bot_sessions_statistics:

The performance of single queries:

SELECT sessions.member_id, sessions.session_token, sessions.username, sessions.ip_address
FROM bot_sessions AS sessions
WHERE latest_renewal >= date(NOW())

Returns 44.2k rows (Duration: 0.078s / Fetch: 1.607s)

SELECT stats.member_id, stats.session_token, stats.username, stats.ip_address
FROM bot_sessions_statistics as stats
WHERE date_active >= date(NOW())

Returns 23.3k rows (Duration: 0.047s / Fetch 0.920s)


texts: Localization of multi style text element in Vue

texts:
After following up this question, I'm thinking if there's a better/shorter way to write this text element that has part with different style, while allowing localizations:

    {{ $store.releaseList != null ? $store.releaseList.length : 0 }}
     versions released

With vue-i18n:

<p v-html="$t('downloads.releases.table.versions-total')
    .replace('{0}', '{1}')
    .replace('{1}', $store.releaseList != null ? $store.releaseList.length : 0)">

The localizable text would be {0} versions released.

I could set the localizable text to {0} versions released, but that would make the life of the translators (usually people without knowledge about HTML) a bit more difficult.

Is there any better built in way to add support for localizations in a multi-styled text?


texts: Comparing two arrays to see if they contain objects with different IDs

texts:
This feels like the kind of problem that has an extremely elegant solution. But my code is mechanical and straightforward. Not bad but I'm interested if there's something nicer.

Performance is not really an issue. I'm looking for elegant/shorter, not faster.

No underscore.js please; it's not worth fighting my coworkers to get another third-party library in there, especially when it duplicates so much ES5. Speaking of which, we work in an ES5-only environment so use all the array extras you want.

function getIds(array) {
    // We have added `Array.prototype.unique`; it does what you'd expect.
    return array.map(function (x) { return x.id; }).unique().sort();
}

function areDifferentByIds(a, b) {
    var idsA = getIds(a);
    var idsB = getIds(b);

    if (idsA.length !== idsB.length) {
        return true;
    }

    for (var i = 0; i < idsA.length; ++i) {
        if (idsA[i] !== idsB[i]) {
            return true;
        }
    }

    return false;
}


texts:
When a user is created, deleted and update the system will give feed back. e.g. User Deleted/Updated/Create success or unsuccessfully, but I'm sure there is a better way to do it than what I have done because I repeat the same code in all functions within my class.

Code to create user

$userOne = new userActions($database, 'Greg', '324b2643243');//
echo $userOne->create();

Code to delete user

$userOne = new userActions($database, 'Abel'); //
echo $userOne->delete();

Code for user creation

public function create()
{//Works
    $outPut = "";
    if(!$this->user_exists)
        {
            list($password_hash, $salt) = $this->hash($this->password);
            echo 'Hash: ' . $password_hash . '
' . 'Salt: ' . $salt . '
';
            $result = $this->connection->query("INSERT INTO users VALUES( NULL, '{$this->username}' , '{$password_hash}' , '{$salt}' ) ");

            if($result)
                {
                    $outPut = "User has been created";
                }
                else
                {
                    $outPut = "User could not be created";
                }

        }
        else
        {
            $outPut = 'Username already exists';
        }

    return $outPut;
}

Is there a better way to display feedback to the user istead of having $outPut every time in all of my create, delete and update functions?


texts:
#include <iostream>

template <typename T>
class my_smart_ptr {
    T* raw;
    unsigned * p_count;
public:
    my_smart_ptr(T* t):
    raw(t),
    p_count (new unsigned(1))
    {

    }

    my_smart_ptr(const my_smart_ptr<T> & p):
    raw(p.raw),
    p_count(p.p_count)
    {
        ++(*p_count);
    }

    const my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p)
    {
        if (p == *this)
        {
            return *this;
        }

        raw = p.raw;
        --(*p_count);
        ++(*(p.p_count));
        return *this;

    }

    ~my_smart_ptr()
    {
        --(*p_count);
        if (*(p_count) == 0)
        {
            delete raw;
        }
    }
};

class A{
public:

    A()
    {
        std::cout<< "A()" << std::endl;
    }

    ~A()
    {
        std::cout<< "~A()" << std::endl;
    }

};
int main()
{
    my_smart_ptr<A> a (new A);
    return 0;
}


texts: Cleaning parameters before passing them to a model

texts:
I'm writing an API and want to be able to pass in the attributes of a model without prefixing them with the name of the model.

I wrote this little extension to ActiveRecord in order to make it happen:

module ActiveRecord
  class Base
    def self.filter_attributes(hash)
      hash.stringify_keys.slice(*self.accessible_attributes.to_a)
    end
  end
end

And I use it like this:

class IdeaController < ActiveRecord::Base
  def create
    @idea = Idea.create(Idea.filter_parameters(params))
    respond_with @idea
  end
end

I have two questions:

What do you think about the name of the method? filter_parameters() seemed to make sense, but it's a little generic.
Are there uses of this that I'm not thinking of and that would cause problems, such as passing in nested attributes?


texts:
I was tasked with creating the class RandomStringChooser that prints the strings in the passed array in a random order, based on the for loop in the tester. If the number of iterations in the for loop is larger than the size of the array passed, then "NONE" should be returned. Look at the tester in the program for an example of how this is run.

I'm looking for feedback on code efficiency, neatness, and other nitpicks that can improve the look of my code. I'd very much like to kick bad habits to the curb.

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

// Declare the RandomStringChooser class

public class RandomStringChooser {

    /** Declare any fields (instance variables) **/
    private ArrayList<String> wordArray;
    private Random r;

    /** Declare any constructors */
    public RandomStringChooser(String[] wordArray) {
        this.wordArray = convert(wordArray);
        this.r = new Random();
    }

    /**Convert array to arraylist**/
    private ArrayList<String> convert(String[] array) {
        ArrayList<String> arraylist = new ArrayList<String>();
        for(String string : array) {
            arraylist.add(string);
        }
        return arraylist;
    }

    /** Write the getNext method */
    public String getNext() {
        if(this.wordArray.size() != 0) {
            int index = r.nextInt(this.wordArray.size());
            String word = this.wordArray.get(index);
            if(word != null) {
                this.wordArray.remove(index);
                return word;
            }
            return "NONE";
        }
        return "NONE";
    }

    /** This is a main method for testing the class */
    public static void main(String[] args) {
        System.out.println("It should print the words in the array in a random order and then NONE twice");
        String[] wordArray = {"wheels", "on", "the", "bus"};
        RandomStringChooser sChooser = new RandomStringChooser(wordArray);
        //This loop will output the words in `wordArray` in random order, then "NONE" twice
        for (int k = 0; k < 6; k++) {
            System.out.println(sChooser.getNext() + " ");
        }
        //This loop will output the words in `wordArray` in random order, then stop
        for (int k = 0; k < 4; k++) {
            System.out.println(sChooser.getNext() + " ")
        }

     } // end of main

} // end of class


texts:
I need to write a function which selects a run of repeated characters from the start of a string, with the run comprising at most nine characters.

chomp :: String -> String
chomp str =  takeWhile (== head str) str

munch :: String -> String
munch = take 9 . chomp

runs :: String -> [String]
runs string = extract string [] where
    extract str xs
        | length str == 0 = xs
        | otherwise = extract (drop (length (munch str)) str) (xs ++ [(munch str)])

I can't define any new functions (except helper ones), however, I can use all of the haskell built-in ones. Is there a nicer way to write the runs function?

Examples

runs "aaaaabbbbcc"
["aaaaa","bbbb","cc"]

runs "aaaaaaaaaaaaaaabbbbcc"
["aaaaaaaaa","aaaaaa","bbbb","cc"]

runs "dddddddddddd"
["ddddddddd","ddd"]

runs "aaabbbaaa"
["aaa","bbb","aaa"]


texts: config files for different development environments (Production, Dev, Testing)

texts:
I am following a guide that specifies how to manage different configurations (DB_URI, LOGGER_NAME, etc...) per development environments.

I create a config module that is structured like this

\my_project\config\__init__.py

import os
import sys
from . import settings

# create settings object corresponding to specified env
APP_ENV = os.environ.get('APP_ENV', 'Dev')
_current_config = vars(setting).get(f'{APP_ENV}Config')

# copy attributes to the module for convenience
for atr in [f for f in dir(_current_config) if '__' not in f]:
    # environment can override anything
    val = os.environ.get(atr, getattr(_current_config, atr))
    setattr(sys.modules[__name__], atr, val)

\my_project\config\settings.py

class BaseConfig:
    DEBUG = True
    LOGGER_NAME = 'my_app'

class DevConfig(BaseConfig):
    # In actuality calling a function that fetches a secret
    SQLALCHEMY_DATABASE_URI = 'sqlite://user.db'

class ProductionConfig(BaseConfig):
    DEBUG = False
    # In actuality calling a function that fetches a secret
    SQLALCHEMY_DATABASE_URI = 'sqlite://user.db'

calling the config

application.py

import config
config.SQLALCHEMY_DATABASE_URI

This approach is kind of a hit and miss for me.
on one hand it allows me to easily specify several environments (dev, stage, prod, dev) without having a complex if else logic in my settings.py.

On the other hand I dont like using setattr on sys.modules[__name__], seems a bit wonky to me. what do you think ?


texts:
Please review the code.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>RGB to HEX (and vice versa) converter</title>
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.0/normalize.min.css">

<input id="rgb" type="text" placeholder="rgb(255, 255, 255)">

<input id="hex" type="text" placeholder="#ffffff">

Jsbin - http://jsbin.com/fokayomo/1/


texts:
I finished the Ruby chapter in Seven Languages in Seven Weeks. It tries to make you familiar with the core concepts of several languages rather quickly. Dutifully I did all exercises, but most likely they can be improved to be more Ruby-like. I'll post my code samples one by one, so I can apply things learned in previous questions to later questions.

Day 1

  Write a program that picks a random number. Let a player guess the
  number, telling the player whether the guess is too low or too high.

range = (0..10)
to_guess = range.min + rand(range.max - range.min)
guessed = false

while !guessed
    puts "Guess a number, between #{range.min} and #{range.max}"
    guess = gets
    int = guess.to_i
    if int == to_guess
        puts 'Correct!'
        guessed = true
    else
        puts int > to_guess ? 'Lower' : 'Higher'
    end
end

After sepp2k's comments:

class Range
  def size
    self.end - self.begin
  end
end

range = 0..10
to_guess = range.begin + rand(range.size)
guessed = false

until guessed
  puts "Guess a number, between #{range.begin} and #{range.end}"
  guess = gets
  int = guess.to_i
  if int == to_guess
    puts 'Correct!'
    guessed = true
  else
    puts int > to_guess ? 'Lower' : 'Higher'
  end
end


texts:
I created a simple 4x4 matrix class (column-major). I would like it to be efficient and to use C++14's full capabilities. Can I improve it?

#include <array>

class mat4
{
public:
    constexpr mat4() noexcept : matrix() {}

    constexpr mat4(const std::array<float, 16> &m) noexcept : matrix(m) {}
    constexpr mat4(std::array<float, 16> &&m) noexcept : matrix(std::move(m)) {}

    constexpr mat4(const mat4 &other) noexcept : matrix(other.matrix) {}
    constexpr mat4(mat4 &&other) noexcept : matrix(std::move(other.matrix)) {}

    constexpr bool operator==(const mat4 &other) const noexcept
    {
        for (size_t i = 0; i < 16; ++i) {
            if ((*this)[i] != other[i]) {
                return false;
            }
        }

        return true;
    }

    constexpr bool operator!=(const mat4 &other) const noexcept
    {
        return !(this->operator==(other));
    }

    constexpr mat4& operator+=(const mat4 &other) noexcept
    {
        for (size_t i = 0; i < 16; ++i) {
            (*this)[i] += other[i];
        }
        return *this;
    }

    constexpr mat4& operator*=(float scalar) noexcept
    {
        for (size_t i = 0; i < 16; ++i) {
            (*this)[i] *= scalar;
        }
        return *this;
    }

    mat4& operator=(mat4 other) noexcept
    {
        std::swap(this->matrix, other.matrix);
        return *this;
    }

    constexpr float& operator[](size_t index) { return const_cast<float&>(static_cast<const std::array<float, 16>&>(matrix)[index]); }
    constexpr float operator[](size_t index) const { return matrix[index]; }

    void print() const noexcept
    {
        printf("\n");
        printf("[%.2f][%.2f][%.2f][%.2f]\n", matrix[0], matrix[4], matrix[8], matrix[12]);
        printf("[%.2f][%.2f][%.2f][%.2f]\n", matrix[1], matrix[5], matrix[9], matrix[13]);
        printf("[%.2f][%.2f][%.2f][%.2f]\n", matrix[2], matrix[6], matrix[10], matrix[14]);
        printf("[%.2f][%.2f][%.2f][%.2f]\n", matrix[3], matrix[7], matrix[11], matrix[15]);
    }

private:
    std::array<float, 16> matrix;
};

constexpr const mat4 operator+(mat4 lhs, const mat4 &rhs) noexcept
{
    lhs += rhs;
    return lhs;
}

constexpr const mat4 operator*(const mat4 &lhs, const mat4 &rhs) noexcept
{
    mat4 result;

    for (size_t i = 0; i < 4; ++i)
    {
        for (size_t j = 0; j < 4; ++j)
        {
            for (size_t k = 0; k < 4; ++k) {
                result[i + 4 * j] += lhs[i + 4 * k] * rhs[k + 4 * j];
            }
        }
    }

    return result;
}

constexpr const mat4 operator*(mat4 lhs, float scalar) noexcept
{
    lhs *= scalar;
    return lhs;
}

You can test it in this live demo here.


texts:
public interface ICacheable<TK,TV>
{
   TV Get(TK key);
   void Add(TK key, TV val);
}

public abstract class BaseCache<TK, TV>
{
    protected static Dictionary<Guid, Dictionary<TK, TV>> data = new Dictionary<Guid, Dictionary<TK, TV>>();
    private Guid StorageNameSpage;

    protected BaseCache(Guid storageNameSpage)
    {
        StorageNameSpage = storageNameSpage;
    }

    protected BaseCache()
    {
        StorageNameSpage = Guid.NewGuid();
    }

    public TV Get(TK key)
    {
        return data[StorageNameSpage][key];
    }

    public void Add(TK key, TV val)
    {
        data.Add(....);
     }
}

2 different ways to implement it:

"mulityTon" or what ever you want to call it.

public class KeyValCacheStorage<TK, TV> : BaseCache<TK, TV>, ICacheable<TK, TV>
{

}

SingleTome

public class KeyValCacheStorageSingleTon<TK, TV> : BaseCache<TK, TV>, ICacheable<TK, TV>
{
    private static Guid storageNameSpage = Guid.NewGuid();
    public KeyValCacheStorageSingleTon():base(storageNameSpage)
    {

    }
}

usage:

KeyValCacheStorageSingleTon<string, string> storageSingleTon1 = new KeyValCacheStorageSingleTon<string, string>();
storageSingleTon1.Add("storageSingleTon1", "KeyValCacheStorageSingleTon");
storageSingleTon1.Add("bla", "yada");

KeyValCacheStorageSingleTon<string, string> storageSingleTon2 = new KeyValCacheStorageSingleTon<string, string>();
storageSingleTon2.Add("storageSingleTon2", "KeyValCacheStorageSingleTon2");


texts: C# Security Module for generating secure hashes

texts:
Any pointers on the level of security this hashing function perform at?
I have never had to really write my own modules for security before.

public static class Hashing
{

    public static int SaltSize = 32;

    public static string HashPassword(string passwordToHash, byte[] salt, int numberOfRounds)
    {
        var hashedPassword = HashPassword(Encoding.UTF8.GetBytes(passwordToHash), salt, numberOfRounds);

        return Convert.ToBase64String(salt.Concat(hashedPassword).ToArray());
    }

    public static string HashPassword(string passwordToHash, int numberOfRounds)
    {
        var salt = GenerateSalt();
        var hash =  HashPassword(passwordToHash, salt, numberOfRounds);

        return hash;
    }
    public static byte[] GenerateSalt()
    {
        using (var randomNumberGenerator = new RNGCryptoServiceProvider())
        {
            var randomNumber = new byte[SaltSize];
            randomNumberGenerator.GetBytes(randomNumber);

            return randomNumber;
        }
    }
    public static byte[] HashPassword(byte[] toBeHashed, byte[] salt, int numberOfRounds)
    {
        using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(toBeHashed, salt, numberOfRounds))
        {
            return rfc2898DeriveBytes.GetBytes(SaltSize);
        }
    }
}

public abstract class HashVerification
{
    public abstract string GetDatabaseHash(string username);

    public bool HashMatch(string username, string password)
    {
        var combinedHash = GetDatabaseHash(username);

        var salt = Convert.FromBase64String(combinedHash).Take(Hashing.SaltSize).ToArray();

        var serverHash = Hashing.HashPassword(password, salt, username.Length * 100);

        return combinedHash.Equals(serverHash);
    }

}


texts: Generators in Javascript; Project Euler #2

texts:
I'm trying to learn javascript using project euler and I decided to try to force myself to learn about generators in javascript using problem number 2 which asks us to:  Find the sum of the even-valued terms in the fibonacci (f(n)) sequence such that f(n) < 4M , beginning with n=1 is 1, n=2 is 2, n=3 is 3 and so on

My code below presently works but I'm hoping to get some input as I began learning javascript this week. I'm coming from a python background and any input that keeps that in mind would be heavily appreciated!

function* fib_gen() {
    var current = a = b = 1;

    while (true) {
        current = b;

        yield current;

        b = a + b;
        a = current;
    }
}

function solution() {
    sequence = fib_gen();
    even_fibs_total = 0;
    cur = sequence.next().value;

    while (cur < 4000000) {
        if (cur % 2 == 0) even_fibs_total += cur;
        cur = sequence.next().value;
    }

    return even_fibs_total
}

var time_pre = performance.now()
document.write(solution())
document.write('<br>')
var time_post = performance.now()
document.write('completed in ' + Math.round((time_post - time_pre)*100)/100 + ' seconds')


texts: Extension for grouping array into two dimensional array based on element ([] -> [[]])

texts:
I'm new at generics, but I've written an array extension to group an array by array element into a two dimensional array:

extension Array {
    func group<U: Hashable>(by key: (Element) -> U) -> [[Element]] {
        //keeps track of what the integer index is per group item
        var indexKeys = [U : Int]()

        var grouped = [[Element]]()
        for element in self {
            let key = key(element)

            if let ind = indexKeys[key] {
                grouped[ind].append(element)
            }
            else {
                grouped.append([element])
                indexKeys[key] = grouped.count - 1
            }
        }
        return grouped
    }
}

For an array of this struct:

struct Thing {
   var category: String
   var name: String
}

I want to be able to group an array of things [Thing] into a two dimensional array [[Thing]] based on Thing.category.

I use the extension like this:

let things = [
   Thing(category: "A", name: "Apple"),
   Thing(category: "B", name: "Boy"),
   Thing(category: "A", name: "Alligator"),
   Thing(category: "B", name: "Ball"),
   Thing(category: "B", name: "Billboard")
]
let groupedThings = things.group { $0.category }

This returns something like:

//groupedThings
[
   [
      Thing(category: "A", name: "Apple"),
      Thing(category: "A", name: "Alligator")
   ],
   [
      Thing(category: "B", name: "Boy"),
      Thing(category: "B", name: "Ball"),
      Thing(category: "B", name: "Billboard")
   ]
]

Please note that I'm not concerned about sort order.

How does my extension look? Since I'm fairly new at this, I'd like to know if I'm over-complicating it. Is there a way to write the extension more concisely? What about speed issues?


texts: Beginner's Implementation of Guess The Word

texts:
As the title suggests, I'm a complete beginner in Haskell. I've just made my way through the "Input and Output" section of Learn You A Haskell For Greater Good and I thought it would be good to try my hand at a simple project like a "Guess The Word" game in Haskell.

The idea behind the game is to guess all the letters of a randomly selected word. If you guess all the letters, you win.

Without further ado, the complete program is below. I'm looking for feedback regarding program structure (particularly in separating I/O from pure functions), any inefficiencies I could look out for, any potential bugs, and any Haskell idioms and general best practices I could incorporate.

import Data.Char
import Data.Maybe
import System.Random

data Difficulty = Easy | Medium | Hard
    deriving (Read, Show, Eq)

createDifficulty :: String -> Maybe Difficulty
createDifficulty s = lookup s [
    ("e", Easy),
    ("m", Medium),
    ("h", Hard),
    ("", Easy)
    ]

isDifficulty :: String -> Bool
isDifficulty = isJust . createDifficulty

randomNumber :: Int -> Int -> IO (Int)
randomNumber begin end = do
    gen <- getStdGen
    return $ head $ randomRs (begin, end) gen

-- Please don't provide review about these tables. They're just meant to be demonstrative of the general idea I'm going for.
fetchWords :: Difficulty -> [String]
fetchWords Easy   = ["foo", "bar"]
fetchWords Medium = ["abc", "def"]
fetchWords Hard   = ["foobar", "whoami"]

generateSecret :: Difficulty -> IO (String)
generateSecret difficulty = do
    let table = fetchWords difficulty

    num <- randomNumber 0 (length table)

    return (table !! num)

replaceChar :: Int -> String -> Char -> String
replaceChar n s c = pre ++ [c] ++ tail post
    where (pre, post) = splitAt n s

compareSecret :: String -> String -> Int -> Char -> String
compareSecret secret guess pos c =
    if secret !! pos == c then
        replaceChar pos guess c
    else
        guess

isInt :: String -> Bool
isInt = all isDigit

isChar :: String -> Bool
isChar []     = False
isChar (c:cs) = isAlpha c && null cs

promptUntil :: (String -> Bool) -> String -> (String -> IO ()) -> IO (String)
promptUntil pred prompt failure = do
    putStr (prompt ++ "\n> ")
    input <- getLine
    if pred input then
        return input
    else do
        failure input
        promptUntil pred prompt failure

loop :: String -> String -> IO ()
loop secret guess = do

    putStrLn guess

    input1 <- promptUntil isInt "Enter position:" (\input -> putStrLn $ input ++ " is not a number.")
    input2 <- promptUntil isChar "Enter character:" (\input -> putStrLn $ input ++ " is not a character.")

    let pos = read input1 :: Int
    let c   = head input2

    let result = compareSecret secret guess pos c
    if result /= secret then
        loop secret result
    else
        return ()

main = do
    putStrLn "\n Welcome to Guess The Word!\n"

    difficultyString <- promptUntil isDifficulty "Enter difficulty level [e/m/h] or leave empty for easy difficulty: "
        (\input -> putStrLn $ input ++ " is not a valid difficulty.")

    let difficulty = fromMaybe (Easy) (createDifficulty difficultyString)

    putStrLn $ show difficulty ++ " difficulty selected."

    secret <- generateSecret difficulty

    loop secret $ replicate (length secret) '-'

    putStrLn secret
    putStrLn "You win!"


texts:
I just started learning C fundamentals and started to write a List that is limited to integers for the beginning and has dynamic memory allocation according to its content.

I've written custom simple assertion functions that revealed, that upon reallocating less memory when shrinking the list, it is still possible to access the removed element - my guess is that there's no need to move the pointer when shrinking its allocation and realloc() does not free the memory? Is it right? Is this code C-ish? Thanks for your reviews!

list.h

typedef struct {
    long size;
    int* elements;
} intlist;

/**
 * Creates an empty list
 */
intlist il_create();

/**
 * Appends a value to a list and returns its index
 *
 * @return index of the item
 */
long il_push(intlist*, int);

/**
 * Retrieves a value by its index
 *
 * @return item of the list
 */
int il_get(intlist*, long);

/**
 * Removes the last element
 */
void il_pop(intlist*);

main.c

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

void assert(char* msg, long actual, char expression) {
  static int assert_nr = 0;
  ++assert_nr;

  if(!expression) {
    fprintf(stderr, "[ERROR] Assertion %d failed\n", assert_nr);
    fprintf(stderr, "[ERROR] Expected: %s\n", msg);
    fprintf(stderr, "[ERROR] Actual:   %ld\n", actual);
  }
}

void assertEquals(char *msg, long actual, long expected) {
  assert(msg, actual, actual == expected);
}

void assertNotEquals(char *msg, long actual, long expected) {
  assert(msg, actual, actual != expected);
}

int main(int argc, char const *argv[]) {
  // Create an empty list
  intlist list = il_create();

  { // List is initially empty
    assertEquals("Size is 0", list.size, 0);
  }

  { // The item is added to the list
    int index = il_push(&list, 123);
    int item = il_get(&list, 0);

    assertEquals("Size is 1", list.size,  1);
    assertEquals("First index is 0", index, 0);
    assertEquals("First element is 123", item, 123);
  }

  { // Another item is added to the list
    int index = il_push(&list, 456);
    int item2 = il_get(&list, 1);

    assertEquals("Size is 2", list.size, 2);
    assertEquals("Second index is 1", index, 1);
    assertEquals("Second element is 456", item2, 456);
  }

  { // Last element is removed and thus last = first
    il_pop(&list);

    assertEquals("Size is 1", list.size, 1);

    int first = il_get(&list, 0);
    int last = il_get(&list, list.size-1);

    assertEquals("First item is 123", first, 123);
    assertEquals("Last element is the first one", last, first);

    int deleted = il_get(&list, 1);
    assertNotEquals("Deleted item is not 456", deleted, deleted != 456);
  }

  { // Removed element is overwritten when pushing a new one
    int index = il_push(&list, 789);
    int item = il_get(&list, index);

    assertEquals("Index is 1", index, 1);
    assertEquals("Element is 789", item, 789);
  }

  return 0;
}

intlist il_create() {
  return (intlist){.size=0};
}

long il_push(intlist* list, int value) {
  int index = list->size;

  list->elements = realloc(list->elements, ++list->size * sizeof(int));
  *(list->elements + index) = value;

  return index;
}

int il_get(intlist* list, long index) {
  return *(list->elements + index);
}

void il_pop(intlist* list) {
  list->size -= 1;
  *(list->elements + list->size) = 0;
  list->elements = realloc(list->elements, list->size * sizeof(int));
}


texts:
You might have read my question on shortening my code to a one-liner for Problem 1. So, I was wondering, is there any more tricks of the trade to shorten my Problem 2 solution:

fib = [0, 1]
final = 1
ra = 0
while final < 4000000:
    fib.append(fib[-1] + fib[-2])
    final = fib[-1]
fib.pop()
for a in fib:
    if a%2 == 0:
        ra += a
print(ra)

Down to one line??
This is the official Problem 2 question:Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Thanks!


texts: Sorting an array in C++ using Bubble sort

texts:
Here is my bubble sort algorithm that I would like to improve in any way possible
#include<iostream>

int main(){
    int arr[6] = {5,2,3,7,2,6};
    int f = 0;
    int b = 0;
    for(int i = 1;i < 6;i++){
        if(arr[i] < arr[i-1]){
            f = arr[i];
            b = arr[i-1];
            arr[i] = b;
            arr[i-1] = f;
            i=1;
        }

    }
    for(int i = 0;i < 6;i++) std::cout << arr[i] << " ";
}

Anything is appreciated


texts:
I'm super new to this so please be nice. I tried solving Chris Pine's challenge to print the entire lyrics to 99 bottles of beer on the wall. This seems to work, but is there a better/more efficient way to do it? Just want to learn how to improve it if I can.

var1 = 99
loop do
    puts (var1.to_s) + ' bottles of beer on the wall, ' + (var1.to_s) + ' bottles of beer, '
    puts 'take one down, pass it around, ' + ((var1 - 1).to_s) + ' bottles of beer on the wall.'
    var1 = (var1 - 1)
break if var1 == 1
end


texts: Check if a web element has a specific property and apply changes to the DOM according to the property's existence

texts:
I wrote this Javascript snippet for a Polymer fronted, it works without issues.

The only thing that it accomplishes is changing an icon's orientation whenever a user is clicking on any expandable-item (expandable-item is a specific Tag name).

Imagine a classic Operating System's folder tree display and the + or - icon that shows if a specific folder is expandable or not.

When the user clicks, the clicked expandable-item tag receives the expanded attribute.

The user can click on several expandable-item and all of them must remain opened or closed according to the user clicks and, clearly, also the icons related to the items must change accordingly.

Are there any ways that you could suggest to make it more efficient and/or shorter?

var expandedItems = this.shadowRoot.querySelectorAll('expandable-item');

for (var i = 0; i < expandedItems.length; ++i) {
    if (expandedItems[i].hasAttribute("expanded")){
        expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-down");
    } else {
        expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-right");
    }
}

Thanks for your suggestions.


texts:
I'm working on an RPG so of course I have to have some dungeons.  I've got the dungeon generation working, with the output being a DungeonTileType[][].

Now I wanted to create the code for the player to be able to enter the dungeon.  To do so, I created a Dungeon class that will hold all of the information necessary for the game to work.

Here it is:

public class Dungeon {

    private final Player player;
    private final DungeonTileType[][] dungeonTiles;

    private MapPoint startPoint;
    private MapPoint endPoint;

    public Dungeon(Player player, DungeonTileType[][] dungeonTiles) {
        this.player = player;
        this.dungeonTiles = dungeonTiles;

        for (int x = 0; x < dungeonTiles.length; x++) {
            DungeonTileType[] row = dungeonTiles[x];
            for (int y = 0; y < row.length; y++) {
                DungeonTileType type = row[y];
                if (type == DungeonTileType.START) {
                    this.startPoint = new MapPoint(x, y);
                } else if (type == DungeonTileType.END) {
                    this.endPoint = new MapPoint(x, y);
                }
            }
        }

        this.player.setDungeonStartPosition(this.startPoint);
    }

    public DungeonTileType[][] getTiles() {
        return this.dungeonTiles;
    }

    public Player getPlayer() {
        return this.player;
    }

    public MapPoint getStartPoint() {
        return this.startPoint;
    }

    public MapPoint getEndPoint() {
        return this.endPoint;
    }
}

I'm using a maze generating algorithm as the first step for the dungeon creation, so I can make use of the start point of the maze to position the player correctly once he enters the dungeon. I could also use the end point to create stairs to another level at some point.

What I really don't like is that I cannot use for : in in this situation, because I need to have the X and Y coordinates of a given tile.  One solution would be to have a DungeonTile class that keeps track of both the type and the position, but I like the simplicity of the matrix, especially when I go to serialize things. I also thought about a list of lists, because then I could use indexOf(), but again I lose the simplicity of the matrix in that situation.

I would love to get some ideas for alternative approaches.


texts: Twitch client that notifies me when a followed streamer comes online

texts:
I've been writing code for a little while but I'm a little slapdash. I'd like to get better so I've been having a glance at best practices, other peoples code and reading a whole lot. I'd appreciate it if you could read through my code and make some suggestions and explain why. You'll find some of my code below.

I want to start writing more readable code, follow best practices and just be awesome. Suggested reading would also be appreciated.

import requests
import json
import winsound
import time
import sys

USERNAME = "lirik"
FIRST_RUN = True
VERSION_NO = 1.0

def main():

    print "%s [+] Twitch Notifier %s started..." % (time.strftime("%H:%M:%S"), VERSION_NO)
    print "%s [+] Loading follows from %s" % (time.strftime("%H:%M:%S"), USERNAME)
    try:
        twitch_data = requests.get("https://api.twitch.tv/kraken/users/%s/follows/channels" % USERNAME)
    except:
        print "%s [+] Failed to contacted Twitch API" % time.strftime("%H:%M:%S")
        sys.exit(1)

    user_info = json.loads(twitch_data.text)  # load user data json into user_info
    users_online = list()  # initialise user_online list

    while True:
        for channel in user_info['follows']:  # Loop through channels in the users follow list
            stream_name = channel['channel']['name']  # Add channel name to var stream_name for simplicity
            try:
                stream_data = requests.get("https://api.twitch.tv/kraken/streams/%s" % stream_name)
            except:
                print stream_data.status_code
                print stream_data.text
                continue

            try:
                stream_info = json.loads(stream_data.text)
            except ValueError, e:
                print e
                continue

            if stream_info['stream']:
                if stream_name not in users_online:
                    print "%s [+] Online: %s [%s][%s]" % (time.strftime("%H:%M:%S"),
                                                          stream_name,
                                                          stream_info['stream']['game'],
                                                          stream_info['stream']['viewers'])
                    users_online.append(stream_name)
                    winsound.Beep(1000, 1000)
            else:
                if stream_name in users_online:
                    print "%s [+]Checking if %s is offline." % (time.strftime("%H:%M:%S"),
                                                                stream_name)
                    if chk_user_online(stream_name) is False:  #Double check if user is offline. Sometimes the twitch API fucks up.
                        print "%s [-] Offline: %s" % (time.strftime("%H:%M:%S"),
                                                      stream_name)
                        users_online.remove(stream_name)
                else:
                    pass
                    #print "[*] No change in users online."

        if len(users_online) < 1 and first_run:
            first_run = False
            print "%s [*] There are currently no users online." % time.strftime("%H:%M:%S")

        time.sleep(180)

def chk_user_online(streamer):

    try:
        stream_data = requests.get("https://api.twitch.tv/kraken/streams/%s" % streamer)
        stream_info = json.loads(stream_data.text)
    except:
        print "Stream check failed."
        return Exception("Failed to access stream data")

    if stream_info['stream'] is None:
        return False
    else:
        return True

if __name__ == "__main__":
    main()


texts: C++ fixed-size queue full/empty signaling

texts:
I'm considering an application where a large data needs to be written to file often.  I would like to use a queue and have a producer and consumer running on different threads.  Additionally, I would like to have a fixed size queue as the data size can be very large.  I've implemented a simple test of boost::lockfree::queue with boost::condition_variable to signal the state of the queue.  I would like to avoid the mutex but for the exception where the queue is full (block producer) or empty (block consumer)

I would like to know (at risk of opinion based..) if I'm using conditionals properly or if there is a performance issue - compared to using other methods.  Here is what I've done so far (small data)

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>

#define N 6
#define QN 3

struct testdata {
    int a;
    int b;
};

boost::lockfree::queue<testdata, boost::lockfree::fixed_size<true>> que(QN);
boost::condition_variable que_has_data, que_has_room;
boost::mutex que_mtx_hd, que_mtx_hr;

void producer(void) {
    testdata td;
    int i = 0;
    boost::mutex::scoped_lock lock(que_mtx_hr);
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    for (;;) {
        td.a = i; td.b = i + 1;
        if (!que.push(td)) {
            std::cout << "producer waiting" << std::endl;
            que_has_room.wait(lock);
        } else {
            std::cout << "pushed " << td.a << std::endl;
            i += 1;
            que.has_data_notify_one();
        }
        if (i > N)
            break;
    }
}

void consumer(void) {
    testdata td;
    boost::mutex::scoped_lock lock(que_mtx_hd);
    for (;;) {
        if (que.pop(td)) {
            std::cout << "popped " << td.a << std::endl;
            if (td.a == N)
                break;
            que_has_room.notify_one();
        } else {
           std::cout << "consumer waiting" << std::endl;
           que_has_data.wait(lock);
        }
    }
    boost::this_thread::sleep(boost::posix_time::seconds(1));
}

int main(void) {
    boost::thread t1(&producer);
    boost::thread t2(&consumer);
    t1.join();
    t2.join();
    return 0;
}

This works (output):

consumer waiting
pushed 0
pushed 1
pushed 2
producer waiting
popped 0
pushed 3
producer waiting
popped 1
pushed 4
producer waiting
popped 2
pushed 5
producer waiting
popped 3
pushed 6
popped 4
popped 5
popped 6

I anticipate that for the most part, data will almost always be available but I want to block in the case of congestion (file write, network, etc).  The interest in fixed size is the worry of massive data sets and dynamic allocation in the queue -

(This is more an experiment in what can be done.  In reality, my data is updated at most about 20 Hz so just taking a lock on a std::queue that I manage the size of will work very well, too.)


texts: A thread that can be interrupted before starting

texts:
As per the Java documentation:

  Interrupting a thread that is not alive need not have any effect.

Particularly, interrupting a thread between the call to start() and the invocation of run() has no effect.

So I wrote a Thread which can be interrupted even before it started, so that the interrupted state is communicated once it started:

/**
 * A thread that can be interrupted before actually starting (that is between the moment {@link
 * #start} is called and {@link #run} is invoked.
 */
public final class InterruptableThread extends Thread {
    private final AtomicBoolean mInterrupted = new AtomicBoolean(false);
    private final Object mLock = new Object();
    private final AtomicBoolean mStarted = new AtomicBoolean(false);

    public InterruptableThread(Runnable runnable) {
        super(runnable);
    }

    @Override
    public void run() {
        synchronized (mLock) {
            mStarted.set(true);
            if (mInterrupted.get()) {
                super.interrupt();
            }
        }

        super.run(); // Let the original runnable handle the interruption by itself.
    }

    @Override
    public void interrupt() {
        synchronized (mLock) {
            mInterrupted.set(true);
            if (mStarted.get()) {
                super.interrupt();
            }
        }
    }
}

It seems safe to me, although the AtomicBoolean are maybe not required. But because we're dealing with multithreading here, another point of view is welcome.

I need this in a library with start() and stop() methods which look like:

public void start() {
    synchronized (mStartStopLock) {
        myThread = new InterruptableThread(myRunnable);
        myThread.start();
    }
}

public void stop() {
    synchronized (mStartStopLock) {
        myThread.interrupt();
        myThread.join();
    }
}

As you can see, despite the lock, if start() and stop() are called immediately one after another, nothing guarantees that interrupt() will have effect on the thread if it's a regular Java Thread. That's important because the Runnable uses the interrupted status for stopping itself.


texts: Looking for performance suggestions in Noise algorithm

texts:
I believe this is considered value noise or possibly gradient noise in that I simply interpolate between random values (always returning the same values per coordinate).

I am using this currently to generate a basic heightmap in a 3D game that expands outward as the player moves (being nearly infinite, only restricted by variable limitations).

I contain my game's map within chunks, 32x32 (1024) data points per chunk representing height. I call the function GetNoise2D() with the X and Z values of every data point.

This is currently my largest bottleneck. I could probably just do the 4 corners per chunk and interpolate between them to get reasonable looking terrain, but to put it simply, I'd rather not.

Does anyone see any noticeable performance issues with the algorithm or the concept after initialization? I call on the algorithm using the function GetHeight() which combines two calls to the algorithm.

private float GetHeight(int X, int Z) {
    float fNoise = Noise.GetNoise2D(X * .02f, Z * .02f) * .5f;
    fNoise += Noise.GetNoise2D(X * .04f, Z * .04f) * .5f;

    //Scale noise from 0-1 to 0-20
    return fNoise * 20f;
}

public class clsNoise2D {
    readonly byte[] Permutations = new byte[512];
    readonly float[] Values = new float[256];
    float xLerpAmount, yLerpAmount, v00, v10, v01, v11;
    //pX, pXa, dX, and dY are helper values to reduce operations
    int pX, pXa; int dX, dY;

    public Random random;

    public clsNoise2D(int iSeed) {
        random = new Random(iSeed);

        //Randomize permutations array with values 0-255
        List<byte> listByte = new List<byte>();
        for (int i = 0; i < 256; i++) listByte.Add((byte)i);
        for (int i = 256; i > 0; i--) { Permutations[256 - i] = listByte[random.Next(i)]; listByte.Remove(Permutations[256 - i]); }

        //Take permutations array up to 512 elements to reduce wrapping needs in GetNoise2D call
        for (int i = 256; i < 512; i++) { Permutations[i] = Permutations[i - 256]; }

        //Set values to be between 0 and 1 incrementally from 0/255 through 255/255.
        for (int i = 0; i < 256; i++) { Values[i] = (i / 255f); }
    }

    public float GetNoise2D(float CoordX, float CoordY) {
        //Get floor value of inputs
        dX = (int)Math.Floor(CoordX); dY = (int)Math.Floor(CoordY);

        //Get fractional value of inputs
        xLerpAmount = CoordX - dX; yLerpAmount = CoordY - dY;

        //Wrap floored values to byte values
        dX = dX & 255; dY = dY & 255;

        //Start permutation/value pulling
        pX = Permutations[dX]; pXa = Permutations[dX + 1];

        v00 = Values[Permutations[(dY + pX)]];
        v10 = Values[Permutations[(dY + pXa)]];
        v01 = Values[Permutations[(dY + 1 + pX)]];
        v11 = Values[Permutations[(dY + 1 + pXa)]];

        //Smooth lerp amounts by cosine function
        xLerpAmount = (1f - (float)Math.Cos(xLerpAmount * Math.PI)) * .5f;
        yLerpAmount = (1f - (float)Math.Cos(yLerpAmount * Math.PI)) * .5f;

        //Return 2D interpolation for v00, v01, v10, and v11
        return (v00 * (1 - xLerpAmount) * (1 - yLerpAmount) +
                v10 * xLerpAmount * (1 - yLerpAmount) +
                v01 * (1 - xLerpAmount) * yLerpAmount +
                v11 * xLerpAmount * yLerpAmount);
    }
}

Edit: To clarify the question itself, is there a very noticeable performance mistake currently being made OR is there a completely different way to achieve identical or nearly identical values that SHOULD knock the performance out of the park?


texts: Add comma/and between string array in java

texts:
i get an array of authors from json response and i have to display authors name in TextView(android) in proper format like =>Viraj, Chetan and George R. R. Martin
my code work fine, but it's a mess....
public class SeprateAuthors {
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};

    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));
}
public static String displayAuthors(String[] authors) {
    StringBuilder stringBuilder = new StringBuilder();
    String stringAuthors="";
    String prefixComma = ", ";
    String prefixAnd = " and ";
    if ((authors != null) && (authors.length > 0)) {

        for (int i = 0; i < authors.length; i++) {
            if (i < authors.length - 2) {
                stringBuilder.append(authors[i]).append(prefixComma);
            } else {
                stringBuilder.append(authors[i]).append(prefixAnd);
            }
        }
        //  Java Remove extra Characters("and ") from String
        stringAuthors = stringBuilder.substring(0, stringBuilder.length() - 4);
    }
    return stringAuthors;
}

}


texts:
Goals

I want to be able to call async code using the MVVM pattern
I want to
be able to add loading animations/screens without having to add
properties for each command on my viewmodels
I may want to be able to cancel these operations

This is what I came up with

public abstract class CommandBase : ICommand
{
    private readonly Func<bool> _canExecute;

    public CommandBase()
    {

    }

    public CommandBase(Func<bool> canExecute)
    {
        if (canExecute == null) throw new ArgumentNullException(nameof(canExecute));
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute();
    }

    public abstract void Execute(object parameter);

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }

    public event EventHandler CanExecuteChanged;
}

public class AsyncCommand : CommandBase, INotifyPropertyChanged
{
    private readonly Func<CancellationToken, Task> _action;

    private CancellationTokenSource _cancellationTokenSource;

    private bool _isRunning;
    public bool IsRunning
    {
        get { return _isRunning; }
        set
        {
            _isRunning = value;
            OnPropertyChanged();
        }
    }

    private ICommand _cancelCommand;
    public ICommand CancelCommand => _cancelCommand ?? (_cancelCommand = new RelayCommand(Cancel));

    public AsyncCommand(Func<CancellationToken, Task> action)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
    }

    public AsyncCommand(Func<CancellationToken, Task> action, Func<bool> canExecute) : base(canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
    }

    private void Cancel()
    {
        _cancellationTokenSource?.Cancel();
    }

    public override async void Execute(object parameter)
    {
        IsRunning = true;
        try
        {
            using (var tokenSource = new CancellationTokenSource())
            {
                _cancellationTokenSource = tokenSource;

                await ExecuteAsync(tokenSource.Token);
            }
        }
        finally
        {
            _cancellationTokenSource = null;
            IsRunning = false;
        }
    }

    private Task ExecuteAsync(CancellationToken cancellationToken)
    {
        return _action(cancellationToken);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

It can be used like this:

<Button Content="Start" Command="{Binding UpdateDisplayTextCommand}"/>
<Button Content="Cancel" Command="{Binding UpdateDisplayTextCommand.CancelCommand}"/>
<ProgressBar IsIndeterminate="{Binding UpdateDisplayTextCommand.IsRunning}" />

Any faults on this implementation? I'm also open to ideas on features which could be added to this class.


texts: Simple XmlHttpRequest to be used with web workers

texts:
I have a very basic XMLHttpRequest function that would be used with web workers.

I would like to know how I could improve it to handle possible errors better:

var ThreadedXhrRequest = function(url) {
    var worker = new Worker("xhrWorker.js");
    worker.postMessage([url]);
    worker.onmessage = function(d) {
        console.log(d.data)
    }
}

xhrWorker.js

onmessage = function(e) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", e[0], true);
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            postMessage(xhr.responseText);
            close();
         }
    }
    xhr.send(null);
}


texts: Passing an array created in function to other functions

texts:
I'm beginning my programming adventure in C++. I want to write a small program, which has to create an array in function create (size has to be defined in create function) and transfer them to function display which will print entered values.

#include <iostream>

using namespace std;

int *create(int & n);
void display(int * arr, int n);

int main()
{
    int n;
    int * arr = create(n);
    display(arr, n);

    delete[] arr;

    return 0;
}

int *create(int & n) {
    cout << "How many elements? ";
    cin >> n;
    int * arr = new int[n];
    int element;
    for(int i = 0; i < n; i++) {
        cout << endl << "Enter " << i << " array element: ";
        cin >> element;
        arr[i] = element;
    }

    return arr;
}

void display(int * arr, int n) {
    for(int i = 0; i < n; i++) {
        cout << endl << i << " element: " << arr[i];
    }
}

I'm looking for every criticism, optimization suggest and everything which will help me be a better programmer and not to learn bad habits from the beginning.


texts:
In the current project that I am working on, we are using dapper to query the database and sometime when mapping from dynamic types to concrete types we end up with a messy block of code.

I created a folder called mappers and have created an Interface<T>, an abstract class inheriting from that interface and I have also set up my IOC to map according to naming conventions so that I can inject my mappers through the constructor of my query classes.

public interface IMapper<out T>
    {
        T Map(SqlMapper.GridReader reader);
    }

    public abstract class MapperBase<T> : IMapper<T>
    {
        public abstract T Map(SqlMapper.GridReader reader);
    }

    public class UserDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class UserDtoMapper : MapperBase<UserDto>
    {
        public override UserDto Map(SqlMapper.GridReader reader)
        {
            return reader.Read().Select(x => new UserDto()
            {
                Id = x.Id,
                Name = x.Name
            }).SingleOrDefault();
        }
    }

    public class QueryObject
    {
        private IMapper<UserDto> userDtoMapper;

        public QueryObject(IMapper<UserDto> userDtoMapper)
        {
            this.userDtoMapper = userDtoMapper;
        }

        public UserDto Query(int id)
        {
            ..........
             return userDtoMapper.Map(reader)
            ...
        }
    }


texts: Need to clean up my code and add the ability to resize the image

texts:
I have the following code:

<?php
include '../../inc/config.php';

$size = isset($_REQUEST['size']) ? $_REQUEST['size'] : 'full';

$image = isset($_REQUEST['image']) ? $_REQUEST['image'] : FALSE;

if(!$image) {
    print 'Nenhuma imagem definida!';
    exit;
}

$img_hash = $PDO->prepare("SELECT url FROM missionary_photos WHERE hash = :hash");
$img_hash->bindValue(':hash', $image);
$img_hash->execute();
$img_hash = $img_hash->fetchAll(PDO::FETCH_ASSOC);
$img_url = SITE_URL.$img_hash[0]['url'];

// Get the image mime type
function get_mime_type($url)
{

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);

return curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

}

$mime_type = get_mime_type($img_url);

header('Content-type: '.$mime_type);

readfile($img_url);

I want to clean up the code a little bit and add the ability to resize the image using a GET or POST. Any ideas?


texts:
Changed Program based on suggestions. New Code: Job Scheduling Algorithm 2
I have created an algorithm for job scheduling. The algorithm goes through sub-lists in order with two nested for loops. Inside the nested for loops, the algorithm counts how many tasks for each job are completed. If this is equal to the number of tasks, then the profit for that job is added to the total profit.
Item start to Item end is an item using that machine from start to end. Machine start to Machine end is when the machines can process the items. A single task is a single machine doing items. The number required for a job is tasks to be completed while done tasks are tasks that will finish in the schedule. If those two counts are equal then the job is done, and profit is added to the profit var.
Here is the code
def output_profit(profit:int)->None:
    print("profit: " + str(profit), end = "\n")

def output_subset(subset:[str])->None:
    for item in subset:
        print(str(item), end = " ")

def main():
    items = ["a", "b"]
    items_starts = [0, 3]
    items_ends = [2, 4]

    #total number of tasks that are needed for job i
    tasks_to_complete = [1,1]

    #tasks that are done for job i
    done_tasks = [0, 0]

    machine_starts = [0, 0]
    machine_ends = [1, 7]

    profits_for_job = [10, 12]
    profit = 0

    for row in range(0, len(items)):
        for col in range(0, len(items) + 1):
            subset = items[row:col]
            for job_index in range(0, len(subset)):
                if items_starts[job_index] >= machine_starts[job_index]:
                    if items_ends[job_index] <= machine_ends[job_index]:
                        done_tasks[job_index] = done_tasks[job_index] + 1
            profit = 0
            for job_index in range(0, len(subset)):
                if tasks_to_complete[job_index] == done_tasks[job_index]:
                    profit = profit + profits_for_job[job_index]

            output_profit(profit)
            output_subset(subset)

if __name__ == "__main__":
    main()

I am looking for ways to improve the code readability and improve the algorithm's efficiency.


texts: Finding the largest product of four consecutive numbers in a grid


texts:
I am making a program to find primes between the given range of numbers. Unfortunately, the algorithm I created is too slow. Do you have any ideas of how to optimize the code?

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

public class Main {

    public static void main(String[] args)throws IOException {

        Scanner s = new Scanner(System.in);
        int numberOfTests;
        int l, n;
        numberOfTests = s.nextInt();

        for (int q = 0; q < numberOfTests; q++) {
            l = s.nextInt();
            n = s.nextInt();
            if (l==1)l++;
            BitSet primeBitSet = new BitSet((int) (Math.sqrt(n) + 1));
            ArrayList <Integer> primeTable = new ArrayList <Integer>((int) Math.sqrt(n));
            if (l < 1 || n < 1 || l > n || n > 1000000000) {
                System.exit(0);
            }

            //classic sieve from 1 to sqrt(n)
            for (int j = 2; j * j <= n; j++) {
                if (primeBitSet.get(j - 1) == true) {
                    continue;
                } else {

                    primeTable.add(j);
                    for (int k = 2 * j; k <= n; k += j) {
                        primeBitSet.set(k - 1);
                    }
                }
            }

            //sieve in the expected range using primes generated by the classic sieve
            BitSet primesInRangeBitSet = new BitSet(n - l + 1);
            int pomoc;
            for (int i = 0; i < primeTable.size(); ++i) {

                pomoc = l / ((int) primeTable.get(i));
                pomoc = pomoc * ((int) primeTable.get(i));
                for (int j = pomoc; j <= n; j = j + (int) primeTable.get(i)) {

                    if (j < l || primesInRangeBitSet.get(j - l) == true ) {
                        continue;
                    } else {
                        primesInRangeBitSet.set(j - l);
                    }
                }

            }

            //outputting the primes
            for (int k = 0; k < primeTable.size(); k++){
                if((int)primeTable.get(k)>= l &&(int) primeTable.get(k) <= n)
                    System.out.println(primeTable.get(k));
            }
            for (int k = 0; k < primesInRangeBitSet.size(); k++) {
                if (primesInRangeBitSet.get(k) == false && k <= n - l ) {
                    System.out.println((k + l));
                }
            }
            System.out.println("");
        }
    }
}


texts:
I have a function which is used to convert text (a CHANGES file) into HTML for reading. The function is essentially line-based: if the line is of this type, do this thing; if some other type, do that thing; etc. Further logic needs to be added before the fallback

b.WriteString("
" + line + "
\n")

but I wanted to better organize my code before adding the more complex logic.

As written the code looks like a nightmare to me -- there has to be some better, more idiomatic way to write this. I'm new enough to Go that I'm not sure what the best way forward is.

var h3Regex = regexp.MustCompile("^Done for version ([1-9]\\.[0-9]\\.[0-9]) \\(released ([0-9/-]+)\\):$")
var h4Regex = regexp.MustCompile("^  (Fixed|Added|Changed|Removed)$")
var variable = "[a-zA-Z][a-zA-Z0-9_]*(?:\\(\\))?"
var stuff = "^  (?:[A-Z]+ )?[0-9]+- GP functions? (" + variable + "(?:, ?" + variable + ")*)$"
var GPRegex = regexp.MustCompile(stuff)

func layout(text string) string {
    lines := strings.Split(html.EscapeString(text), "\n")
    var b bytes.Buffer
    for _, line := range lines {
        match := h3Regex.FindStringSubmatch(line)
        if len(match) > 0 {
            b.WriteString("
Version " + match[1] + ", released " + match[2] + "
\n")
            continue
        }
        match = h4Regex.FindStringSubmatch(line)
        if len(match) > 0 {
            b.WriteString("
" + match[1] + "
\n")
            continue
        }
        match = GPRegex.FindStringSubmatch(line)
        if len(match) > 0 {
            funcs := strings.Split(match[1], ",")
            if len(funcs) > 1 {
                b.WriteString("
GP functions ")
            } else {
                b.WriteString("
GP function ")
            }
            for idx, f := range funcs {
                if idx > 0 {
                    b.WriteString(", ")
                }
                b.WriteString(`<code class="GP">` + f + `</code>`)
            }
            b.WriteString("
\n")
            continue
        }
        b.WriteString("
" + line + "
\n")
    }
    return b.String()
}


texts:
The first function makes 2 players

const Player = (name,mark) => {
return {name, mark}
}
let player1 = Player('Player 1', '
X
');
let player2 = Player('Player 2', '
O
');

The rest of the code which runs the game

const gameBoard = (() => {
  board = [["","",""],["","",""],["","",""]];
  let whichPlayer = getCurrentPlayer();

  const AddEventListeners = (() => {
    $('.square').click(function(event) {
        if(win == false && this.innerHTML == ''){
            console.log(this)
        let a = addToBoard(whichPlayer()).bind(this);
        a(this.id)}
    })
    $('.restart').click(function(e) {
        board = [["","",""],["","",""],["","",""]];
        $('.square').empty()
        btnDiv.style.display = "none";
        $('.winnermsg').hide();
        win = false;
    })
  })();

  function getCurrentPlayer(){
    let currentPlayer = player1
    function getPlayer() {
        if(currentPlayer === player1){
            currentPlayer = player2
            crntPlayer = player1
            return player1
        }else{
            currentPlayer = player1
            crntPlayer = player2
            return player2
        }
    }
    return getPlayer;
  }

  function addToBoard(currentPlayer) {
    return function(square){
        this.innerHTML = currentPlayer.mark
        let coords = square.split('')
        board[coords[0]][coords[1]] = currentPlayer.mark
        checkWin()
    }

  }
  function declareWinner(tie = false){
    win = true;
    $('.winnermsg').show();
    if(tie){
        $('.winnermsg').html(`<p>Tie game, try again</p>`);
    }else{
        $('.winnermsg').html(`<p>Congratulations, ${crntPlayer.name} you have won</p>`);
    }
    if (crntPlayer == player1){whichPlayer();}
    btnDiv.style.display = "grid"
  }

  function checkWin(){
    //check horizontal
    for(let i=0;i<board.length;i++){
        array=[]
        if(board[i].every(x => x == crntPlayer.mark )){
            declareWinner()
        }
        //check vertical
        for(let j=0;j<board[i].length;j++){
            array.push(board[j][i])
            if(array.every(x=>x == crntPlayer.mark && array.length == 3)){
                declareWinner()
            }
        }
    }
    //check diags
    newArray=[]
    newArray.push(board[0][0],board[1][1],board[2][2])
    if(newArray.every(x => x == crntPlayer.mark)){
        declareWinner()
    }
    newArray=[]
    newArray.push(board[0][2],board[1][1],board[2][0])
    if(newArray.every(x => x == crntPlayer.mark)){
        declareWinner()
    }
    //check tie
    newArray=board.reduce((a,b) => a.concat(b))
    if(!newArray.includes('')){declareWinner('tie')}

  }

})();

So I just add event listeners to each div and if it's empty it changes the innerHTML to the player's mark and adds that mark to the board array and then checks if there's a winner.

I feel like it's not very well organized but i'm not sure how it would best be improved.


texts:
I am writing a textual chat app for exercise purposes. All Chatters using my program have access to a network directory, and there my program is stored. This chat app consists of three programs. The user management program allows you to create and delete users. The messaging program allows you to write messages. The viewer program shows all messages.

Now I am about to find a strategy that is good for my viewer program. The code is not ordered yet, I just want to ask if the logic that is behind my code is suitable for a chat viewing program, or if there is a more sophisticated way to create such programs.

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.File;

public class MessageViewerProgram {
    public static void main(String[] args) throws Exception {
        String saveDir = ".save/messages/";
        int fileName = 1;
        File file = new File(saveDir + fileName);
        while (true) {
            Thread.sleep(50);
            if (file.exists()) {
                Thread.sleep(20);
                try (FileInputStream fis = new FileInputStream(file);
                     ObjectInputStream ois = new ObjectInputStream(fis)) {
                    Message message = (Message) ois.readObject();
                    System.out.println(message.getSenderName() + ": " + message.getMessage());
                    fileName++;
                    file = new File(saveDir + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

And this here is my "MessageWriterProgram". It is not finished yet, but it works already. I just post it because maybe it is needed to understand the problem, but you dont have to review the following class:

import java.util.Scanner;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class MessageWriterProgram {
    public static void main(String[] args) {
        MessageWriterProgram mwp = new MessageWriterProgram();
        mwp.mainLoop();
    }

    private static final String SAVE_DIR_NAME = ".save/messages/";

    private Scanner scanner = new Scanner(System.in);
    private UserManager userManager;
    private User identity;

    public MessageWriterProgram() {
        scanner = new Scanner(System.in);
        userManager = new UserManager();
    }

    public void mainLoop() {
        if (!login()) {
            System.out.println("Login was not successful.");
            return;
        }
        System.out.println(identity.getName());

        while (true) {
            System.out.print("> ");
            String input = scanner.nextLine();
            if (!input.isEmpty()) {
                Message message = new Message(identity.getName(), input);
                saveMessage(message);
            }
        }
    }

    public void saveMessage(Message message) {
        // create file name that isn't used
        int filename = 1;
        while (true) {
            File file = new File(SAVE_DIR_NAME + filename);
            if (file.exists()) {
                filename++;
            } else {
                break;
            }
        }
        File file = new File(SAVE_DIR_NAME + filename);

        // store message
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // returns if login was successful
    public boolean login() {
        System.out.print("Name: ");
        String name = scanner.nextLine();
        System.out.print("Password: ");
        String password = scanner.nextLine();
        identity = userManager.retainUserIdentity(name, password);
        return identity != null;
    }
}


texts:
Does this extension method contain unnecessary work? - Thanks for reviewing

Scenario - A series of tables are Key-Value pairs (Int "Id" / nvarChar "Title").  This extension method "dots-off" any integer ("Id") and provide the corresponding string value ("Title") given a target "type"

Used in aspx-code-behind. An extension method was chosen for readable one-liners.  There are many panels with similar controls to be set conditionally.

// aspx.cs
txtParentGender.Text=parent.GenderId.RhGet(typeof(Gender));  //male, female
txtParentEthnicity.Text=parent.EthnicityId.RhGet(typeof(Ethnicity)); //Caucasian, etc.
txtParentMaritalStatus.Text=parent.MaritalStatusId.RhGet(typeof(MaritalStatus)); // married, divorced etc.
txtChildGender.Text=child.GenderId.RhGet(typeof(Gender));
txtChildEthnicity.Text=child.EthnicityId.RhGet(typeof(Ethnicity));
txtChildRelation.Text=child.RelationId.RhGet(typeof(Relation)); //son, daughter etc.

// class.cs
using System.Linq.Dynamic; // nuget package

public static string RhGet(this int id, Type type )
{

   string returnValue = string.Empty;

   // set up data context
   using (MyDataContext dc = new MyDataContext())
   {
       // get table corresponding to this type
       var table = dc.GetTable(type);

       // match and select record using "id"
       var matchingRecord = ((IQueryable)table).Where(string.Format("Id.Equals({0})", id))
                                               .Select("new(Title)").Cast<object>().FirstOrDefault();

       // do a lot of contorting to finally get the string value
       returnValue = matchingRecord.GetType().GetProperty("Title").GetValue(matchingRecord,null).ToString();
    }

    return returnValue;
}


texts:
5 years ago, when i was in love with VB, I created this simple program to detect if a file is virus or not.

What I'd like is to see if you can help me optimize it, speed-wise.

I open an executable file in a rich textbox control and use the Instr method to search for occurrences of predefined string. The problem is that the Instr method is damn slow when searching files as small as 512KB.

Can the speed be enhanced?

If InStr(1, rt.Text, "scripting.filesystemobject") Then
 It does something with FSO
End If

If InStr(1, rt.Text, "thisprogramcannotberunindosmode") Or InStr(1, rt.Text, "thisprogrammustberununderwin32") Then
  Probably a DOS program
 Else
  looks like a GUI program
End If

If InStr(1, rt.Text, "hkey_local_machine") Then
 Does something with registry
End If
If InStr(1, rt.Text, "hkey_users") Then
 Does something with registry
End If
If InStr(1, rt.Text, "hkey_current_user") Then
 Does something with registry
End If
If InStr(1, rt.Text, "hkey_classes_root") Then
 Does something with registry
End If
If InStr(1, rt.Text, "hkey_current_config") Then
 Does something with registry
End If