texts: Check the security of my image upload script

texts:
I am writing a basic image upload script in PHP, and am looking for critiques. The script below is the result of various suggestions I have found online... for now I am running it locally and it works fine, but I would love for someone more experienced to look over it.

Is this secure? Poorly implemented? Too redundant? Not redundant enough? What am I missing and/or doing incorrectly? Any suggestions/help/advice is GREATLY appreciated. Thank you.

PHP:

if (isset($_FILES['image']))
{
    $files_array = $_FILES['image'];
    $num_of_image_uploads = count($files_array['name']);

    // Loop through array of file uploads
    for ($i = 0; $i < $num_of_image_uploads; $i++)
    {
        // Check if there is a file to upload
        // If so -> define, validate, and upload
        if ($files_array['tmp_name'][$i] != "")
        {
            $errors = false;    // Flag for errors
            $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');

            $file_name = $files_array['name'][$i];
            $file_ext = strtolower(end(explode('.', $file_name)));
            $file_size = $files_array['size'][$i];
            $file_tmp = $files_array['tmp_name'][$i];

            // Extension check 1
            if (in_array($file_ext, $allowed_ext) === false)
            {
                echo "Extension not allowed.
";
                $errors = true;
            }

            // Extension check 2 - if file is not empty
            if ($file_size == 0)
            {
                echo "File is empty.
";
                $errors = true;
            }
            else if (!getimagesize($file_tmp))
            {
                echo "Not an image.
";
                $errors = true;
            }

            // Extension check 3
            $blacklist = array(".php", ".phtml", ".php3", ".php4");
            foreach ($blacklist as $item)
            {
                if(preg_match("/$item\$/i", $file_name))
                {
                    echo "File not allowed.
";
                    $errors = true;
                }
            }

            // File size check
            if ($file_size > 4718592)
            {
                echo "File size must be under 4.5MB.
";
                $errors = true;
            }

            // Rename file
            $file_name = preg_replace("/[^A-Z0-9_]/i", "_", $file_name);
            $file_name = md5($i.$file_name.time());

            // Insert if no errors
            if ($errors == false)
            {
                if (move_uploaded_file($file_tmp, 'uploads/'.$file_name.'.'.$file_ext))
                {
                    echo "Success! File uploaded.
";
                }
            }
        }
    }
}

HTML:

  <form enctype="multipart/form-data" action="" method="post">

    <input name="image[]" type="file" />
    <input name="image[]" type="file" />
    <input name="image[]" type="file" />
    <input name="image[]" type="file" />

    <input type="submit" value="Upload" />

  </form>


texts: Determining function return types for std::function

texts:
I'm using the boost::units library (boost::units) and trying to make use of auto and decltype to deal with all the complicated types it produces.

I have a templated function to integrate a mathematical function (which might accept x values with units such as 1*metre) between two points:

template <class Out, class In >
auto integrate( std::function<Out(In)> const & f,
In xmin, In xmax, int nSteps)
-> decltype( f(xmin)  * xmin  )

Now I want to use this with some functions that have big ugly return types. I have written this:

//Standard quantities
quantity<temperature> stdBlackBodyTemp = 2857.0*kelvin;
auto luminousEfficiency = quantity<luminous_flux>(682.0*lumen) / quantity<power>(1.0 * watt);

//Integration range
quantity<length> minWavelength(150.0 * nano * metre);
quantity<length> maxWavelength(600.0 * nano * metre);

//Get type for spectral_differential_current
quantity<length> fakeLength(300.0 * nano * metre);

typedef decltype(pmt_radiant_sensitivity(fakeLength)
        * plancklaw(fakeLength, stdBlackBodyTemp)) sdctype;

//Define spectral_different_current function
std::function< sdctype(quantity<length>)>
    spectral_differential_current = [&stdBlackBodyTemp](quantity<length> l)
    {
        return
            pmt_radiant_sensitivity(l) * plancklaw(l, stdBlackBodyTemp );
    };

//Integrate over spectral_differential_current
auto differential_current = integrate( spectral_differential_current,
        minWavelength, maxWavelength, 100);

To define my std::function spectral_differential_current which I'm going to give to integrate I need to know the return type. The only way I have found to get this is by using the function on some random value (fakeLength) and then using decltype. It seems odd that I have to introduce a variable which isn't actually used just to get a type. Is there a better way of approaching this?


texts: Remove Duplicates from Array in Swift 3.0

texts:
I ran the following code through a Leetcode.com challenge and it says the runtime for the test cases is 119ms, which puts it at the back of the pack performance wise.

The goal is to remove duplicates from a sorted array of Ints and return the count of the array without dups.

func removeDuplicates(_ nums: inout [Int]) -> Int {
    nums = Array(Set(nums)).sorted()
    return nums.count
}

I thought my solution was pretty simple, but 119ms isn't so hot compared with the average of ~60-70ms. Is there a better way to do this?


texts: Measure distance using echo signal from Ultrasonic sensor

texts:
I was not happy with original code for Ultrasonic sensor and decided to write my own implementation.

I managed to do this, but it still looks weird. Could you help me to improve it?

#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>

#define Trig    0
#define Echo    1

double raw_ultrasonic_measure(int trig, int echo) {
  digitalWrite(Trig, LOW);
  delayMicroseconds(1);

  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);

  while(!(digitalRead(Echo) == 1));
  int time1 = micros();

  while(!(digitalRead(Echo) == 0));
  int time2 = micros();
  return (double)(time2 - time1) / 100;
}

double ultrasonic_measure(int trig, int echo) {
  double value1 = raw_ultrasonic_measure(trig, echo);
  delay(1);
  double value2 = raw_ultrasonic_measure(trig, echo);
  delay(1);
  double value3 = raw_ultrasonic_measure(trig, echo);
  delay(1);
  double value4 = raw_ultrasonic_measure(trig, echo);
  delay(1);
  double value5 = raw_ultrasonic_measure(trig, echo);
  return (value1 + value2 + value3 + value4 + value5) / 5;
}

int main(void) {
  wiringPiSetup();
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);

  while(1){
    double value = raw_ultrasonic_measure(Trig, Echo);
    printf("%0.1f cm\n", value);
    delay(1000);
  }

  return 0;
}


texts: Keep the sequential nature while updating the UI of the progress of the HTTP request

texts:
Let's say that I have a method that makes an HTTP request that will take a long time to finish. While that's happening the UI is not updating because I'm doing it in the UI's thread.

One solution is to:

Show the "Loading" animation.
Start the HTTP request on a thread.
On the completion callback stop the "Loading" animation and work on the response.

That's all nice and good, but it means that I went from code that was sequential in nature to something that has callbacks or something similar (promises).

So, I'm trying to keep the sequential nature while updating the UI. Having something like await/async would help here, but even in that case the caller has to be aware of this (plus I need .NET 4.5, let's assume that this is not an option). So I came up with something that keep the sequential nature of the original call, doesn't affect the caller of the function makes the HTTP request but updates the UI.

So, here it is:

public class Async<T>
{
    public static T Run(Func<T> action)
    {
        var worker = new BackgroundWorker();
        var error = new Exception[] {null};
        var result = new[] {default(T)};

        // The original call will run in a separate thread.
        worker.DoWork += (sender, ea) => { result[0] = action(); };
        worker.RunWorkerCompleted += (sender, ea) => { error[0] = ea.Error; };
        worker.RunWorkerAsync();

        // While the work is being done in a separate thread, update the UI's event loop (is this safe???)
        while (worker.IsBusy)
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
            Thread.Sleep(20);
        }
        // Re raise the exception if needed
        if (error[0] != null)
            throw error[0];

        return result[0];
    }
}

//Usage
var someVariable = 123;
var responseA = Async<T>.Run(DoSuperLongTask);
var responseB = Async<T>.Run(() =>
                    {
                        return DoSuperComplicatedTask(someVariable);
                    });

It'll be something like

await Task.Run(() => DoWork());
await Task.Run(() => DoWork());

I'm not an expert in GUIs, and I'm especially not an expert in WPF. So my question to you is:

Is this safe to use?

So far it seems to work okay.


texts:
I am working on an app where I have to calculate the age of a person.  Inside of my age class I have a function that is designed to account for leap year.  Is there anything I am missing or could improve upon?  I would have though this would have been more complicated so I am not confident in my method or my test case.

The function:

Function calculateAge() As Integer

    Dim age As Integer

    Try
        If Not Birthdate.Day.Equals(29) And Birthdate.Month.Equals(2) Then
            age = todaysDate.Year - Birthdate.Year
        Else
            age = todaysDate.Year - Birthdate.Year - 1
        End If

        Return age
    Catch ex As Exception
        Console.WriteLine(ex.ToString)
        Return Nothing
    Finally
        age = Nothing
    End Try

End Function

The test:

    Sub Main()

    'Test calculate age function'
    Console.WriteLine(chip.calculateAge)

    'Test calculate age function with a February 29th birthday'
    Dim steve As New clsAge("Steve")
    With steve
        .Birthdate = #2/29/2008#
    End With

    Dim date1 As DateTime = #2/29/2000#
    Dim date2 As DateTime = #2/28/2009#
    Dim age As Integer

    Console.WriteLine(date1.Day.ToString)

    If Not date1.Day.Equals(29) And date1.Month.Equals(2) Then
        age = date2.Year - date1.Year
        Console.WriteLine(age.ToString)
    Else
        age = date2.Year - date1.Year
        age = age - 1
        Console.WriteLine(age.ToString())
    End If

    Console.ReadLine()

End Sub


texts:
The following code is used to access a shield which converts settings written over I2C to Servo output.

I make use of the MRAA library since that's the default supported by my hardware.

To prevent my I2C commands from being written all at the same time, I use setTimeout to wait a given amount of time before executing the next.

For those unfamiliar with MRAA and I2C:

writeReg accepts two arguments. The first is the target register, the second is the data. As long as two different registers are being written, it's no problem if one is written earlier than the other. However, I want to make this code more generic so it can be used with something different than Servos as well. A generic solution should give me the possibility to burst multiple parts of data to the same address and keep the order intact.

Save to say my current structure is not easily expandable. How should I make it more expandable the Node.JS way? Expandability is more important than performance, but since I'm looking for an idiomatic solution this shouldn't be relevant.

Also note the data written seems redundant, but there are out-of-scope reasons for this.

var m = require('mraa'); // I/O library

Servo = new m.I2c(0)
Servo.address(0x74)

timer();

function timer() {
  firstI2C();
  setTimeout(timer, 5000)
}

function firstI2C() {
  Servo.writeReg(1, 250);
  Servo.writeReg(2, 128+16+0x0);
  Servo.writeReg(37, 0);
  console.log("1");
  setTimeout(secondI2C, 1000)
}

function secondI2C() {
  Servo.writeReg(1, 5);
  Servo.writeReg(2, 128+16+0x0);
  Servo.writeReg(37, 0);
  console.log("2");
  setTimeout(thirdI2C, 1000)
}

function thirdI2C() {
  Servo.writeReg(1, 250);
  Servo.writeReg(2, 128+16+2);
  Servo.writeReg(37, 0);
  console.log("3");
  setTimeout(fourthI2C, 1000)
}

function fourthI2C() {
  Servo.writeReg(1, 5);
  Servo.writeReg(2, 128+16+2);
  Servo.writeReg(37, 0);
  console.log("4");
}

I've been thinking about a function which would accept data in JSON and maps it to such functions and which keeps execution order by the position in the JSON (list). However, such a function is way beyond my current skill level.


texts: Password Trainer v1.0 - Helping you learn a new password

texts:
There are two reasons why many people choose weak passwords over stronger, more complicated ones:

They don't know that their passwords are insecure
They don't want to change to a better password because they are generally more complicated and harder to remember

So, I came up with this program: a password trainer! It helps you learn a new password, which should hopefully make point no. 2 more appealing.

While I am not new to the Python language, this my first attempt at correct styling according to PEP 0008. I have been focousing on the correct use of docstrings and commenting.

Code:

"""
Password Trainer v1.0
Copyright (c) 2016 angussidney
Released under the MIT license

This program helps you remember long, complicated, (and most importantly) secure passwords.
"""

import os

PASSWORD = "password123" # Insert your password here
MAXIMUM_TRIES = 3 # The maximum number of attempts before the program stops annoying the user.

def main():
    """Prompts the user for their password and provides feedback."""
    tries = 0
    while tries < MAXIMUM_TRIES:
        password_attempt = raw_input("Please type your password: ")
        print
        if password_attempt == PASSWORD:
            print "You entered your password correctly."
            break # Skips directly to end of session
        else:
            print "Your attempt was incorrect.\n"
            print_differences(password_attempt)
            raw_input("\nPress any key to continue...")
            tries += 1
            clear_screen()
    print "\nPassword training is complete for this session."
    raw_input("Press any key to continue...")

def clear_screen():
    """Clears the screen for a new password attempt."""
    os.system("cls" if os.name=="nt" else "clear")

def print_differences(attempt):
    """Prints the differences between the password attempt and the real password.
    Raises an error if the attempt is of the wrong length.

    Keyword arguments:
    attempt -- the password attempt

    Example output:
    Correct password: password123

    Your attempt:     passwood124
    Errors:                 x   x
    Corrections:            r   3
    """
    if len(attempt) != len(PASSWORD):
        print "Your password attempt was of the wrong length."
        print "Your attempt should have been %s characters long." % str(len(PASSWORD))
        print "No password accuracy breakdown available."
    else:
        print "Correct password: %s\n" % PASSWORD
        print "Your attempt:     %s" % attempt
        print "Errors:           ",
        for letter in range(len(PASSWORD)):
            if attempt[letter] == PASSWORD[letter]:
                print "\b ", # \b backspace character must be used to remove automatically added space
            else:
                print "\bx",
        print
        print "Corrections:      ",
        for letter in range(len(PASSWORD)):
            if attempt[letter] == PASSWORD[letter]:
                print "\b ",
            else:
                print "\b%s" % PASSWORD[letter],
        print

if __name__ == "__main__":
    main()

Notes:

Currently, the program simply returns an error if the length of the password attempt is different to that of the actual password. This will be changed in v2.0.
The program only works when run in the console. It does not work in IDLE (because the clear screen function and the backspace characters won't work)

What needs reviewing:

I would be greatful if you could review the following items:

Is my code following the PEP 0008 standard? Especially the comments and docstrings?
Is there a better way to print the corrections and errors, without using backspace characters (\b)?


texts:
I made a small application that makes async calls to an api (local in this case). The target application will make a million of calls per day.

With maxSockets set to 1 I had a time of 45 seconds. With maxSockets = 10, the execution time has dropped to 40 seconds.

How can I make this code go faster please?

var request = require('request');
var mysql      = require('mysql');
var async = require('async');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'testAPI'
});
var inputData = [];
for(i=1; i<=9999;i++){
    inputData.push('number' + i);
}
var options = {
    url: 'http://localhost/test.txt',
    maxSockets: 10
};
var limit = inputData.length;
var counter = 0;

var fetch = function(file,cb){
    request(options, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var time = (new Date().getTime()/1000)
            connection.query("insert into testAPI (name) values ('" + time + body +"')", function(err, rows, fields) {
                if (err) throw err;
                //console.log('Inserted: ' + time + body)
                counter++;
            });
        }
    })
}

async.map(inputData,fetch,function(err, results){
    if ( err){
        // either file1, file2 or file3 has raised an error, so you should not use results and handle the error
    } else {
        options.count = i;
//        request(options, fetch)
        // results[0] -> "file1" body
        // results[1] -> "file2" body
        // results[2] -> "file3" body
    }

})
var checkIfFinished = setInterval(function(){
    if(counter === limit){
        console.log('finished')
        connection.end();
        clearInterval(checkIfFinished);
    }
},1000)


texts: Custom PTZ camera controll from Appindicator

texts:
EDIT 1

Changed code to PEP8

My task is to create custom script to control PTZ (pan-tilt-zoom) cameras. We have an application for video surveillance but problem is that some functions are missing, like speed zoom out. Also, some cameras loses focus etc.

My idea is to create appindicator to control cameras from there. Below is python script, and it's working, so my question here is, can I change this code a bit for a better performance or to improve something? I am not so familiar with python, so this is more like a test project for now. I am using API to control cameras from script.

file: lib/Camctrl.py

import urllib

class Camctrl(object):
"""
Base class for Cam control
"""

def __init__(self, ip, param):
    self.ip = ip  # last part of IP address
    self.param = param
    self.getUrl().zoomOut()  # execute

def getUrl(self):
    self.url = "http://user:pass@192.168.188.{0}/cgi-bin/camctrl/camctrl.cgi?".format(
        self.ip)
    return self

def zoomOut(self):

    if type(self.param).__name__ != 'list':   # Execute one operation
        url = self.url+self.param
        self.execurl(url)

    else:  # execute multiple, iterate through list

        for command in self.param:
            command = str(command)
            url = self.url+command
            self.execurl(url)

def execurl(self, url):
    try:
        urllib.urlopen(url)
    except:
        pass

Camctrl have a task to execute command. It accepts last part of IP address, as well as params (one command is string, multiple are list).

file: lib/Gui.py

import appindicator
import gtk
from Camctrl import Camctrl

class Gui(object):

    def __init__(self, menuList, icon="None"):

        self.icon = icon
        self.statusMenu = gtk.Menu()
        self.menuList = menuList
        self.menuItemsNumber = len(menuList)
        self.getInstance().createMenus().packMenu()   # Start program

    def getInstance(self):
        """
        Create appindicator
        """

        self.appIndicator = appindicator.Indicator(
            'wallch_indicator',
            self.icon,
            appindicator.CATEGORY_APPLICATION_STATUS)
        self.appIndicator.set_status(appindicator.STATUS_ACTIVE)
        return self

    def createMenus(self):
        """
        Create menu items from the given list
        Args:
            menuList (List) = List of cameras    ***
            [0] - Name of camera (appears in menu),
            [1] - last part of ip address

        """

        for key, val in enumerate(self.menuList):
            item = gtk.MenuItem(val[0])
            self.menuList[key][0] = item

        return self

    def signals(self, item, val):
        params = [
            "setzoom=0",
            "zoom=tele&speedzoom=2",
            "zoom=wide&speedzoom=2"]
        normal = "setzoom=0"

        if val is '140':
            Camctrl('140', params)
        else:
            Camctrl(val, normal)

    def packMenu(self):
        for val in self.menuList:
            self.statusMenu.append(val[0])
            val[0].show()
            val[0].connect('activate', self.signals, val[1])

        self.appIndicator.set_menu(self.statusMenu)

        gtk.main()

File Gui.py have a task to create appindicator and menus. Inside signals function are two different lists, because one camera have issues with auto-focus, so it must zoom out, then zoom in a bit and zoom out again, and then focus is correct.

Main scrip, to run everything is main.py

#!/usr/bin/python
from lib.Gui import Gui
from lib.Camctrl import Camctrl

cameras = [
    ['Rotaciona el.kasa', '140'],
    ['Rotaciona konfekcija', '79'],
    ['Rotaciona VIP', '47'],
    ['Rotaciona mesara', '107'],
    ['Zadnja rotaciona', '13'],
    ['Rotaciona ispred', '159']
]

Gui(cameras, "/usr/share/icons/cctv.png")  # cameras and custom icon

In order to start script, you must have python-appindicator.


texts: Vanilla JS/CSS -- set of buttons to trigger sliders by transitioning height value

texts:
I've been working on a solution that allows a set of buttons to reveal divs that slide down from above on-click. I needed each button to toggle an active state for itself, but also if the user were to click on one button, reveal a div, and then go on to click another button, that the initially revealed div transition back up and dissapear while the new one appears.
When all the buttons are on one line, my solution works relatively well. But when there are buttons below some of the hidden divs, suddenly the divs those buttons trigger appear from below instead of dropping down from above... IF one of the buttons above has an active state... If not, business as usual.
Appologies if this is confusing, please see my fiddle : https://jsfiddle.net/maesj_/qdk4z1vm/26/
My solution is an adaptation of a demo that I found on css-tricks adressing a similar kind of situation, but in my case having mutliple buttons has added a bit more complexity to the mix and I'm wondering if anyone has any ideas on how I might improve my code.
Any thoughts are much appreciated!
HTML
<button  class="dyn-gallery-btn" type="button"> one </button>
<button  class="dyn-gallery-btn" type="button"> two </button>

 one text

 two text

<button  class="dyn-gallery-btn" type="button"> three </button>
<button  class="dyn-gallery-btn" type="button"> four </button>

 three text

 four text

CSS
.dyn-slide {
   background: red;
   transition: height .5s ease-in-out;
   height: 0;
   overflow: hidden;
}

.dyn-slide.active {
  height: auto;
  overflow: hidden;
}

.dyn-slide:not(.active) {
  height: 0;
  overflow: hidden;
}

JS
const slides = document.querySelectorAll('.dyn-slide')
const buttons = document.querySelectorAll('.dyn-gallery-btn')

buttons.forEach((button, i) => {
  button.addEventListener('click', () => {

    const slide = slides[i]
    const wasActive = slide.classList.contains('active')

    slides.forEach(slide => {
      slide.classList.remove('active')
      slide.style.height = 0;
    })

    if (!wasActive) {
      slide.classList.add('active')

      slide.style.height = 'auto';

    var height = slide.clientHeight + 'px';
    slide.style.height = '0px';

    setTimeout(function () {
      slide.style.height = height;
    }, 0);

    } else {
    var height = slide.clientHeight + 'px';
     slide.style.height = '0px';

     setTimeout(function () {
      slide.style.height = 0;
    }, 0);

    }
  })
})


texts: Writing information from a List of KeyValuePairs into a DataRow

texts:
I have the following algorithm which retrieves information in a List of KeyValuePair (prices) and write them in a DataRow. I was wondering if I could achieve the same result without j.

if (prices != null)
{
   for (int i = 8, j=0; j < prices.Count; i+=2, j++)
   {
      res[i] = prices[j].Value;
      res[i+1] = prices[j].Key;
   }
}

The ouput is a DataRow as follow :

res[8] = prices[0].Value
res[9] = prices[0].Key
res[10] = prices[1].Value
res[11] = prices[1].Key
res[12] = prices[2].Value
res[13] = prices[2].Key

etc.


texts: Map associative array to another array php

texts:
I have an associative array of the states of some country, and the states names are the keys:

array:13 [
  "Ontario" => null
  "Manitoba" => null
  "New Brunswick" => null
  "Yukon" => null
  "Saskatchewan" => null
  "Prince Edward Island" => null
  "Alberta" => null
  "Quebec" => null
  "Nova Scotia" => null
  "British Columbia" => null
  "Nunavut" => null
  "Newfoundland and Labrador" => null
  "Northwest Territories" => null
]

And I have anothe associative array that contains all states that have values:

array:8 [
  "Alberta" => 17
  "Cairo" => 1
  "Calgary" => 1
  "ddd" => 4
  "gfdxf" => 1
  "New Cairo" => 1
  "Ontario" => 1
  "secret" => 30
]

Now I need to map the second array to the first one so that the result would be:

array:13 [
  "Ontario" => 1
  "Manitoba" => 0
  "New Brunswick" => 0
  "Yukon" => 0
  "Saskatchewan" => 0
  "Prince Edward Island" => 0
  "Alberta" => 17
  "Quebec" => 0
  "Nova Scotia" => 0
  "British Columbia" => 0
  "Nunavut" => 0
  "Newfoundland and Labrador" => 0
  "Northwest Territories" => 0
]

I created a nested loop and it works fine, but the code is very ugly, now is there a more efficent way to do it?

My code:

foreach ($all_states as $state_x => $value_x) {

    foreach ($country_states as $state_y => &$value_y) {

        if (strtolower($state_x) == strtolower($state_y)) {

            $value_y = $value_x;
        } elseif ($value_y == NULL) {

            $value_y = 0;
        }
    }
}


texts: C++ Stack implementation using std::list

texts:
I have the following 'interface' to the C++ std::list and I was wondering how I could make it go faster. In particular, it needs to be able to evaluate up to two million operations in a matter of a couple seconds. Right now it's at around 8 seconds.

#include <iostream>
#include <list>

int main()
{

    int n, m;
    std::cin >> n >> m;

    std::list<int> myList (n);

    for (int i = 0 ; i < m; i++) {
        std::string op;
        std::cin >> op;
        if (op[1] == 'O') {
            std::cout << myList.back() << '\n';
            myList.pop_back();
        } else {
            int val;
            std::cin >> val;
            myList.push_back(val);
        }
    }

    return 0;
}

It reads input in the form

3 4
PUSH 2
PUSH 3
POP
POP

With expected output

3
2

Where 3 corresponds to highest value, and 4 corresponds to number of operations.

The operations are guaranteed to be safe (no POPing empty stacks), and each value is used at most once (this part in particular I feel I could optimize, but I'm not sure how).

Right now I'm testing with the following Python script:

print "1000000 2000000"

for val in xrange(1,1000001):
    print "PUSH ", val

for _ in xrange(0,1000000):
    print "POP"

And getting this for time:

8.89 real         0.00 user         0.01 sys

I started out using std::stack, but tried switching to std::list in order to give a preset size, so as to not need to reallocate memory. This did not help the time any, but that's where it stands as of now.


texts:
I have written the following control which allows loading a GIF from embedded resource, file, or raw Image.  It allows for more granular control over the direction and frames per second of animated image types.
The problem I face, is it is quite laggy during the frame switching (unlike the PictureBox control which doesn't offer any animation control but does animate GIFs).
Given this code and the objective, what do you think could be done to improve it's performance. Presently, it lags when animation is set to 10 FPS, and ideally, I would like user control up to 200 FPS.
public partial class ImageBox : UserControl
{
    private FrameDimension dimension;
    private int frameCount;
    private int currentFrame = -1;
    private int step = 1;

    private Timer timer;

    public int FrameCount { get { return FrameCount; } }

    public bool Animate { get { return timer.Enabled; } set { timer.Enabled = value; } }

    public enum AnimationDirectionEnum
    {
        Forward,
        Reverse
    }

    public AnimationDirectionEnum AnimateDirection { get; set; }

    private int _FPS;
    public int FPS
    {
        get { return _FPS; }
        set
        {
            if (value >= 0 && value <= 200)
            {
                _FPS = value;
                if (_FPS > 0)
                {
                    timer.Interval = 1000 / value;
                }
                else
                {
                    timer.Interval = 2000;
                    timer.Enabled = false;
                }
            }
        }
    }

    public void LoadImage(FileInfo path)
    {
        if(File.Exists(path.ToString()))
        {
            LoadImage(Image.FromFile(path.ToString()));
        }
    }

    public void LoadImage(string resource)
    {
        Stream res = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
        LoadImage(Image.FromStream(res));
    }

    public void LoadImage(Image image)
    {
        currentFrame = -1;
        BackgroundImage = image; //initialize
        dimension = new FrameDimension(BackgroundImage.FrameDimensionsList[0]); //gets the GUID
        frameCount = BackgroundImage.GetFrameCount(dimension); //total frames in the animation
    }

    public ImageBox()
    {
        DoubleBuffered = true;
        InitializeComponent();
        timer = new Timer();
        _FPS = 10;
        timer.Enabled = false;
        timer.Interval = 100;
        timer.Tick += AnimateFrame;
        currentFrame = -1;
    }

    private void AnimateFrame(object sender, EventArgs e)
    {

        currentFrame += step;

        //if the animation reaches a boundary...
        if (currentFrame >= frameCount || currentFrame < 1)
        {
            if (AnimateDirection == AnimationDirectionEnum.Reverse)
            {
                step *= -1; //...reverse the count
                currentFrame += step; //apply it
            }
            else
            {
                currentFrame = 0; //...or start over
            }
        }
        BackgroundImage.SelectActiveFrame(dimension, currentFrame);
        Invalidate();
        //Refresh();
    }

    public Image GetFrame(int index)
    {
        if(index <= frameCount && index >= 0 && BackgroundImage != null)
        {
            BackgroundImage.SelectActiveFrame(dimension, index); //find the frame
            return (Image)BackgroundImage.Clone(); //return a copy of it
        } else
        {
            return null;
        }
    }
}


texts: AGGRCOW on SPOJ – Maximize the minimum distance between aggressive cows

texts:
I am getting a TLE on my submission to AGGRCOW - Aggressive cows on SPOJ:

  Farmer John has built a new long barn, with N (2 <= N <= 100,000)
  stalls. The stalls are located along a straight line at positions
  x1,...,xN (0 <= xi <= 1,000,000,000).

  His C (2 <= C <= N) cows don't like this barn layout and become
  aggressive towards each other once put into a stall. To prevent the
  cows from hurting each other, FJ wants to assign the cows to the
  stalls, such that the minimum distance between any two of them is as
  large as possible. What is the largest minimum distance?

  Input

  t – the number of test cases, then t test cases follows.
  * Line 1: Two space-separated integers: N and C
  * Lines 2..N+1: Line i+1 contains an integer stall location, xi

  Output

  For each test case output one integer: the largest minimum distance.

  Example

  Input:

1
5 3
1
2
8
4
9

  Output:

3

  Output details:

  FJ can put his 3 cows in the stalls at positions 1, 4 and 8,
  resulting in a minimum distance of 3.

I tried checking starting from smallest minimum distance i.e zero to the largest minimum distance that will be the solution. I used recursion to solve this question but getting TLE. How can I use binary search in this problem for making it more efficient.

#include<bits/stdc++.h>
using namespace std;

bool CanBeMin( vector<long long int> arr, unsigned int b,int s,unsigned int
     cnt,long long int k){
           if(cnt == b ) return true;
           if(arr[s+1]=='\0') return false;
           for(unsigned int i=s+1 ; arr[i]!='\0'; i++){
                 if (arr[i] - arr[s] > k && b-cnt <= arr.size() - i) {
                            cnt ++;
                            return CanBeMin ( arr , b , i , cnt , k);}
                 }
                 return false;}

int count ( vector <long long int> arr, unsigned int b){
      long long int k=0;
      while (CanBeMin ( arr , b , 0 , 0 , k)) {
              k=k+1;}
      return k;}

int main(){
     int t;
     cin >> t;
     while ( t-- ){
         int a , b;
         cin >> a >> b;
         vector<long long int> arr(a);
             for( int i = 0; i < a; i++) {
                 cin >> arr[i];}
         sort ( arr.begin(), arr.end());
         if (b <= a)
         cout << count (arr, b-1);
         else cout<<"0";
         cout << endl; }
       }


texts: Create new columns depending on the columns in a table

texts:
I have code in the this example:

legacy_id phone_type phone_number
     1        f      1234567890
     1        b      1233854100
     1        f      4110256565
     2        f      0707070770
     2        b      7895120044

I want the data to end up like the following:

legacy_id  f_phone_number_1 b_phone_number_1 f_phone_number_2
     1      1234567890        1233854100        4110256565
     2      0707070770        7895120044

My initial approach works but I was hoping there is a more efficient what of doing this.

Select fill.legacy_id, max(fill.f_phone_number_1),max(fill.b_phone_number_1),max(fill.f_phone_number_2)
from
(
  Select
       a.legacy_id as legacy_id, a.phone_type as phone_type,
       case
           when a.phone_type = 'F' then a.phone_number and
           dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 1
           else null
       end as f_phone_number_1,
       case
           when a.phone_type = 'F' then a.phone_number and
           dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 2
           else null
       end as f_phone_number_2,
       case
           when a.phone_type = 'b' then a.phone_number and
           dense_rank() over (partition by a.legacy_id, a.phone_type order by a.legacy_id, a.phone_type, a.phone_number) = 1
           else null
       end as b_phone_number_1
  from table a
  group by a.legacy_id, a.phone_type, a.phone_number
) fill
group by fill.legacy_id


texts: Optimizing simple prime number function test

texts:
For my first basic project with functions, I wanted to make a program that would allow you to input a number, and it would output whether it was prime or not. For the most part, it's functional and working.

How can I optimize it to be more efficient? How can I make my code more readable for the next person? What are some good programming techniques?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <math.h>

using namespace std;
int PrimeTest(int x);

int main()
{
    int X = 0;
    cout << "Enter a number ";
    cin >> X;
    cout << "\n\n\n\t\t\t";
    if (PrimeTest(X) == 1)
    {
        cout << X << " is prime";
    }
    else
    {

        cout << X << " is NOT prime";
    }

    cout << "\n\n\n\t\t\t";
    return 0;
}

int PrimeTest(int x)
{
    int b = 2;
    while (b < x)
    {
        if (x % b == 0)
        {
            int Answer = 0;
            return Answer;
        }

        b++;
    }
    int Answer = 1;
    return Answer;
}


texts: Overriding properties at runtime but not for serialization

texts:
I have a use case where I need to deserialize some settings from a JSON file and override their values at runtime but when then configuration is saved, I want to keep the original value.
Imagine a simple JSON like this:

var json = @"{ 'WorkingDirectory': '\\bin' }";

You specify a relative path in the config but at runtime you resolve the path and use it in the entire application: @"c:\temp\bin".
Later when you save the configuration (because there are other saveable setting) you don't want to change this particular relative path but leave it untouched.

I solved this problem by creating a new type that I call Overrideable<T>. It has two properties. Value always returns the original value and gets serialized. Current returns the updated value and can be used at runtime. Current has no public setters. You use Value to actually override it and under the hood it sets the new value to Current.
public class Overrideable<T>
{
    private T _value;

    [JsonConstructor]
    public Overrideable(T value)
    {
        _value = value;
        Value = value;
    }

    public T Value { get => _value; set => Current = value; }

    [JsonIgnore]
    public T Current { get; private set; }

    public static implicit operator T(Overrideable<T> overridable) => overridable.Current;
}

To support this new type a new JsonConverter was necessary. It takes care of deserializing the value and creating an instance of the Overridable<T> and of serializing it by extracting the Value from it.
public class JsonOverridableConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        var genericArguments = objectType.GetGenericArguments();
        if (genericArguments.Length == 1)
        {
            var overridable = typeof(Overrideable<>).MakeGenericType(genericArguments[0]);
            return (objectType == overridable);
        }
        return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // .Single is safe here because CanConvert will prevent invalid types.
        var overridableGeneringArgument = objectType.GetGenericArguments().Single();
        var value = serializer.Deserialize(reader, overridableGeneringArgument);
        return Activator.CreateInstance(objectType, new[] { value });
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // .Single is safe here because CanConvert will prevent invalid types.
        var valueType = value.GetType().GetGenericArguments().Single();
        var actualValue = value.GetType().GetProperty(nameof(Overrideable<object>.Value)).GetValue(value);
        serializer.Serialize(writer, actualValue);
    }
}

Example:
Here's some example code in case someone wanted to run it:
void Main()
{
    var json = @"{ 'WorkingDirectory': '\\bin' }";
    var config = JsonConvert.DeserializeObject<Configuration>(json, new JsonSerializerSettings
    {
        Converters = { new JsonOverridableConverter() }
    });

    config.WorkingDirectory.Value = @"c:\temp\bin";

    config.Dump();

    json = JsonConvert.SerializeObject(config, new JsonSerializerSettings
    {
        Converters = { new JsonOverridableConverter() }
    });

    json.Dump();
}

public class Configuration
{
    public Overrideable<string> WorkingDirectory { get; set; }
}

Can you think of a better solution or of any improvements?


texts: Compare same filenames with different extensions

texts:
I wrote this piece of code below, but I'm sure it can be done in a more Pythonic way. Only, my knowledge is not that much to be able to figure out a more efficient way.

The DOCX and PDF files are in the same folder.

def compare_text_docx_pdf(path):
    for i in range(0, len(os.listdir(path))):
        if os.listdir(path)[i].upper().endswith('.PDF') and '.' not in os.listdir(path)[i][:7]:
            for j in range(0, len(os.listdir(path))):
                if os.listdir(path)[j].upper().endswith('.DOCX'):
                    if os.listdir(path)[i][:7] == os.listdir(path)[j][:7]:
                        try:
                            print('PDF:', os.listdir(path)[i][:7])
                            print('DOCX:', os.listdir(path)[j][:7])
                        except Exception as e:
                            print(e)


texts:
I solve this problem in Swift. I am looking for a code review, thanks!

  Given a non negative integer number num. For every numbers i in the
  range 0 ≤ i ≤ num calculate the number of 1's in their binary
  representation and return them as an array.

class Solution {
    func countBits(num: Int) -> [Int] {
        var nums = [Int](count: num+1, repeatedValue: 0)
        if num == 0 { // if num is 0
            return nums
        }
        for i in 1...num {
            nums[i] = binaryOnes(i)
        }
        return nums
    }
    func binaryOnes(num: Int) -> Int {
        var num = num
        var count = 0
        repeat  {
            if num % 2 == 0 { // even numbers
                num /= 2
            } else { // all odd numbers
                num = (num-1)/2
                count += 1
            }
        } while num > 1
        if num == 1 { // when num is 1 at the end
            count += 1
        }
        return count
    }
}


texts: Codility: MaxZeroProduct challenge and solution

texts:
Test data passes the test, so why does Codility keep failing it? Am I perhaps misunderstanding the requirement?

using System;

class Solution {
    public int solution(int[] A) {
        int max = 0;
        for (var i = 0; i < A.Length; i++) {
            for (var j = i + 1; j < A.Length; j++) {
                for (var k = j + 1; k < A.Length; k++) {
                    var product = A[i] * A[j] * A[k];
                    var zeros = trailingZeros(product);
                    //Console.WriteLine($"{product} - {zeros}");
                    if (zeros > max) {
                        max = zeros;
                    }
                }
            }
        }

        return max;
    }

    private int trailingZeros(int N) {
        if (N == 0) {
            return 0;
        }
        int count = 0;
        while (!(N <= 0 || N % 10 != 0)) {
            count++;
            N /= 10;
        }
        return count;
    }
}

Test data:

A = [7, 15, 6, 20, 5, 10]
A = [25, 10, 25, 10, 32]
A = [1, 1, 110]
A = [90, 76, 300, 10, 3, 5, 9, 1000000000]
A = [100090, 10030, 1000, 90, 87655, 676345]
A = [85, 65, 20, 50, 1, 0]
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
A = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 3, 90]
A = [101, 307, 890, 208, 406, 701, 222, 445, 5432]
A = [7, 15, 6, 20, 5, 10]
A = [90, 70, 80]
A = [900, 800, 700, 600, 500, 551, 662, 773, 884, 995]

Full description of the problem:

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given an array of N positive integers, returns the maximum
  number of trailing zeros of the number obtained by multiplying three
  different elements from the array. Numbers are considered different if they are at different positions in the array.

  For example, given A = [7, 15, 6, 20, 5, 10], the function should
  return 3 (you can obtain three trailing zeros by taking the product of
  numbers 15, 20 and 10 or 20, 5 and 10).

  For another example, given A = [25, 10, 25, 10, 32], the function
  should return 4 (you can obtain four trailing zeros by taking the
  product of numbers 25, 25 and 32).

  Assume that:

  N is an integer within the range [3..100,000]; each element of array A
  is an integer within the range [1..1,000,000,000]. Complexity:

  expected worst-case time complexity is O(N*log(max(A)))
  expected worst-case space complexity is O(N) (not counting the storage required
  for input arguments).


texts: Copy Multiple Excel Tables to VBA Dictionary

texts:
I have  a number of Excel tables that I want to populate into VBA dictionaries. Most of the code is repetitive but there are some unique things for each table that prevent me from making one general purpose routine and calling it for each table. The basic code:

Public Sub MakeDictionary( _
    ByVal Tbl As ListObject, _
    ByRef Dict As Scripting.Dictionary)

    ' This routine loads an Excel table into a VBA dictionary

    Dim ThisList As TableHandler
    Set ThisList = New TableHandler

    Dim Ary As Variant

    If ThisList.TryReadTable(Tbl, False, Ary) Then
        Set Dict = New Scripting.Dictionary

        pInitialized = True

        Dim I As Long
        For I = 2 To UBound(Ary, 1)
            Dim ThisClass As MyClass
            Set ThisClass = New MyClass

            ThisClass.Field1 = Ary(I, 1)
            ThisClass.Field2 = Ary(I, 2)

            If Dict.Exists(Ary(I, 1)) Then
                MsgBox "Entry already exists: " & Ary(I, 1)
            Else
                Dict.Add Ary(I, 1), MyClass
            End If

        Next I

    Else
        MsgBox "Error while reading Table"
    End If

End Sub

TableHandler and TryReadTable are a class and function that reads a table into a variant array.
Field1 and Field 2 are the columns of the Excel table. My tables range from 1 to 8 columns depending on the table.

I don't know how to make these lines generic:

            Dim ThisClass As MyClass
            Set ThisClass = New MyClass

            ThisClass.Field1 = Ary(I, 1)
            ThisClass.Field2 = Ary(I, 2)

At this point I have to make 10-12 versions of MakeDictionary where only the class name and class fields are unique. If that's the best way to do it, I can live with it, but, I'd like to make my code more general.
Any suggestions?


texts:
I am trying to solve this problem:

  Given an array of integers, find two numbers such that they add up to a specific target number.

and this is my strategy:

  For each i in array num, do a binary search in numfor target - i in num.

class Solution:
    # @return a tuple, (index1, index2)

    def binary_search(self, array, target):
        def _binary_search(a, l, h, t):
            if l == h:
                return None
            elif a[(h + l) / 2] == t:
                return (h + l) / 2
            elif a[(h + l) / 2] > t:
                return _binary_search(a, l, (h + l) / 2, t)
            elif a[(h + l) / 2] < t:
                return _binary_search(a, (h + l) / 2 + 1, h, t)
            else:
                return None

        return _binary_search(array, 0, len(array) - 1, target)

    def twoSum(self, num, target):
        s_num = sorted(num)
        z_num = [(i, num.index(i)) for i in s_num]
        for tup in z_num:
            n = tup[0]
            i = tup[1]
            t = self.binary_search(s_num, target - n)
            if t != None:
                index_2 = num.index(target - n)
                if i == index_2:
                    index_2 = i + 1 + num[i:].index(target - n)
                return (i + 1, index_2 + 1)

Time complexity: \$O(n * log(n))\$

This algorithm is not accepted since the it exceeds the time limitation. How can I improve it?


texts: Finding the number of moves a knight can perform while standing on a given square

texts:
This is a problem from CodeSignal which can be founded over here
Here is an image on what we have to do:

Code
def map(cell):
    new_cell1 = ''

    for i in cell:
        if i == 'a':
            new_cell1 += '1'
        if i == 'b':
            new_cell1 += '2'
        if i == 'c':
            new_cell1 += '3'
        if i == 'd':
            new_cell1 += '4'
        if i == 'e':
            new_cell1 += '5'
        if i == 'f':
            new_cell1 += '6'
        if i == 'g':
            new_cell1 += '7'
        if i == 'h':
            new_cell1 += '8'

    new_cell1 += cell[-1]
    return new_cell1

def chessKnight(cell):
    cell = map(cell)
    num_of_moves = 0

    if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
        num_of_moves += 1

    if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
        num_of_moves += 1

    if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
        num_of_moves += 1

    if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
        num_of_moves += 1

    if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
        num_of_moves += 1

    if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
        num_of_moves += 1

    if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
        num_of_moves += 1

    if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
        num_of_moves += 1

    return num_of_moves

Question
The Code works as expected and returns the right answer, but I have just put a bunch of if conditions which doesn't look nice to me. Is there any way to implement the problem but without so much if blocks?


texts: Perform sum of squared numbers without using for loop

texts:
I have to find the sum of number after performing square operation in the given input the negative numbers need to be ignored. The input Format is, first line is number of test cases followed by N as number of test inputs in new line followed by N space seperated numbers. The task need to be done using golang without using for loop. Output need to be print in new line for each test case.
3
4
3 -1 1 14
5
9 6 -53 32 16
6
3 -4 12 2 5 7

Below is my attempt to achieve the task using recurrsion.
package main

import "fmt"

func findSquareSum(x int, a []int, iteration int) {
    var num int
    if x > 0 {
        fmt.Scanf("%d", &num)
        if num > 0 {
            a[iteration-1] += num * num
        }
        findSquareSum(x-1, a, iteration)
    }
}

func readTest(x int, a []int){
    var input int
    if x > 0{
        fmt.Scanf("%d", &input)
        findSquareSum(input,a,x)
        readTest(x-1,a)
    }
}

func printResult(x int, a []int){
    if (x > 0){
        fmt.Println(a[x-1])
        printResult(x-1,a)
    }
}

func main() {
    var test int

    fmt.Scanf("%d", &test)

    a := make([]int, test)

    readTest(test,a)

    printResult(test,a)
}

My question is as there is no base case in the recursive function. How the programm is working as per expectations?


texts:
The statement of the problem is there are 2 files, one has a set of intervals i.e. 0-10, 3-40, etc which may be repetitive. The second file has a set of numbers which are also repetitive. The exercise is to get a count of the intervals, a number in the 2nd file would fit into.

Intervals.txt

0 12
2 36
6 98
2 36

Numbers.txt

2
4
123
20

What I thought of as a  possible solution was keep a count of intervals when you populate a map of intervals. So if you encounter an interval 3-40 5 times, you keep the count as 5 so you don't try to populate a map 5 times with the same interval. How it helps downstream is, if a number is in a specific interval you can count its existence in 5 intervals. Secondly there is a map of found numbers in your previous iterations, so that you don't loop through the intervals again.

I have been told, by some random guy, that my implementation is ok but not what he desires. No further explanations. I have tried raking my brain but haven't got any further. Any pointers or help would be much appreciated. Any further clarifications, please ask.

void generateCounts(const string& fname1, const string& fname2)
{
    std::ifstream file(fname1.c_str());
    string line;
    map<int, pair<int, int> > extents;
    map<int, pair<int, int> >::iterator it;
    std::string left;
    std::string right;

    if(file.is_open())
    {
        while(file.good())
        {
            getline(file, line);
            string::size_type pos = line.find(' ');
            left = line.substr(0, pos);
            right = line.substr((++pos));
            int ll = atoi(left);
            int up = atoi(right);
            it = extents.find(ll);
            if(it != extents.end())
            {
                if(it->second.first != up){
                    extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
                }
                else{
                    it->second.second += 1 ;
                }
            }
            else
            {
                extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
            }
            count = 0;
        }
    }
    fclose(inp_file);

    std::ifstream file1(fname2.c_str());
    map<int, int> found;
    map<int, int>::iterator it1;
    string str;
    if(file1.is_open())
    {
        while(file1.good())
        {
            count = 0;
            getline(file1, str);
            if(str.empty()) continue;
            int var = atoi(str.c_str());
            it1 = found.find(var);
            if (it1 == found.end())
            {
                for(it = extents.begin(); it != extents.end(); ++it)
                {
                    if((var >= it->first ) && (var <= it->second.first))
                    {
                           count += it->second.second ;
                    }
                }
                found.insert(make_pair(var, count));
            }
            else
                count = it1->second;

            cout << count << "\n";
            str.clear();
    }
    file1.close();
}


texts:
I have the following working code to send search results via e-mail.  Since we have segregated domains that cannot talk to each other, the program needs to support multiple SMTP servers.

private static int[] _SMTPport = new int[2] { 25, 587 };
private static string[] _SMTPserver = new string[4]
{
  "smtp.domain1.local",
  "smtp.domain2.local",
  "smtp.domain3.local",
  "smtp.domain4.local"
};

switch (sUserDomain)
{
  case: "domain1":
  case: "DOMAIN1":
    Send_Email(_SMTPserver[0], _SMTPport[0], false);
    break;
  case: "domain2":
  case: "DOMAIN2":
    Send_Email(_SMTPserver[0], _SMTPport[0], false);
    break;
  case: "domain3":
  case: "DOMAIN3":
    Send_Email(_SMTPserver[0], _SMTPport[0], false);
    break;
  case: "domain4":
  case: "DOMAIN4":
    Send_Email(_SMTPserver[0], _SMTPport[0], false);
    break;
  default:
    Send_Email(_SMTPserver[3], _SMTPport[0], false);
    break;
}

private static void Send_Email(string _server, int _port, bool _ssl)
{
  StringBuilder emailString = new StringBuilder();
  MailMessage mMessage = new MailMessage();

  SmtpClient smtpClient = new SmtpClient(_server);
  smtpClient.Port = _port;
  smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

  if (_ssl.Equals(true))
  { smtpClient.EnableSsl = true; }

  ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  { return true; };

  mMessage.From = new MailAddress("from-address");
  mMessage.To.Add(sEmailAddress);

  mMessage.Subject = "Logs from " + Environment.GetEnvironmentVariable("COMPUTERNAME") + " searched " + sDate + " for " + sSearchTerm;
  emailString.Append("
Here are the file(s) on " + Environment.GetEnvironmentVariable("COMPUTERNAME") + " under " + sDate + " that contain " + sSearchTerm + "

");
  emailString.AppendLine("

Filenames
");
  int count = 0;
  foreach (var item in logList)
 {
   if (count % 2 == 0)
   {
     emailString.AppendLine("
" + Path.GetFileName(item) + "
");
   }
   else
  {
    emailString.AppendLine("
" + Path.GetFileName(item) + "
");
  }
  count++;
}
emailString.Append("

");
mMessage.IsBodyHtml = true;

mMessage.Body = emailString.ToString();

I'm working on converting it to be object-oriented.  My concern is that I need to add multiple items to the message before sending.  Here is what I have so far — am I on the correct path?

public class EmailClass
{
  private string _domain;
  private string _emailaddress;
  private string _fromaddress;
  private string _subject;
  private List<string> _message = new List<string>();

  public string Domain
  {
    get { return _domain; }
    set { _domain = value; }
  }

  public string EmailAddress
  {
    get { return _emailaddress; }
    set { _emailaddress = value; }
  }

  public string FromAddress
  {
    get { return _fromaddress; }
    set { _fromaddress = value; }
  }

  public string Subject
  {
    get { return _subject; }
    set { _subject = value; }
  }
  public List<string> Message
  {
    get { return _message; }
    set { _message = value; }
  }
}


texts:
Can anyone help me with checking this code? It is for connecting to a database. The method getFromDatabase is to take values from the database and put it to a dataset, and the other method getFromDatabaseToCombo is to get from the database to a comboBox.
I can't shake off this feeling that the last two methods can be combined somehow and something is not right in this class.

(the variables will be set to private later)

   public class dbConnect
   {
    public MySqlConnection con;//declare variable for connection
    public MySqlCommand com;//varialbe for command
    public DataTable dt;
    public DataSet ds;
    public DataView myview;

    public dbConnect()  //Constructor
    {
        string serverName = "localhost"; //server name
        string dbName = "airline_db";//database name
        //string pass = "***"; //password
        string uid = "root";
        string conString = "server="+serverName+";User Id="+uid+";database="+dbName+"";

        con = new MySqlConnection(conString); //instance of con object

    }

    public void openConnect() //to open connection to database
    {
        if (con != null && con.State == ConnectionState.Closed)//to check if conn is already open or not
        {
            con.Open();
        }
    }

    public void closeConnect() //to close connection to database
    {
        if (con!=null && con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }

    public void comText(string sqlQuery) //method to use sql
    {
        com = new MySqlCommand(sqlQuery,con);
        //com.ExecuteNonQuery();
    }

    //to get from the database
    public DataTable getFromDatabase(string sqlQuery)
    {
        dt = new DataTable();
        ds = new DataSet();
        MySqlDataAdapter adp = new MySqlDataAdapter();

        comText(sqlQuery);
        adp.SelectCommand = com;
        adp.Fill(ds);
        dt = ds.Tables[0];      //all tables assignted as table[0]
        return dt;
    }
    public void getFromDatabaseToCombo(string sqlQuery) //check with above
    {
        dt = new DataTable();
        ds = new DataSet();
        MySqlDataAdapter adp = new MySqlDataAdapter(sqlQuery,"server=localhost;User Id=root;database=airline_db");
        adp.Fill(dt);
    }
}
}


texts:
I created an rxjs search for a hiring company, but I got rejected for the following reason:
-performance issue on a bigger data set.
-bugs
My question is how can I make this code better for the next time if I have similar task?
brands =  These should be populated from the brand property from the collection of products.

The search should match using the name, description and brand
properties.

The search should not fire unless a minimum of three characters have been typed.
The search should only fire a maximum of once per 400 milliseconds.

If searching for “xxx” with the brand selected as “xxx” and In Stock, then only products matching all three filters

const stackoverflowFilter = (filter: ISearch) => {
  return (product: IProducts): boolean => {
    return ((
      (
        (product.name.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1) ||
        product.description.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1 ||
        product.brand.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1) &&
      product.brand.toLowerCase().indexOf(filter.select.toLowerCase()) !== -1 &&
      (filter.radio === 'all' ? true : filter.radio === 'in-stock' ? product.quantity > 0 : product.quantity === 0)
    )
    )
  };
};

export interface ISearch { input: string; select: string; radio: string }

> public getStackoverflow(): Observable<Stackoverflow[]> {
>         return of([
>           {
>             id: "1",
>             name: "This is just test data",
>             price: "89.9",
>             description: "test data",
>             brand: "stackoverflow",
>             quantity: 4
>           }....])}

 this.stackoverflow$ = this.service.getStackoverflow();

    this.stackoverflow$.pipe(
      tap((prod) => {
        this.stackoverflow = prod;
        this.brands = this.stackoverflow.map(({ brand }) => brand).reduce((prev, cur) => {
          if (prev.indexOf(cur) < 0) prev.push(cur);
          return prev;
        }, []);
      }),
      concatMap(() =>
        this.search$.pipe(
          debounceTime(400),
          distinctUntilChanged(),
          switchMap((search: string) =>
            iif(() => search.length >= 3,
              this.stackoverflow$.pipe(
                map(stackoverflow=> stackoverflow.filter(stackoverflowFilter(this.filter))),
                distinctUntilChanged((curr, prev) => curr === prev),
              ),
              this.stackoverflow$.pipe(
                filter(() => search.length === 0),
              )
            )
          )
        ))
    ).subscribe(
      stackoverflow=> { this.stackoverflow= stackoverflow; },
      (err) => throwError(err)
    );


texts: Wrapping std::bind call in a function returning std::function

texts:
Is this code correct?

It appears to work in g++ 4.8.3 and clang (bcc64), however appearing to work is no guarantee of correctness :)

The aim is to be able to replace a call to a member function:

void Master::go()
{
     std::string s;
     func(s);    // func is a member function of Master
}

with a function template that wraps this call (and would indeed work with any class, not just Master):

void Master::go()
{
    std::string s;
    call_function( func, s );    // pseudocode
}

which ends up calling this->func(s).

The code which seems to work:

#include <iostream>
#include <string>
#include <functional>

struct Master
{
    void func(std::string &s) { std::cout << "Master::func(" << s << ")\n"; }
    void go();
    Master() {}

private:
    Master(Master const &);
};

int main()
{
    Master m;
    m.go();
}

template<typename FuncT>
void call_function( std::function<FuncT> fp, std::string s )
{
    fp(s);
}

template<typename FuncT, typename Host>
typename std::function<FuncT> my_binder(Host *h, FuncT Host::*p)
{
    using std::placeholders::_1;
    return std::bind(p, h, _1);
}

void Master::go()
{
    std::string s("hello");
    call_function( my_binder(this, &Master::func), s );
}

If the code is correct, then is my function my_binder a good idea, or am I overlooking a simpler option?


texts:
How can this method that inserts a hashref into a database table be improved?  It assumes that the columns of the database table are named identically to the fields in the hashref.  The return value is the id field created by the insert.

sub insert(){
    my ($table, $data) = @_;
    my ($fields, $placeholders, $values) = ("", "", []);
    while (my ($field, $value) = each %$data){
        $fields.=", " if ($fields);
        $fields.=$field;
        $placeholders.=", " if ($placeholders);
        $placeholders.="?";
        push(@$values, $value);
    }
    $dbh->prepare("INSERT INTO $table ($fields) VALUES ($placeholders)")->execute(@$values);
    return $dbh->last_insert_id(undef, undef, undef, undef);
}

It assumes that $dbh is a correctly initialized global database handle.

It is used like:

&insert("animals", {
    "type"=>"cat",
    "name"=>"Patches",
    "date-of-birth"=>"November 1, 2015",
    "date-of-death"=>undef
});

Which will insert a record into the animals table:

id | type | name    | date-of-birth    | date-of-death
=====================================================
 1 | cat  | Patches | November 1, 2015 | null


texts: Compute text area given letter heights and a text

texts:
I have solved the designer pdf question with haskell. The code works. I am posting the code here to know how I could have done it better.

  First line contains the weight of each alphabet
  Second line contains the word.

  Sample input

1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 7
zaba

  Output

28

  Explanation
  each character would take 1 space and multiply it with the max weight
  4 characters * 1 space * 7 weight = 28
  'z' has the max weight of 7.

Code

import Data.List
import Data.Maybe

getintval::(Maybe Int) -> Int
getintval Nothing = 1
getintval (Just x) = x

solve'::[Char]->[(Char, Int)] -> Int
solve' ch lst = k $  map getintval $ map (\x -> finder' x) ch
  where
  k::[Int] -> Int
  k fb = (*) (length ch)   $ foldl (\acc x -> max acc x) 1 fb
  finder'::Char -> Maybe Int
  finder' g =  case i of
            Just(x1,x2) -> Just x2
            Nothing -> Just 1
            where i = find(\(val1, val2) -> val1 == g) lst

solve::[Char] -> [Char] -> Int
solve wght val = solve' val rec
  where
  rec::[(Char, Int)]
  rec = zipWith (\x y -> (x, y)) ['a'..'z'] word1
  word1::[Int]
  word1 = map(read::String->Int) $ words wght

main::IO()
main = do
  weight <- getLine
  pdfstr <- getLine
  putStr . show $ solve weight pdfstr


texts: Scrape webpage with Beautifulsoup and export relevant data to csv

texts:
I am looking for feedback on my code, how I can simplify some operations, use more efficient methods or other best practices. This is my first web scraping project.

The goal here is to scrape a dentist's page for reviews and export to csv. I have not solved the issue with infinite scrolling, but ignore that for now. For the existing code, what can I improve?

I used ipython as I had to do a lot of trial and error to get beautifulsoup to provide me with the right output. The 4th review is in a different format than every other review on the site, and caused Nonetypes to mess up most of my loops. I found solutions for this, but not sure if ideal either. Thanks in advance.

The full notebook is here:
https://github.com/joepope44/dentist_reviews/blob/master/upwork-web-scrape-2nd-approach-v2.ipynb

The meat of the code is here though:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import re

url = 'https://www.toothssenger.com/118276-ofallon-dentist-dr-edward-logan#read_review'
r = requests.get(url)
html_doc = r.text
soup = BeautifulSoup(html_doc, "lxml")

blocks = soup.find_all("div", attrs={"class" : "jsReviewItem"}, limit=20)
one_block = soup.find("div", attrs={"class" : "jsReviewItem"})

records = []

#TO DO: handle infinite scrolling on webpage

for block in blocks:

    #review number
    review_num = block.select("div b")[0]
    if len(review_num) > 0:
        review_num = review_num.text.strip()
    else:
        review_num = "NaN"

    #reviewer name
    name = block.select("span")[1]
    if len(name) > 0:
        name = name.text.strip()
    else:
        name = "NaN"

    #date published
    date = block.select('span[itemprop="datePublished"]')
    if len(date) > 0:
        date = date[0].text.strip()
    else:
        name = "NaN"

    #review text
    review = block.find("span", {"itemprop":"reviewBody"})
    if review is not None:
        review = review.text.strip()
    else:
        review = "NaN"

    #select ratings tag and count the number of icons for each rating type
    ratings = block.select('div[class="mb-0-20"]')

    if len(ratings) > 0:

        #facilities ratings
        fac = ratings[0]
        fac_rating = (len(list(fac.find_all("i"))))

        #service rating
        serv = ratings[1]
        serv_rating = (len(list(serv.find_all("i"))))

        #painless rating
        painless = ratings[2]
        painless_rating = (len(list(painless.find_all("i"))))

        #results rating
        results = ratings[3]
        results_rating = (len(list(results.find_all("i"))))

        #cost rating
        cost = ratings[4]
        cost_rating = (len(list(cost.find_all("i"))))

    else:
        ratings = "NaN"

    records.append((review_num, name, date, review, fac_rating, serv_rating, painless_rating, cost_rating))

print(records[0])


texts:
Part 1: General Cleanup

(Edit: Part 2 is here.)

I have a script in a Work Order Management System (Maximo) that performs a spatial query.

Details:

Takes the X&Y coordinates of a work order in Maximo
Generates a URL from the coordinates (including other spatial query information)
Executes the URL via a separate script/library (LIB_HTTPCLIENT)
Performs a spatial query in an ESRI REST feature service (a separate GIS system)
JSON text is returned to Maximo with the attributes of the zone that the work order intersected
The zone number is parsed from the JSON text via a separate script/library (LIB_PARSE_JSON)
Inserts the zone number into the work order record

Jython main automation script

from psdi.mbo import MboConstants
from java.util import HashMap

#Get the y and x coordinates(UTM projection) from the WOSERVICEADDRESS table via the SERVICEADDRESS system relationship
#The datatype of the LatitydeY and LongitudeX is decimal: 1234567.8335815760, 123456.4075621164
#Convert the decimals to integers, and then strings, for the purpose of generating the URL (I don't think the URL can have decimal places)
laty = str(mbo.getInt("SERVICEADDRESS.LatitudeY"))
longx = str(mbo.getInt("SERVICEADDRESS.LONGITUDEX"))

#Verify if the numbers are legitimate UTM coordinates
if len(laty) == 7 and len(longx) == 6:
    #Assemble the URL (including the longx and the laty). Note: The coordinates are flipped in the url
    url="http://something.com/arcgis/rest/services/something/Zones/MapServer/15/query?geometry=" + longx + "%2C" + laty + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=pjson"
    #Get the JSON text from the feature service (the JSON text contains the zone value)
    ctx = HashMap()
    ctx.put("url",url)
    service.invokeScript("LIB_HTTPCLIENT",ctx)
    json_text = str(ctx.get("response"))

    #Parse the zone value from the JSON text
    ctx = HashMap()
    ctx.put("json_text",json_text)
    service.invokeScript("LIB_PARSE_JSON",ctx)
    parsed_val = str(ctx.get("parsed_val"))

    #Enter the zone value into the zone field in the work order
    mbo.setValue("DESCRIPTION","Waste Zone: "+parsed_val,MboConstants.NOACCESSCHECK)

Jython library (LIB_HTTPCLIENT)

from psdi.iface.router import HTTPHandler
from java.util import HashMap
from java.lang import String
handler = HTTPHandler()
map = HashMap()
map.put("URL",url)
map.put("HTTPMETHOD","GET")
responseBytes = handler.invoke(map,None)
response = String(responseBytes,"utf-8")

JavaScript library (LIB_PARSE_JSON)

#The field name (ZONE) is hardcoded. I'm not sure if this is best practice or not.
var obj = JSON.parse(json_text);
parsed_val = obj.features[0].attributes.ZONE

How can this code be improved?


texts: Taking text from a file and formatting it

texts:
My code takes numbers from a large text file, then splits it to organise the spacing and to place it into a 2-dimensional array. The code is used to get data for a job scheduler that I'm building.

#reading in workload data
def getworkload():
    work = []
    strings = []
    with open("workload.txt") as f:
        read_data = f.read()
        jobs = read_data.split("\n")
    for j in jobs:
        strings.append(" ".join(j.split()))
    for i in strings:
        work.append([float(s) for s in i.split(" ")])
    return work

print(getworkload())

The text file is over 2000 lines long, and looks like this:

    1        0 1835117 330855  640   5886   945   -1     -1    -1  5   2   1   4  9 -1 -1 -1
    2        0 2265800 251924  640   3124   945   -1     -1    -1  5   2   1   4  9 -1 -1 -1
    3        1 3114175     -1  640     -1   945   -1     -1    -1  5   2   1   4  9 -1 -1 -1
    4  1813487   7481     -1  128     -1 20250   -1     -1    -1  5   3   1   5  8 -1 -1 -1
    5  1814044      0    122  512   1.13  1181   -1     -1    -1  1   1   1   1  9 -1 -1 -1
    6  1814374      1     51  512     -1  1181   -1     -1    -1  1   1   1   2  9 -1 -1 -1
    7  1814511      0     55  512     -1  1181   -1     -1    -1  1   1   1   2  9 -1 -1 -1
    8  1814695      1     51  512     -1  1181   -1     -1    -1  1   1   1   2  9 -1 -1 -1
    9  1815198      0     75  512   2.14  1181   -1     -1    -1  1   1   1   2  9 -1 -1 -1
   10  1815617      0    115  512   1.87  1181   -1     -1    -1  1   1   1   1  9 -1 -1 -1
    …

It takes 2 and a half minutes to run but I can print the returned data. How can it be optimised?


texts:
I know this is a bit elementary, but I am highly uncomfortable writing Scheme code, and I want to make sure that what I'm doing is good practice.  I know mutation is frowned upon in Scheme.
I have no other source of review so I have come to you all.
(define (filter-lst fn lst)
    (if (not (null? lst))
    (if (fn (car lst))
        (cons (car lst) (filter-lst fn (cdr lst)))
        (filter-lst fn (cdr lst))
        )
    '()
    )
)

Note: The function seems to be working according to a few test cases I ran.
As a follow-up PURELY STYLISTIC question, which of these is preferred?
#1
(define (merge l1 l2)
      (if (null? l1) l2
          (if (null? l2) l1
              (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))

#2
(define (merge l1 l2)
    (if (null? l1) l2
        (if (null? l2) l1
            (cons (car l1) (cons (car l2) (interleave (cdr l1) (cdr l2))))
        )
    )
)


texts:
I'm implementing the compareTo method to set the natural order of an object. My object has three fields that make up a name. fName, lName, middleInitial. The natural ordering should be by lName, fName, middleInitial. I was wondering if this is an efficient way of implementing the compareTo.

    @Override
public int compareTo(Employee o) {
    StringBuilder builder = new StringBuilder();
    String thisName;

    if(!StringUtils.isEmpty(this.lName.trim())){
        builder.append(this.lName);
    }
    if(!StringUtils.isEmpty(this.fName.trim())){
        builder.append(this.fName);
    }
    if(!StringUtils.isEmpty(this.midInitial.trim())){
        builder.append(this.midInitial);
    }
    thisName = new String(builder.toString());
    builder = new StringBuilder();

    if(!StringUtils.isEmpty(o.lName.trim())){
        builder.append(o.lName);
    }
    if(!StringUtils.isEmpty(o.fName.trim())){
        builder.append(o.fName);
    }
    if(!StringUtils.isEmpty(o.midInitial.trim())){
        builder.append(o.midInitial);
    }

    if(!StringUtils.isEmpty(thisName) && !StringUtils.isEmpty(builder.toString())){
        return thisName.compareTo(builder.toString());
    }else{
        return 0;
    }

}


texts: Haskell-like function composition function

texts:
Much like this question I'm attempting to write in C++ something which can resemble Haskell's (.) function as much as possible, which is basically Chapter 1's second exercise from Bartosz Milewski's Category Theory for Programmers.
This similar question about writing the identity function served as a reference too.
This answer on StackOverflow reassured me that decltype used on lambdas' auto parameters is equivalent to decltype used on template parameters.
And this is what I came up with:
static constexpr struct compose_t {
    template <typename F, typename G>
    constexpr decltype(auto) operator()(F&& f, G&& g) const noexcept {
        return [&f,&g](auto&& x){
            return f(g(std::forward<decltype(x)>(x)));
        };
    }
} compose;

Some thoughts:

operator() takes f and g by reference, and the returned lambda captures them by reference; and I made this choice thinking it should make passing non-stateless callables cheaper, but I'm not sure I made the right choice.  Another reference is this.
Since I'm passing them by reference, I had to choose between const& and &&, and I've basically chosen randomly.
I've not concerned myself with variadics, as I wanted a binary function composition "operator", in line with Haskell's (.) :: (b -> c) -> (a -> b) -> a -> c.
I cannot compose compose with something else, because it is binary, whereas the implementation implicitly assumes that F and G be unary. I guess making something like compose(compose,compose) (which is (.).(.) in Haskell) possible would be up to a partial application "facility".

This is a code where I tried to test it:
#include <cassert>
#include <utility>

// ... the code from above

static constexpr struct changesign_t {
    template<typename T>
    constexpr decltype(auto) operator()(T&& t) const noexcept { return -t; };
} changesign;

int square(int x) { return x*x; }
int twice(int x) { return 2*x; }

int main() {
    assert(compose(square,twice)(3) == 36);
    assert(compose([](int x){ return x*x; },[](int x){ return 2*x; })(3) == 36);
    assert(compose(changesign, compose([](auto x){ return x*x; }, [](auto x){ return 2*x; }))(3) == -36);
}


texts: Terrain map generator with JavaScript and HTML5/CSS

texts:
I'm trying to generate maps (as in terrain maps) using JavaScript only, but currently performance is pretty bad at best.

What my script currently does is:

Generate a square base grid for the map and print it
For each cell, check the adjacent cell's terrain type and select the terrain for the current cell
Print the results

How can I improve performance? (I'm aware that the current result looks nothing like an actual map, but one thing at a time.)

I've hosted my current script here.

(base and terrain properties are CSS classes)

$(document).ready(function () {
    var x = 50;
    var y = 50;
    var worldMap = [];

    worldMap = genesis(x, y, worldMap);
    worldMap = terraform(x, y, worldMap);
});

function genesis(x, y, worldMap) {
    for (i = 0; i < x; i++) {
        worldMap[i] = [];
        for (var j = 0; j < y; j++) {
            worldMap[i][j] = {
                xCoord: i,
                yCoord: j,
                base: "cell",
                terrain: "baren"
            };
            //console.log(worldMap[i][j]);
        }
    }

    var world = $(".world");

    for (i = 0; i < x; i++) {
        var row = document.createElement("div");
        row.className = "row";

        for (j = 0; j < y; j++) {
            var cell = document.createElement("div");
            cell.className = worldMap[i][j].base + " " + worldMap[i][j].terrain;
            cell.setAttribute('data-row', i);
            cell.setAttribute('data-col', j);
            row.appendChild(cell);
        }

        world.append(row);
    }

    return worldMap;
}

function selectTerrain(worldMap, cell) {
    var terrain = ["river", "river", "forest", "forest", "plain", "plain", "plain", "desert", "mountain"];

    var i = cell.xCoord;
    var j = cell.yCoord;

    console.log(i + " " + j);

    for (var a = -1; a < 2; a++) {
        for (var b = -1; b < 2; b++) {
            var m = parseInt(i) + parseInt(a);
            var n = parseInt(j) + parseInt(b);

            if (typeof worldMap[m] != "undefined") {
                if (typeof worldMap[m][n] != "undefined") {
                    var adj = worldMap[m][n];
                    console.log(adj);
                    console.log("Is defined");
                    if (adj.terrain != "baren") {
                        console.log("Is not baren");
                        for (z = 0; z < 4; z++) {
                            terrain.push(adj.terrain);
                        }
                        console.log(terrain);
                    }
                }
            }

        }
    }

    var selectedIndex = Math.floor(Math.random() * (terrain.length - 0)) + 0;
    var selectedTerrain = terrain[selectedIndex];

    return selectedTerrain;
}

function terraform(x, y, worldMap) {
    for (var i = (x-1); i-- ;) {
        for (var j = (y-1); j--; ) {
            var mappingCell = worldMap[i][j];
            console.log(mappingCell);
            var selectedTerrain = selectTerrain(worldMap, mappingCell);

            worldMap[i][j].terrain = selectedTerrain;

            console.log(mappingCell.terrain);

            var cell = $("[data-row=" + i + "][data-col=" + j + "]");
            cell[0].className = mappingCell.base + " " + mappingCell.terrain;
        }
    }

    return worldMap;
}


texts:
I have this working code and was wondering how I can optimize it. Is there anything I can declare globally so it does not need to be be created over and over? This function is called around 30 times a second.

bmScreenBuffer is a global Bitmap.

Contents of drawScreen():

// Buffer - Get the main window handle to create 2 dcs (device contexed)
HWND hwndMain = programInfoPtr->hWnd;
HDC hdcMain = GetDC(hwndMain);
HDC hdcBuffer = CreateCompatibleDC(hdcMain);

// Current buffer and old
HBITMAP hbm_Buffer = CreateCompatibleBitmap(hdcMain, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight());
HBITMAP hbm_oldBuffer = (HBITMAP)SelectObject(hdcBuffer, hbm_Buffer);

// Tells GDI+ to draw to the "GDI" DC
Graphics* g = new Graphics(hdcBuffer);
g->DrawImage(bmScreenBuffer, 0, 0);

// Now copy the image to the screen
BitBlt(hdcMain, 0, 0, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight(), hdcBuffer, 0, 0, SRCCOPY);

// Clean Up
ReleaseDC(hwndMain, hdcMain);
SelectObject(hdcBuffer, hbm_oldBuffer);
DeleteDC(hdcBuffer);
DeleteObject(hbm_Buffer);
delete g;


texts: Efficiently shift elements right by one in an __mm256 vector

texts:
The code below correctly shifts v256f_stats by one and puts the results into v256f_x3. This is then used to get the delta between n[1..7] and n[0..6]. The undefined element in the output is not an issue.

Is there a more efficient way of doing this?

// create a shift-by-1 copy
v256f_x1 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0);
v256f_x2 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0x11);
v256f_x1 = _mm256_permute_ps(v256f_x1, 0b10010011);
v256f_x2 = _mm256_permute_ps(v256f_x2, 0b10010011);
v256f_x3 = _mm256_blend_ps(v256f_x1, v256f_x2, 0b11100000);


texts: Properly create and customise a web app using visual studio 2015 C# MVC template

texts:
I'm new to C# web, I want to know how to properly create a web app using
visual studio 2015 MVC templates, and being able to customise some of its code. I want to both practice C# web and clean code...
So I have 2 projects, one for Domain and another which is the Web App.

For example: In my Domain I have a class named User, with the following code (It is aimed at users who speak Spanish so error messages are in Spanish):

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Domain
{
    public class User
    {
        public int Id { get; set; }

        [DisplayName("Nombre de Usuario")]
        [Required(ErrorMessage = "El Nombre de Usuario es obligatorio.")]
        [StringLength(30)]
        [Index(IsUnique = true)]
        public string UserName { get; set; }

        [DisplayName("Correo Electrónico")]
        [Required(ErrorMessage = "El Correo Electrónico es obligatorio.")]
        [StringLength(45)]
        [EmailAddress]
        [Index(IsUnique = true)]
        public string Email { get; set; }

        [DisplayName("Contraseña")]
        [Required(ErrorMessage = "La Contraseña es obligatoria.")]
        [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Confirmar Contraseña")]
        [DataType(DataType.Password)]
        [NotMapped]
        [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")]
        public string ConfirmPassword { get; set; }

        public bool Locked { get; set; } = false;

        public bool ConfirmedAccount { get; set; } = false;

        [DisplayName("Perfil")]
        [Required(ErrorMessage = "El Perfil es obligatorio.")]
        public Profile Profile { get; set; }

        private User() { }

        public User(string userName, string email, string password, string confirmPassword, Profile profile)
        {
            UserName = userName;
            Email = email;
            Password = password;
            ConfirmPassword = confirmPassword;
            Profile = profile;
        }
    }
}

Before continuing, any suggestions about this code will be very welcome!

I want to use ResetPasswordViewModel, ForgotPasswordViewModel, ExternalLoginConfirmationViewModel, and many other functionalities that come with MVC templates (you can see them inside AccountViewModels.cs) without programming them myself (that is the idea of using a template isn't it?), but I also want to have my own User class...

Reading the template code, I've found that ApplicationUser class inside IdentityModels.cs would have the logic for User the template applies, It also has a commentary telling me that if I want any other User properties added, they should be added here. But I don't think it would be a good idea to have Business bound code inside the web app, what if (hypothetically speaking) tomorrow I want to make the same application on another platform? (and by the way, why does the template encourage to have the business code inside the web app in the first place??)

I hope you get the idea by now, how to use my own User code to work properly with the MVC template? For example to work along with the class AccountViewModels.cs.

I know those are a lots of questions (I've got plenty more)... As I said, I'm new to this and want to get the hand of it, any suggestions on how to improve my code is welcome.

Regards


texts: Asynchronously fetching data from the database

texts:
The following C# code is written to fetch the Categories data from SQL Server Database using Asynchronous Task for HttpGet. The Dapper library is used as ORM.

I need help to identify whether the Async Task implementation is correct or any better way to implement.

CategoriesController.cs

public class CategoriesController : Controller
{
  [HttpGet]
  public async Task<IActionResult> FindList(CategorySearchModel searchModel)
  {
    var results = await new CategoryQueryService().FindList();

    return GetHandler(results);
  }

  IActionResult GetHandler(object results)
  {
      return new OkObjectResult(new { results });
  }
}

CategoryQueryService.cs

public class CategoryQueryService : BaseQueryDataStoreAsync<CategoryQueryModel>
{
  public override Task<IEnumerable<CategoryQueryModel>> FindList()
  {
    const string dbConnectionString = "-- db connection string here --";
    const string sql = "SELECT CategoryId, CategoryName FROM Category ORDER BY CategoryName ASC";

    return QueryAsync(dbConnectionString, sql);
  }
}

CategoryQueryModel.cs

public class CategoryQueryModel {
  public int CategoryId { get; set; }
  public int CategoryName { get; set; }
}

BaseQueryDataStoreAsync.cs

using Dapper;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;

public abstract class BaseQueryDataStoreAsync<T> where T : class
{
  public abstract Task<IEnumerable<T>> FindList();

  public async Task<IEnumerable<T>> QueryAsync(string dbConnectionString, string sql)
  {
    using (var connection = new SqlConnection(dbConnectionString))
    {
      return await connection.QueryAsync<T>(sql, conditions: null, transaction: null, commandTimeout: null, commandType: null);
    }
  }
}


texts: Having models which inherit from one base model

texts:
I have a model such as this below that acts as a base model. Several other models inherit from this one since they will all share common properties. Would an approach like this fit best practices or would it be better to go another route. I'm aware that composition is always considered a best practice.

public class BaseServiceResponse
{
    #region Properties

    public Guid PatientId { get; set; }
    public Guid PracticeId { get; set; }
    public ServiceStatusCodes Status { get; set; }
    public string Message { get; set; }
    public string ReturnUrl { get; set; }

    #endregion

    #region Constructors

    public BaseServiceResponse()
    {
        InitMembers();
    }

    public BaseServiceResponse(Guid patientId)
    {
        this.PatientId = patientId;
    }

    #endregion

    #region Private Methods

    private void InitMembers()
    {
        this.PatientId = Guid.Empty;
        this.PracticeId = Guid.Empty;
        this.Status = 0;
        this.Message = string.Empty;
        this.ReturnUrl = string.Empty;
    }
    #endregion
}

I then have several other models which inherit from it such as this one

public class FullReportResponse : BaseServiceResponse
{
    #region Properties

    public List<string> ReportNames;
    public string SomeOtherProp;

    #endregion

    #region Constructors

    public FullReportResponse(Guid patientId, List<string> reportNames)
    {
        this.PatientId = patientId;
        this.ReportNames = reportNames;
    }

    #endregion
}


texts:
This code is to solve the Hacker Rank problem array left rotation.

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.

public static int[] rotLeft(int[] a, int d)
    {
        for (int intI = 0; intI < d; intI++)
        {
            int temp = 0;
            temp = a[0];
            for (int intK = 0; intK < a.Length; intK++)
            {
                a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
            }
        }
        return a;
    }
    static void Main(string[] args)
    {
        string[] nd = Console.ReadLine().Split(' ');
        int n = Convert.ToInt32(nd[0]);
        int d = Convert.ToInt32(nd[1]);
        int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
        int[] result = rotLeft(a, d);
        Console.WriteLine(string.Join(" ", result));
    }

This program works fine, but it takes too long with some examples. How can I improve it?


texts: Improving performance hacker rank Median

texts:
I'm trying to compete on HackerRank and my answer got accepted, but the times are not so good. I have a friend who sent the answer in C# too but somehow made it a lot faster. I'm wondering what can I do to improve it.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution {

   static void Main(String[] args) {
      int N;
      StringBuilder st= new StringBuilder();

      N = Convert.ToInt32(Console.ReadLine());
      int[] x = new int[N];
       List<double> a= new List<double>();
      string[] s = new string[N];

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

         string tmp = Console.ReadLine();
         string[] split = tmp.Split(new Char[] {' ', '\t', '\n'});

         s[i] = split[0].Trim();
         x[i] = Convert.ToInt32(split[1].Trim());
          bool r=true;

          if(s[i]=="r"){
              int index= a.BinarySearch(x[i]);
              if(index>=0){
                  a.RemoveAt(a.LastIndexOf(x[i]));
              }
              else{
              r=false;
              }

          }else{
              var index = a.BinarySearch(x[i]);
                if (index < 0) index = ~index;
                  a.Insert(index,x[i]);
          }
          if(!r || a.Count==0){
              st.AppendLine("Wrong!");

          }
          else{
          st.AppendLine(calcularModa(a).ToString());
          }
      }
       Console.WriteLine(st.ToString());

   }
   static double calcularModa(List<double> a){

   int i= a.Count/2;
       if(a.Count % 2 !=0){
           return a[i];
       }else{
           return ((a[i - 1] + a[i]))/2;
       }

    }
}


texts:
Challenge:

  Write a program which prints all the permutations of a string in alphabetical order.

Specifications:

  Your program should accept a file as its first argument.
   The file contains input strings, one per line.
   Print the permutations of the string separated by commas, in alphabetical order.
   We consider that digits < upper case letters < lower case letters.
   The sorting should be performed in ascending order.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class PermutateString {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            System.out.println(
                permutateString(sortString(input.nextLine()))
            );
        }
        input.close();
    }

    private static void permutate(String prefix, String str, StringBuilder sb) {
        int len = str.length();

        if (len == 1) {
            sb.append(',').append(prefix).append(str);
        } else {
            for (int i = 0; i < len; i++) {
                permutate(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, len), sb);
            }
        }
    }

    private static String permutateString(String input) {
        StringBuilder characterBuilder = new StringBuilder();
        permutate("", input, characterBuilder);

        return characterBuilder.substring(1);
    }

    private static String sortString(String input) {
        char[] temp = input.toCharArray();
        Arrays.sort(temp);
        return String.valueOf(temp);
    }
}

Sample Input:

hat
abc
Zu6

Sample Output:

aht,ath,hat,hta,tah,tha
abc,acb,bac,bca,cab,cba
6Zu,6uZ,Z6u,Zu6,u6Z,uZ6

I first started solving this using a list of lists, but that required a lot of loops within loops and making size! lists seemed memory intensive..and confusing, This marks the first instance where I find a problem should be solved using recursion.

Generally wondering if there are any improvements I could make to solve this in a faster, cleaner, or memory efficient way.

For those interested, the source is CodeEval.com.

P.S.
If it seems like Java 8 features were suggested before, yet not used here, there's a reason for that. I appreciate and take all feedback to heart it's just that CodeEval only uses Java 7. So, please don't think I'm intentionally disregarding the excellent advice I receive and nonetheless welcome.


texts:
As a beginner, in order to cement my knowledge of functions in Python, I’ve prepared this Jupyter notebook First-Class Functions. The code in it is working, but before moving on to closures and decorators I would like you to comment on my code please.

def cube(x):
    return x ** 3

cube_two = cube(2)    # Call the function, set cube_two to the value returned

print(cube)            # It says cube is a function
print(cube_two)       # The value stored in cube_two

# <function cube at 0x010E71E0>
# 8

Returned values as list elements and dict values:

nums = [4, cube(4), cube(4) / cube(4) ** 0.5]    # returned values as list elements
print(nums)

cube_dict = {'two_cubed': cube(2), 'five_cubed': cube(5)}   # as dict values
print(cube_dict)

# [4, 64, 8.0]
# {'two_cubed': 8, 'five_cubed': 125}

Setting a variable to the cube() function:

make_cube = cube    # Take out those parentheses

print(cube)
print(make_cube)    # make_cube points to the cube() function

# <function cube at 0x010E71E0>
# <function cube at 0x010E71E0>

the variable make_cube can be used as a function, like so:

print(cube)
print(make_cube(4))

# <function cube at 0x010E71E0>
# 64

map taking a function (int) as an argument:

str_nums = ['1', '2', '3']
one, two, three = map(int, str_nums)  # similar to [int(n) for n in str_nums] which is pythonic

print(str_nums)
print([one, two, three])

# ['1', '2', '3']
# [1, 2, 3]

reduce is another example: it applies a function of two arguments cumulatively to the items of an iterable.

from functools import reduce

cumu_diff = reduce(lambda x, y: x - y, [3, 2, 1])    # cumulative difference
print(cumu_diff)

# 0

Creating a map-like function (well, kind of).

def map_it(func, seq):    # func (without parentheses) as an argument
    for x in seq:
        yield func(x)

str_nums = ['1', '2', '3']
one, two, three = map_it(int, str_nums)    # same as map(int, str_nums)

print([one, two, three])

# [1, 2, 3]

Returning a function from another function:

def greet(name):

    def print_message():
        print("Hello, " + name + "!")     # print_message() gets the name from greet()

    return print_message                  # returning the function, not calling it

greet_et = greet('E.T.')    # greet_et points to print_message()

print(greet)
print(greet_et)
print(greet_et())

# <function greet at 0x01090C90>
# <function greet.<locals>.print_message at 0x010B36A8>
# Hello, E.T.!
# None

Here's another example.

def make_paragraph(tag):

    def wrapper(text):
        return '<{0}>{1}</{0}>'.format(tag, text)

    return wrapper

para_one = make_paragraph('p')

print(para_one('This is a small paragraph.'))   # returns '
This is a small paragraph.
'

#
This is a small paragraph.