texts: Exporting objects in various formats while reporting progress

texts:
Description
A WinForms application has a function to export objects of the following type, in various formats:
class Item
{
    public int id { get; set; }
    public string description { get; set; }
}

At the click of a button in a window, a SaveFileDialog is shown, and currently it provides the option to save the data in .txt, .csv or .xlsx format. Since there are sometimes hundreds or thousands of objects, and the UI should not freeze up, a Task is used to run this operation. This implementation works, but could be improved.
Code
public partial class ExportWindow : Form
{
    // objects to be exported
    List<Item> items;

    // event handler for the "Export" button click
    private async void exportButton_click(object sender, System.EventArgs e)
    {
        SaveFileDialog exportDialog = new SaveFileDialog();
        exportDialog.Filter = "Text File (*.txt)|*.txt|Comma-separated values file (*.csv)|*.csv|Excel spreadsheet (*.xlsx)|*.xlsx";
        exportDialog.CheckPathExists = true;
        DialogResult result = exportDialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            var ext = System.IO.Path.GetExtension(saveExportFileDlg.FileName);

            try
            {
                // update status bar
                // (it is a custom control)
                statusBar.text("Exporting");

                // now export it
                await Task.Run(() =>
                {
                    switch (ext.ToLower())
                    {
                        case ".txt":
                            saveAsTxt(exportDialog.FileName);
                            break;

                        case ".csv":
                            saveAsCsv(exportDialog.FileName);
                            break;

                        case ".xlsx":
                            saveAsExcel(exportDialog.FileName);
                            break;

                        default:
                            // shouldn't happen
                            throw new Exception("Specified export format not supported.");
                    }
                });
            }
            catch (System.IO.IOException ex)
            {
                 statusBar.text("Export failed");
                 logger.logError("Export failed" + ex.Message + "\n" + ex.StackTrace);

                 return;
            }
        }
    }

    private delegate void updateProgressDelegate(int percentage);

    public void updateProgress(int percentage)
    {
        if (statusBar.InvokeRequired)
        {
            var d = updateProgressDelegate(updateProgress);
            statusBar.Invoke(d, percentage);
        }
        else
        {
            _updateProgress(percentage);
        }
    }

    private void saveAsTxt(string filename)
    {
        IProgress<int> progress = new Progress<int>(updateProgress);

        // save the text file, while reporting progress....
    }

    private void saveAsCsv(string filename)
    {
        IProgress<int> progress = new Progress<int>(updateProgress);

        using (StreamWriter writer = StreamWriter(filename))
        {
            // write the headers and the data, while reporting progres...
        }
    }

    private void saveAsExcel(string filename)
    {
        IProgress<int> progress = Progress<int>(updateProgress);

        // EPPlus magic to write the data, while reporting progress...
    }
}

Questions
How can this be refactored to make it more extensible? That is, if I wanted to add support for more file types, make it easy and quicker to modify. The switch statement could get very long. Essentially, how to comply with the Open/Closed principle?


texts: Refactoring multiple boolean conditions?

texts:
I have a Predicate which takes employee object.
Predicate<Employee> getPredicate() {
    return emp -> filter(emp);
}

Now the filter method is very complex, it calls four other methods which returns true/false if all the conditions are true, the predicate will return true.
private boolean filter(Employee employee) {
    String employeeJSONString = employeeToString(employee);
    return filterBasedOnConsistAge(employeeJSONString) &&
           filterBasedOnConsistGender(employeeJSONString) &&
           filterBasedOnConsistNationality(employeeJSONString) &&
           filterBasedOnConsistHandicap(employeeJSONString);
}

private String employeeToString(Employee employee) {
    // converts domainObject to a formatted string, it's a business requirement
}

There are five-line methods, that are linked using logical AND. But the problem here is, the chaining is looking clean. is there a way to improve this logic?


texts: Squeezing decorators into functional extensions

texts:
When you try to use several decorators it can get ugly pretty quickly and you'll end up with:

new RelativeFileProvider(
  new SystemVariableFileProvider(
      new PhysicalFileProvider()
  ),
  "%TEMP%"
);

or if you prefer one-liners then like that:

new RelativeFileProvider(new SystemVariableFileProvider(new PhysicalFileProvider()), "%TEMP%");

I thought I turn them into extensions and make them play along nicer in a functional way so I created a couple of helper methods that allow me to do this:

new PhysicalFileProvider()
    .DecorateWith(SystemVariableFileProvider.Create())
    .DecorateWith(RelativeFileProvider.Create("%TEMP%"));

Don't be confused about the empty classes. To be able to experiment without being distracted by the implementations I extracted the interface and the classes from my question about Multiple file access abstractions
 that I'm going to use this pattern for. They all have implementations that have been already reviewed there. This question is about the additional decorator helper APIs and they are implementation-netural.

Here are the types I used:

Version 1 - with an exntesion

interface IFileProvider
{

}

class PhysicalFileProvider : IFileProvider
{
    public static PhysicalFileProvider Create()
    {
        return new PhysicalFileProvider();
    }
}

class RelativeFileProvider : IFileProvider
{
    public RelativeFileProvider(IFileProvider fileProvider, string basePath)
    {

    }

    public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)
    {
        return decorable => new RelativeFileProvider(decorable, basePath);
    }
}

class SystemVariableFileProvider : IFileProvider
{
    public SystemVariableFileProvider(IFileProvider fileProvider)
    {

    }

    public static Func<IFileProvider, SystemVariableFileProvider> Create()
    {
        return decorable => new SystemVariableFileProvider(decorable);
    }
}

static class FileProviderExtensions
{
    public static IFileProvider DecorateWith(this IFileProvider decorable, Func<IFileProvider, IFileProvider> createDecorator)
    {
        return createDecorator(decorable);
    }
}

Version 2 - with an interface

This API forces each type to implement the DecorateWith method instead of relying on an extension.

interface IDecorable<T>
{
    T DecorateWith(Func<T, T> createDecorator);
}

interface IFileProvider : IDecorable<IFileProvider>
{

}

class PhysicalFileProvider : IFileProvider, IDecorable<IFileProvider>
{
    public static PhysicalFileProvider Create()
    {
        return new PhysicalFileProvider();
    }

    public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
    {
        return createDecorator(this);
    }
}

class RelativeFileProvider : IFileProvider, IDecorable<IFileProvider>
{
    public RelativeFileProvider(IFileProvider fileProvider, string basePath)
    {

    }

    public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)
    {
        return decorable => new RelativeFileProvider(decorable, basePath);
    }

    public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
    {
        return createDecorator(this);
    }
}

class SystemVariableFileProvider : IFileProvider, IDecorable<IFileProvider>
{
    public SystemVariableFileProvider(IFileProvider fileProvider)
    {

    }

    public static Func<IFileProvider, SystemVariableFileProvider> Create()
    {
        return decorable => new SystemVariableFileProvider(decorable);
    }

    public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
    {
        return createDecorator(this);
    }
}

And these are the whys about the factories:

I chose static factory methods over free arguments to keep parameter names and their order.
I chose them also to avoid new.

What do you think of this system? Do you prefer one version over the other? Can this be made even more convinient? Or would you say this is madness?


texts:
How may this code be improved upon, the user inputs array of specified length and replaces each element that is smaller than the mean of the first and last element with the mean.

Is there a better way to pass the array to the function (ref/ptr, etc.), or more efficient way to manage memory (when handling array)?

I know the vector container from STL is ideal but just wanted to gain some insight on fundamentals.

#include <iostream>
using namespace std;

void replaverage(int arr[], size_t n){
    cout<<"Enter array length"<<endl;
    cin>> n;
    for(int i=0; i<n; i++){
        cout<<"Enter the numbers"<<endl;
        cin>>arr[i];
        cout<<endl;
    }
    int f=arr[0];
    int l=arr[n-1];
    double av=(f+l)/2;
    for(int j=0; j<n; j++){
        if(arr[j]<av){
            arr[j]=av;
        }
    }
    for (int i=0; i<n; i++){
        cout<<arr[i]<< " ";}
}

int main(int argc, char* argv[]){
    size_t x=10;
    int arr[x];
    replaverage(arr,x);
    return 0;
}


texts: Filtering units by a dynamic Lambda expression

texts:
I have a simple if statement which, based on user input, determines which expression is going to be utilized. It looks like it can be done better.

Func<Unit, bool> exp;
if (onlyChildren)
    exp = u => u.PhaseId == id;
else
    exp = u => u.PhaseId != id;

var unitGroups = _db.Units.Where(exp).GroupBy(m => m.UnitTemplate, (m, group) => new UnitTemplateZoneVm()
{
    Id = m.Id,
    Units = group.ToList()
}).ToList();


texts:
Since Hacker News launched their official API, I started working on Python wrapper for it. API v0 is fairly simple, you send a GET request with hacker news story's ID or user id, it returns data in JSON.

Here I do the same using requests library and return specific object like Item for news story or comment and User for a user on Hacker News.

All source can be found here.

#!/usr/bin/env python

__all__ = [
    'User',
    'Item',
    'HackerNews',
    'InvalidAPIVersion',
    'InvalidItemID',
    'InvalidUserID']

"""
haxor
Unofficial Python wrapper for official Hacker News API
"""

import datetime
import json

import requests

from settings import supported_api_versions
# supported_api_versions = {'v0': 'https://hacker-news.firebaseio.com/v0/'}

class InvalidItemID(Exception):
    pass

class InvalidUserID(Exception):
    pass

class InvalidAPIVersion(Exception):
    pass

class HackerNews(object):

    def __init__(self, version='v0'):
        try:
            self.base_url = supported_api_versions[version]
        except KeyError:
            raise InvalidAPIVersion

    def _get(self, url):
        response = requests.get(url)
        if response.status_code == requests.codes.ok:
            return response
        else:
            raise Exception('HTTP Error: {}'.format(response.status_code))

    def get_item(self, item_id):
        response = self._get('{0}item/{1}.json'.format(self.base_url, item_id))

        if not response.json():
            raise InvalidItemID

        return Item(response.json())

    def get_user(self, user_id):
        response = self._get('{0}user/{1}.json'.format(self.base_url, user_id))

        if not response.json():
            raise InvalidUserID

        return User(response.json())

    def top_stories(self, limit=None):
        response = self._get('{}topstories.json'.format(self.base_url))
        return response.json()[:limit]

    def get_max_item(self):
        response = self._get('{}maxitem.json'.format(self.base_url))
        return response.json()

class Item(object):

    """
    Represents stories, comments, jobs, Ask HNs and polls
    """

    def __init__(self, data):
        self.item_id = data.get('id')
        self.deleted = data.get('deleted')
        self.item_type = data.get('type')
        self.by = data.get('by')
        self.submission_time = datetime.datetime.fromtimestamp(
            data.get(
                'time',
                0))
        self.text = data.get('text')
        self.dead = data.get('dead')
        self.parent = data.get('parent')
        self.kids = data.get('kids')
        self.url = data.get('url')
        self.score = data.get('score')
        self.title = data.get('title')
        self.parts = data.get('parts')
        self.raw = json.dumps(data)

    def __repr__(self):
        return '{0}: {1}'.format(self.item_id, self.title)

class User(object):

    """
    Represents a hacker i.e. a user on Hacker News
    """

    def __init__(self, data):
        self.user_id = data.get('id')
        self.delay = data.get('delay')
        self.created = datetime.datetime.fromtimestamp(data.get('time', 0))
        self.karma = data.get('karma')
        self.about = data.get('about')
        self.submitted = data.get('submitted')
        self.raw = json.dumps(data)

    def __repr__(self):
        return '{0}: {1}'.format(self.user_id, self.karma)


texts:
Have I made any obvious mistakes?
Is this code clean?
Is there a better way to do this in python?

# -*- coding: utf-8 -*-
import feedparser
from feedgen.feed import FeedGenerator
from random import shuffle
from feedformatter import Feed
import time
from datetime import datetime

tstart = datetime.now()
# Set the feed/channel level properties
# ----------------------------------- #
chanTitle = 'Feed Merger'
chanLink = 'http://server.com/feed'
chanAuthor = 'Bob Dylan'
chanDescription = 'Brain Food'
# ----------------------------------- #
# Apply feed/channel level properties
# ----------------------------------- #
feed = Feed()
feed.feed["title"] = chanTitle
feed.feed["link"] = chanLink
feed.feed["author"] = chanAuthor
feed.feed["description"] = chanDescription
# ----------------------------------- #
urls = list(set(open('urls.txt', 'r').readlines()))
shuffle(urls)
extract_entries = lambda url: feedparser.parse(url).entries
addEntries = lambda entries: [feed.items.append(entry) for entry in entries]
merg = lambda urls: [addEntries(extract_entries(url)) for url in urls]
shuffle(feed.entries)
save = lambda outfile: feed.format_rss2_file(outfile)
merg(urls)
save('feed.xml')
tend = datetime.now()
runtime = tend - tstart
print "Runtime > %s" % (runtime)
print "Merged  > %d items" % (len(feed.entries))


texts:
I wanted to make a library thing which provides specific extensions for collections/collection-like containers in kotlin:

fun <T> Collection<T>.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }

fun String.extendEntries(length: Int) = this.toList().extendEntries(length)
fun <T> Array<T>.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun CharArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun BooleanArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun DoubleArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun IntArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun LongArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun FloatArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun ByteArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun ShortArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }

Is the above a good way to do it if I want to cover arrays?

Exampe usage:

val a = intArrayOf(1, 2, 3)
println(a.extendEntries(5))

Outputs:

[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]


texts:
I'm working on this snippet of code within a PHP file. The upload function is working but I suspect it is not secure. I move all the files into an upload folder within the site folder. I think that some of this could be tricked into uploading malicious files but I'm not sure how it would be done and more importantly, how to adjust this code to be more secure.

Basically what I'm trying to do is:

Allow Word and PDF documents to be uploaded to a sitefolder's upload folder.
Append the date to the filename.
Move the file from the PHP temporary directory into the destination direction mentioned in step 1.

Other note: I've read on some similar threads that files should not be uploaded to the wwwroot folder, but I'm not sure why that is the case. I understand that if a hacker gains access to some folder X and Y resides within X, that the hacker will have access to X and Y, but would the hacker necessarily be able to gain access to files up the www root directories?

<?php

$allowedExts = array("docx", "DOCX", "DOC", "doc","pdf","PDF");
$temp = explode(".", $_FILES["file".$x]["name"]);
$extension = end($temp);
$destinationdirectory= "C:\inetpub\wwwroot\sitefolder\upload\\";
$date=date("m-d-Y-his", time());
$originalname=(string)$_FILES["file".$x]["name"];
$newfilename=$date." ".$originalname;
$newfilename=preg_replace('/\s+/', '', $newfilename);//Need to remove all white space to make url friendly
//Validation of files types
if ((($_FILES["file".$x]["type"] == "application/pdf") || ($_FILES["file".$x]["type"] == "application/msword")) && in_array($extension, $allowedExts)) {
      if ($_FILES["file".$x]["error"] > 0) {
            echo "Return Code: " . $_FILES["file".$x]["error"] . "<br>";
      } else {
          if (file_exists($destinationdirectory . $_FILES["file".$x]["name"])) {
              echo $_FILES["file".$x]["name"] . " already exists. ";
          } else {
              move_uploaded_file($_FILES["file".$x]["tmp_name"], destinationdirectory . $newfilename);
              //Now that the file is validated, renamed and uploaded to the server, get the vars together to store them inside of the array.
              $filelocation="http://mywebsite.com/upload/".$newfilename;
          }//File moving success loop.
      }
} //IF FILETYPE IS CORRECT AND ALLOWED.
else {
    //Upload error or no file chosen for upload, add it to the array.
    array_push($uploadserrors,$actiondoctypesindex[$x]);
}

?>


texts:
Project Euler #3:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Here is my solution:
public class PrimeFactorFinder {

    private static final long NUMBER = 600851475143L;

    public static void main(String[] args) {
        long time = System.nanoTime();
        long result = 0;
        for(int i = 2; i < NUMBER; i++) {
            if(NUMBER % i == 0 && isPrime(NUMBER / i)) {
                result = NUMBER / i;
                break;
            }
        }
        System.out.println("Result: " + result + "\nTime required to calculate in nanoseconds: " + (System.nanoTime() - time));
    }

    private static boolean isPrime(long l) {
        for(long num = 2, max = l / 2 ; num < max; num++) {
            if(l % num == 0) {
                return false;
            }
        }
        return true;
    }

}

Output:

 Result: 6857
 Time required to calculate in nanoseconds: 1154999669

Questions:

I am especially annoyed with the isPrime() method. Is there a better way to do this? How?
Any general comments?


texts:
I'm doing a BattleShip game in javascript with iio engine.

I'm trying to play against a computer so I have to put a random position for the ships (I hope you know the game :) ).

I have 5 ships that have to be placed in a grid (10x10). The problem is that the function is pretty slow, and sometimes the page don't get load at all.

I want to know if there are some emprovement for the speed of these function, I'm a little bit newbie :D

function posShips(size){
    // var size -> size of the ship
    var isOk = false; // flag var to check if the ship is in a right position
    var isOk2 = true; // flag var, become false if the cell is already fill with another ship
    var i;
    var j;
    var side; // horizontal or vertical
    while(!isOk){
        i = iio.getRandomInt(1,11);
        j = iio.getRandomInt(1,11);
        side = iio.getRandomInt(0,2);
        if((side ? j : i)+size-1 < 11){ // Not out of the array
            for (var k = 0;  k < size; k++) { // Size of the ship
                if(side){
                    if(gridHit[i][j+k].stat == "empty"){ //If is empty put the ship
                        gridHit[i][j+k].stat = "ship";
                        gridHit[i][j+k].setFillStyle("red")
                    }else{ // If not empty
                        isOk2 = false; //Position is not good, do all the thing again.
                        for (var a = 0;  a < size; a++) { // Reset cell
                            gridHit[i][j+a].stat = "empty";
                        }
                        k = 10;
                    }
                }else{
                    if(gridHit[i+k][j].stat == "empty"){ //If is empty put the ship
                        gridHit[i+k][j].stat = "ship";
                        gridHit[i+k][j].setFillStyle("red")
                    }else{ // If not empty
                        isOk2 = false; //Position is not good, do all the thing again.
                        for (var a = 0;  a < size; a++) { // Reset cell
                            gridHit[i+a][j].stat = "empty";
                        }
                        k = 10;
                    }
                }
            };
            if(isOk2)
                isOk = true;
        }
    }
}


texts: Web API wrapper design and sharing EF database context

texts:
I'm trying to keep my sanity while working with a legacy winforms application that uses an web api, both maintained by my team.

In the past we have multiple cases of methods using wrong api endpoints, or even having different names in both client and server implementation, so we came with the idea of having an interface to represent the API available methods:

public interface IUser
{
    Task<List<Data>> Fetch(string login);
}

Using this approach, the server API implementation is pretty straightforward:

public class UserController : MyController<User>
{
    [HttpGet, ResponseType(typeof(List<Data>))]
    public async Task<IHttpActionResult> Fetch(string login)
    {
        var business = GetBusiness();
        var result = await business.Fetch(login);
        return Ok(result);
    }
}

public class User: MyBusiness, IUser
{
    public async Task<List<Data>> Fetch(string login)
    {
        using (var context = GetContext(...))
        {
            var result = await context...;
            result.SomethingElse = await SomethingElse();
            return result;
        }
    }

    public async Task<Foo> SomethingElse()
    {
        using (var context = GetContext(...))
        {
            return await ...;
        }
    }
}

In the client side, we don't want the presentation layer dealing with web api request URL formatting, so we encapsulate those details inside a web api class wrapper which implements the same interface:

public class User: IUser
{
    private User()
    {
    }

    private static class ApiConstants
    {
        public const string Fetch = "api/{0}/User/Fetch";
    }

    public static readonly User Data = new User();

    public async Task<List<Data>> Fetch(string login)
    {
        var result = new List<Data>();
        try
        {
            result = await ApiHelper.GetAsync<List<Data>>(
                User.ApiConstants.Fetch, new NameValueCollection
                {
                    {"login", login},
                });
        }
        catch (Exception ex)
        {
            Logger.Error(ex);
        }
        return result;
    }
 }

Whenever I do need to use this in the presentation layer, I would do something like this:

private void ok_Click(object sender, EventArgs e)
{
    var data = Extensions.BlockWithoutLockup(
        async () => await Api.User.Data.Fetch(login));

    // do stuff
}

Things there are currently bugging me:

Swallowing the error in the client api wrapper;

fixing this involves creating a generic error handling to tell apart business validations from infrastructure issues.
We're planning to throw the exception all way to the interface and it will take the proper action based on the exception type.

Having the ApiConstants inner class

We're considering using StackTrace to get the caller method/class and compose the URL but StackTrace doesn't play nice with async calls
as having that constant could be useful for dealing with endpoint naming exceptions, we don't feel like we should provide such level of customization by now

Have to type several times the API call return type:

fair occurrences:

in the common interface
in the API business implementation
in the wrapper method declaration

in the Controller ResponseType attribute, for generating dynamic documentation help pages
in the result variable within the wrapper method
passing the same T to the ApiHelper.GetAsync method

Initializing the database context several times in the API layer:

we're considering create a MyBusiness.Context protected property

using this we could create it only once and pass it through dependant calls;
this would also provide support to transactions down in the road


texts: Daubechies wavelet and scaling filters: Is there a better way?

texts:
I have computed the Daubechies wavelet and scaling filters in float, double, long double, and quad precision, and now want to expose these filters in a usable API. My problem is as follows: I want to make sure that these filters are correct to every single bit, so I wrote them as hexadecimal floating point literals. Then I wanted to get them to parse in the correct format, so I need to append literals like f, L, or Q. But to get them to parse as the correct type, I need to duplicate them over and over, resulting in a monstrous #include file, given here

The file is too big to place in the question, but here's a short sample:

#ifndef BOOST_MATH_FILTERS_DAUBECHIES_HPP
#define BOOST_MATH_FILTERS_DAUBECHIES_HPP
#include <array>
#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/float128.hpp>
#endif
namespace boost::math::filters {

template <typename Real, unsigned p>
constexpr std::array<Real, 2*p> daubechies_scaling_filter()
{
    static_assert(sizeof(Real) <= 16, "Filter coefficients only computed up to 128 bits of precision.");
    static_assert(p < 25, "Filter coefficients only implemented up to 24.");
    if constexpr (p == 1) {
        if constexpr (std::is_same_v<Real, float>) {
            return {0x1.6a09e6p-1f, 0x1.6a09e6p-1f};
        }
        if constexpr (std::is_same_v<Real, double>) {
            return {0x1.6a09e667f3bcdp-1, 0x1.6a09e667f3bcdp-1};
        }
        if constexpr (std::is_same_v<Real, long double>) {
            return {0xb.504f333f9de6484p-4L, 0xb.504f333f9de6484p-4L};
        }
        #ifdef BOOST_HAS_FLOAT128
        if constexpr (std::is_same_v<Real, boost::multiprecision::float128>) {
            return {0x1.6a09e667f3bcc908b2fb1366ea95p-1Q, 0x1.6a09e667f3bcc908b2fb1366ea95p-1Q};
        }
        #endif
    }
    if constexpr (p == 2) {
        if constexpr (std::is_same_v<Real, float>) {
            return {0x1.ee8dd4p-2f, 0x1.ac4bdep-1f, 0x1.cb0bfp-3f, -0x1.0907dcp-3f};
        }
        if constexpr (std::is_same_v<Real, double>) {
            return {0x1.ee8dd4748bf15p-2, 0x1.ac4bdd6e3fd71p-1, 0x1.cb0bf0b6b7109p-3, -0x1.0907dc193069p-3};
        }
        if constexpr (std::is_same_v<Real, long double>) {
            return {0xf.746ea3a45f8a62ap-5L, 0xd.625eeb71feb8557p-4L, 0xe.585f85b5b8845bdp-6L, -0x8.483ee0c9834834cp-6L};
        }
        #ifdef BOOST_HAS_FLOAT128
        if constexpr (std::is_same_v<Real, boost::multiprecision::float128>) {
            return {0x1.ee8dd4748bf14c548b969de58fap-2Q, 0x1.ac4bdd6e3fd70aae9f48d8a63d1bp-1Q, 0x1.cb0bf0b6b7108b79b4bf11d08b16p-3Q, -0x1.0907dc1930690697b13714fd4a15p-3Q};
        }
        #endif
    }
...

template<class Real, size_t p>
std::array<Real, 2*p> daubechies_wavelet_filter() {
    std::array<Real, 2*p> g;
    auto h = daubechies_scaling_filter<Real, p>();
    for (size_t i = 0; i < g.size(); i += 2)
    {
        g[i] = h[g.size() - i - 1];
        g[i+1] = -h[g.size() - i - 2];
    }
    return g;
}

Is there a way to only state the filter coefficients once, with the maximum allowed precision, and have the compiler parse it as the user's desired type, and preserve the constexpr?

Is keep the filter coefficients constexpr a sensible desideratum here? (I'm not even sure that I should make p a template parameter. . .) If so, note that the scaling filters are constexpr, but the wavelet filters are not. Is there a way around that?

C++17 solutions are acceptable; C++20 solutions are  . . . less so, but if they can be shown to dramatically improve the code that's what language updates are for correct?


texts: Replace every letter in the string with the letter following it in the alphabet and capitalize vowels

texts:
Any suggestions to make this code better(efficient, style, etc.)?

I also want to know if there is a simpler way to check if a character is a vowel or not because I had to copy and paste "element == (vowel)" like 4 times.

int isVowel(char element)
{
    if(element == 'a'||element == 'e'||element == 'i'||element == 'o'||element == 'u')
    {
        return 0;
    }else
    {
        return 1;
    }
}
std::string LetterChanges(const std::string& str)
{
    std::vector<char>cstr(str.c_str(),str.c_str()+str.size());
    for(auto &element : cstr)
    {
        if((element >= 'A' && element < 'Z')||(element >='a' && element <   'z'))
        {
            element = element+1;

            if(isVowel(element)==0)
            {
                element = std::toupper(element);
            }

        }
    }
    std::string ss(cstr.begin(),cstr.end());
    return ss;
}


texts:
I wrote a class with this function. Can I improve my code performance in the bottom of the function? I don't like the while loops!

public function loadFields(array $fields, $as_object = Config::FIELDS_AS_OBJECT) {
        $connection = $this->connection;
        $sql = "SELECT ".implode(",", $fields)." FROM ".$this->table." WHERE lang = ?";
        if (!($stmt = $connection->prepare($sql))){
            throw new MysqliPrepareException($connection);
        }
        if(!($stmt->bind_param('s',$this->lang))){
            throw new MysqliBindParamException($connection);
        }
        if(!$stmt->execute()){
            throw new MysqliExecuteException($connection);
        }
        $stmt->store_result();
        $variables = array();
        $data = array();
        $meta = $stmt->result_metadata();
        while ($field = $meta->fetch_field()) {
            $variables[] = &$data[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $variables);
        $i = 0;
        while ($stmt->fetch()) {
            $array[$i] = array();
            foreach ($data as $k => $v) {
                $array[$i][$k] = $v;
            }
            $i++;
        }
        $array = (!isset($array[1]) ? $array[0] : $array);
        return ($as_object == true ? (object) $array : $array);
}


texts: Mini Test testing save on one and many trips

texts:
I know there is a balance to be struck between writing dry code and damp code but I have the feeling that this is a bit too repeative. Is there a terse yet self explainatory way to rewrite these tests?

class TripTest < ActiveSupport::TestCase
  def setup
    @trip = trips(:one)
    @invoice = invoices(:one)
  end

  test 'trip can save' do
    trip = Trip.new
    trip.departure_date = "2040-03-24"
    trip.depart_airport = "DHW"
    trip.arrive_airport = "ABC"
    trip.invoice_id = 123534

    assert trip.save, "Error message: #{trip.errors.full_messages}"
  end

  test "one invoice can have multiple trips" do
    trip = Trip.new
    trip.departure_date = "2040-03-24"
    trip.depart_airport = "DHW"
    trip.arrive_airport = "ABC"
    trip.invoice_id = 123534
    @invoice.trips.push(trip)
    @invoice.save

    trip = Trip.new
    trip.departure_date = "2040-03-24"
    trip.depart_airport = "ICN"
    trip.arrive_airport = "XYZ"
    trip.invoice_id = 123534
    @invoice.trips.push(trip)
    @invoice.save

    assert @invoice.trips.size > 1
  end


texts: Updating a jquery progressbar via button clicks

texts:
I'm trying to get my progress bar animated. I'd like it to smoothly transition in between the starting and destination values, but only be initiated by clicking the continue button.

The code I currently have works great, but when clicking forward or backward, it brings you directly to the values:

//PROGRESS BAR
$("#progress").progressbar(
{
    value: 0
})
//UPDATING PROGRESS BAR WHEN CONTINUE BUTTON CLICKED
var currValue=0,toValue=0;
$("#cont").button().click(function()
{
    currValue = $("#progress").progressbar("value");
    if(currValue+25 <= 100)
    {
        toValue=currValue+25;
        animateProgress();
    }
});
//DECREASING PROGRESS BAR WHEN GO BACK BUTTON CLICKED
$("#back").button().click(function()
{
    currValue = $("#progress").progressbar("value");
    if(currValue-25 > 0)
    {
        toValue=currValue-25;
        animateProgress();
    }
});
});

function animateProgress() {
  if (currValue < toValue) {
    $("#progress").progressbar("value", currValue+1);
    currValue = $("#progress").progressbar("value");
    setTimeout(animateProgress, 4);
  }
  else if (currValue > toValue) {
    $("#progress").progressbar("value", currValue-1);
    currValue = $("#progress").progressbar("value");
    setTimeout(animateProgress, 4);
  }
}

I've seen a couple examples of animated progressbars, but none by clicking and stopping when a certain value was reached.

Think of it more like 4 individual "slides" and the progress bar showing you which slide you're on.

EDIT: here's the working fiddle...http://jsfiddle.net/ryanhagz/8u76B/20/

Anyone tried something similar?


texts:
I am extremely new at scheme and I am doing this problem from here:

  Write a procedure switch that takes a sentence as its argument and
  returns a sentence in which every instance of the words I or me is
  replaced by you, while every instance of  you is replaced by me except
  at the beginning of the sentence, where it’s replaced by I.  (Don’t
  worry about capitalization of letters.) Example:

    (switch ’(You told me that I should wake you up))  (i told you that you should wake me up)

I used additional functions from here.

(define (switchnext n)
(cond ((empty? n) '())
    ((or (equal? (first n) 'you) (equal? (first n) 'You)) (se 'me (switchnext (bf n))))
    ((or (equal? (first n) 'i) (equal? (first n) 'I) (equal? (first n) 'me)) (se 'you (switchnext (bf n))))
(else (se (first n) (switchnext (bf n))))))

(define (switch n)
(cond ((empty? n) '())
    ((or (equal? (first n) 'you) (equal? (first n) 'You)) (se 'i (switchnext (bf n))))
(else (se (first n) (switchnext (bf n))))))

I absolutely hate this code; I feel it is too repetitive. I think part of it is because I probably have no way of knowing when is beginning of a sentence. How can I improve this code?


texts:
Merge two sorted lists

# Input:    lst1 {List}
# Input:    lst2 {List}
# Output:   {List}
#
# Example: merge([1, 4, 7], [2, 3, 6, 9]) => [1, 2, 3, 4, 6, 7, 9]
#
def merge(items1, items2):
    # merge 2 list
    # divide and conquer
    # combine - step2
    ("\n"
     "    while left_index is not the length of left_array and right_index is not the length of right_array\n"
     "        if left_array[left_index] < right_array[right_index]\n"
     "            add left_array[left_index] to merged array\n"
     "            left_index + 1\n"
     "        else\n"
     "            add right_array[right_index] to merged_array\n"
     "            right_index + 1 ")
    # if we've passed the end of either list, then extend the sorted list
    # with what remains in the other
    left_pointer = 0
    right_pointer = 0
    sorted_list = []

    while len(sorted_list) < len(items1) + len(items2):
        left_item = items1[left_pointer]
        right_item = items2[right_pointer]
        if left_item < right_item:
            sorted_list.append(left_item)
            left_pointer += 1
        else:
            sorted_list.append(right_item)
            right_pointer += 1

        if right_pointer >= len(items2):
            sorted_list.extend(items1[left_pointer:])
            break
        if left_pointer >= len(items1):
            sorted_list.extend(items2[right_pointer:])
            break

    return sorted_list

test cases that i am working on

print('merge tests')
test_count = [0, 0]

def test():
    results = merge([1, 4, 7], [2, 3, 6, 9])
    return (len(results) == 7 and
            results[0] == 1 and
            results[1] == 2 and
            results[2] == 3 and
            results[3] == 4 and
            results[4] == 6 and
            results[5] == 7 and
            results[6] == 9)

expect(test_count, 'should return [1, 2, 3, 4, 6, 7, 9] when merging [1, 4, 7]', test)

def test():
    results = merge([], [2, 3, 6, 9])
    return (len(results) == 4 and
            results[0] == 2 and
            results[1] == 3 and
            results[2] == 6 and
            results[3] == 9)

expect(test_count, 'should handle inputs when left argument is empty array', test)

def test():
    results = merge([1, 4, 7], [])
    return (len(results) == 3 and
            results[0] == 1 and
            results[1] == 4 and
            results[2] == 7)

expect(test_count, 'should handle inputs when right argument is empty array', test)

def test():
    results = merge([], [])
    return len(results) == 0

expect(test_count, 'should handle two empty arrays as inputs', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')

class TestObject(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __lt__(self, other):
        return self.x < other.x
    def __str__(self):
        return "LTO (%d, %d)" % (self.x, self.y)


texts: Getting the character index of recurring substring

texts:
I created this function that allows you to declare a string, then multiple instances of a substring. This uses a hash map to keep track of strings that have already been searched for and upon each call of its returning function will give you the next instance of that substring.

I'm wondering if there's a way to do this without crypto. I have the option of applying the strings as a object property but I didn't want to overload memory with those.

I'm not sure if there's a native JavaScript way to do this, either, so I'm open to suggestions of native code or other libraries that achieve this.

var crypto = require('crypto')
var S = require('underscore.string')
var _ = require('lodash')

/** returns a md5 hash of the content */
function getHash (content) {
  var shasum = crypto.createHash('md5')
  return shasum.update(content).digest('hex')
}

function multiIndexOf (s) {
  var map = []
  return function (ss) {
    var hash = getHash(ss)
    var indexes = indexesOf(s, ss)
    var countMap = _.countBy(map)
    var instance = countMap[hash] || 0
    map.push(hash)
    return indexes[instance]
  }
}

function indexesOf (s, ss) {
  var instances = S.count(s, ss)
  return _.chain(instances)
  .range()
  .reduce(function (indexes, instance) {
    var lastIndex = _.last(indexes)
    var start = (typeof lastIndex === 'undefined') ? 0 : lastIndex + ss.length
    var index = s.indexOf(ss, start)
    indexes.push(index)
    return indexes
  }, [])
  .value()
}

var find = multiIndexOf('hello world, hello darling')

console.log(find('hello')) // => 0
console.log(find('hello')) // => 13


texts: Shift vowels towards the end of a Single Linked List

texts:
We have a linklist which is made of alphabets. We have to shift the vowels towards the end of the linklist, without changing the order in which they appear. So,

A->C->E->F->G->O

should become

C->F->G->A->E->O

This is the code I have written

#include<iostream>

using namespace std;

struct node
{
    char ch;
    node *next;
};

void enqueue (node **head, node **tail, char val)
{
    node *newn = (node *)malloc(sizeof(node));
    newn->ch = val;
    newn->next = NULL;

    if (*head == NULL)
    {
        *head = newn;
        *tail = newn;
    }

    (*tail)->next = newn;
    (*tail) = newn;

}

void print (node *head)
{
    while (head!=NULL)
    {
        cout<<head->ch<<" ";
        head = head->next;
    }
    cout<<endl;
}

bool isVowel (char ch)
{
    ch = ch | 32;

    if (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')
        return true;
    return false;

}

node* segregateVowels (node *head, node *tail)
{
    if (head == NULL || head->next == NULL)
        return head;

    node *temp = head;
    node *fin = tail;

    while (temp->next!=fin)
    {
        cout<<temp->ch<<" "<<fin->ch<<endl;
        if (isVowel(temp->next->ch))
        {
            node *shift = temp->next;
            temp->next = temp->next->next;
            tail->next = shift;
            shift->next = NULL;
            tail = shift;
        }
        else
            temp = temp->next;

    }

    if (temp->next!=NULL && isVowel(temp->next->ch))   /* Handling the case where the last element is a vowel   */
    {
        node *toMove = temp->next;
        temp->next = temp->next->next;
        tail->next = toMove;
        toMove->next = NULL;

    }
    else
        temp = temp->next;

    if (isVowel(head->ch))                  /*  Handling the case where the first element is a vowel    */
    {
        node *toMove = head;
        head = head->next;
        toMove->next = temp->next;
        temp->next = toMove;
    }

    return head;

}

int main()
{
    srand(time(NULL));

    node  *head = NULL, *tail = NULL;

    int i = 20;

    while (i>=0)
    {
        enqueue (&head, &tail, rand()%26+65);
        i--;
    }

    print(head);

    head = segregateVowels (head, tail);

    print(head);
}

Although this does seem to give me correct results, but I have to explicitly check for two edge cases. Also I feel there is a better solution for this problem or a better approach which I seem to be missing. The problem can be handled by creating two separate Link Lists too, and then joining them together. But what modifications do you suggest in the above program?


texts: Creating a repetitive string in Common Lisp

texts:
I needed to have a Lisp function that could produce a string of a certain length, created by repeated concatenations of a another string given as argument (so for example by giving 10 and "abc" I could obtain "abcabcabca"). I came up with a perverse idea of using a circular list of characters in combination with the loop macro. I'm not really aiming at great performance, but I'm wondering what are the disadvantages of this approach and what could be improved. I also added a switch indicating at which end to start filling the string.

(defun pad-with-string (n str &key (from-end nil))
  "Create a string of length `n` filled with repeating instances of `str`.
If `from-end` is T the string is filled from the end."
  (labels ((circular-list (&rest elements)
         (let ((cycle (copy-list elements)))
           (nconc cycle cycle))))
    (loop :repeat n
       :for c
       :in (apply #'circular-list (coerce (if from-end (nreverse str) str) 'list))
       :collect c
       :into chars
       :finally (return (coerce (if from-end (nreverse chars) chars) 'string)))))


texts:
I've written a little command-line utility for filtering log files. It's like grep, except instead of operating on lines it operates on log4j-style messages, which may span multiple lines, with the first line always including the logging level (TRACE, DEBUG etc.).

Example usage on a file short.log with contents like this:

16:16:12 DEBUG - Something happened, here's a couple lines of info:
 debug line
 another debug line
16:16:14 - I'm being very verbose 'cause you've put me on TRACE
  trace info
16:16:15 TRACE - single line trace
16:16:16 DEBUG - single line debug

logrep -f short.log DEBUG produces:

16:16:12 DEBUG - Something happened, here's a couple lines of info:
 debug line
 another debug line
16:16:16 DEBUG - single line debug

I think the main loop of the program could probably be simplified with some sort of parse and filter.

  file = fileinput.input(options.file)
  try:
    line = file.next()
    while True:
      if any(s in line for s in loglevels):
        if filter in line:
          sys.stdout.write(line)
          line = file.next()
          while not any(s in line for s in loglevels):
            sys.stdout.write(line)
            line = file.next()
          continue
      line = file.next()
  except StopIteration:
    return


texts:
I have a custom class to handle some triangle calculations that I am doing. For the most part I am happy with it, however, there is one aspect that I don't really trust. That is my implementation of HashCode.

Some quick information about my triangle- it has 3 Vector2 structs that represent points of two floats. This is an inbuilt class with the Unity engine but the simple version of it is that it is a struct with two floats and a couple math functions.

public class Triangle2D {
    public Vector2 point1;
    public Vector2 point2;
    public Vector2 point3;

    //... Some other methods that don't matter

    public override int GetHashCode() {
        var hashCode = -305700999;
        hashCode = hashCode * -1521134295 + (EqualityComparer<Vector2>.Default.GetHashCode (point1)
            + EqualityComparer<Vector2>.Default.GetHashCode (point2)
            + EqualityComparer<Vector2>.Default.GetHashCode (point3));
        return hashCode;
    }
}

The specific thing about this class that is special is that, it shouldn't matter what order points 1, 2 and 3 are in. If the points are shared, then the Triangle2D objects are the same. My equals function reflects that, but I worry that my hashCode function is not specific enough. Due to the additive nature of things, I suspect there could be a lot of collisions.

Is there some way that I could make the hashCode function have less collisions? Is it good enough as it is?

I use this object in a lot of hashSets to prevent duplicate triangles from getting listed.


texts:
As part of learning Haskell, I'm solving few problems, usually solved imperatively.

I've come up with a naive solution for the problem described here, which is to find a sequence in which to burst a row of balloons that will earn the maximum number of coins. Each time balloon \$i\$ is burst, we earn \$C_{i-1} \cdot C_i \cdot C_{i+1}\$ coins, then balloons \$i-1\$ and \$i+1\$ become adjacent to each other.

I would like to get few comments on the naive implementation below before solving it using dynamic programming.

What I'm looking for is:

Correctness
Program structure
Idiomatic Haskell
Any other higher order functions that can be used
Other optimizations that can be done

import qualified Data.List as List (permutations)

burst :: [Int] -> (Int, [Int])
burst = burstNaive

burstNaive :: [Int] -> (Int, [Int])
burstNaive = foldl (\a@(aVal,_) e@(eVal,_) -> if eVal > aVal then e else a) (0, []) . allOrders

allOrders :: [Int] -> [(Int, [Int])]
allOrders []       = []
allOrders l@(x:xs) = map (\p -> (flip withOrder l p, p))$ List.permutations [0..length l - 1]

type IndexOrder = [Int]
withOrder :: IndexOrder -> [Int] -> Int
withOrder []     _  = 0
withOrder (i:is) xs = left * (xs !! i) * right + withOrder adjust xss
  where
    xss = remAt i
    adjust = map (\index -> if index > i then index - 1 else index) is
    left  = if i == 0 then 1 else xs !! (i-1)
    right = if i == (length xs - 1) then 1 else xs !! (i+1)
    remAt index = let (f,s) = splitAt index xs in f ++ drop 1 s

Sample Output:

Prelude> :l Balloon.hs
[1 of 1] Compiling Balloon          ( Balloon.hs, interpreted )
Ok, one module loaded.
*Balloon> burst [3,1,5,8]
(167,[1,2,0,3])
*Balloon>


texts:
In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i would have to go through every view and add that link. I decide to make a partial view in layouts/_nav.haml which contains:

= link_to 'Home', root_path, :class => "btn #{active_page(root_path)}"
= link_to 'Sign in', sign_in_path, :class => "btn #{active_page(sign_in_path)}"
= link_to 'Account', account_path, :class => "btn #{active_page(account_path)}"

and then in my application_helper.rb i added:

def active_page(path)
  'active' if current_page?(path)
end

I know this isn't the best approach, is there any way to DRY up this solution or make it better. Im using bootstrap and i tried the simple-navigation gem but it wasn't that useful in my situation.


texts: Perl code that breaks a line after fixed number of columns

texts:
Here is a simple program that I created to print a file by breaking it after a fixed number of columns. I feel it can be optimized but not sure how. Any feedback is great.

#This is a simple program that takes a file and the limits the columns length to
#the number passed in as second argument
if ($#ARGV < 1) {
   printf("Usage: perl %s <name of the input file> <column length>\n", $0);
   exit(-1);
}
$file=$ARGV[0];
open(INFO, $file) or die("Could not open  file.");
$LINE_LENGTH = $ARGV[1];
$count = 0;
foreach $line (<INFO>)  {
    #print $line;
    if (length($line) <= $LINE_LENGTH) {
      printf("%s\n", $line);
    } else {
      $remaining_chars  = length ($line);
      $remaining_line = $line;
      while ($remaining_chars >= $LINE_LENGTH) {
          $cur_str = substr($remaining_line, 0, $LINE_LENGTH - 1 );
          printf("%s\n", $cur_str );
          $remaining_line = substr($remaining_line, $LINE_LENGTH - 1);
          $remaining_chars = $remaining_chars - length($cur_str);
      }
      printf("%s",$remaining_line );
    }
    if ($++counter == 2){
      last;
    }
}
printf("\n");
close(INFO);


texts: Path validation helper in a 'path input box'

texts:
I have a helper extension method that I use for path string validation. It looks as below. It's purpose is to work with network paths as well, so in case a network resource is not available, I do not want my applications to freeze, hence the specified timeout etc.

public static bool IsExistingFilePath(this string source, int numberOfAttempts = 3, int timeout = 300)
{
    for (int i = 0; i < numberOfAttempts; i++)
    {

        var task = new Task<bool>(() => File.Exists(source));
        task.Start();

        bool exists = task.Wait(timeout) && task.Result;
        if (exists)
        {
            return true;
        }
        else
            continue;
    }
    return false;
}

I also have a generic text box control, where I want to validate the provided path - and indicate if path is not correct. I want this auto text box validation to happen as infrequently as possible, because I don't want to run this loop of File.Exists() tasks when the path is being provided at the moment (e.g. user typing) etc.

My current approach is that I have a property that is bound to textbox text, and whenever it is updated, the validation is performed (update source trigger = property changed, mode = two way).

However, there is a problem, because property setter is not accessed when I paste into the text box nor when I write in it. I had set up a bunch of event handlers (OnPaste and LostFocus), but it's becoming unmanageable and appears not correct - and also appears to fire more times then necessary.

Then I thought about data validation from XAML with a ValidationRule class, but that actually works more or less like with KeyUp.

What would be the correct way to perform validation only when needed?

When text is pasted into box
When property is changed for whatever reason
When textbox is cleared
When text is changed (for instance, a proper path is pasted and a user decides to change it manually, e.g. use different drive)


texts:
Just did this simple application to check whether a string is a palindrome or not

#include <iostream>
#include <string>

using namespace std;

void main()
{
  string str;
  cout << "Enter a string: "; getline(cin, str);
  cout << "Your string is: "; cout << str << endl;
  cout << "The reverse of the string is: ";
  int counter = 0;
  for (int reverseIdx = str.size() - 1, forwardIdx = 0; reverseIdx >= 0 &&
  forwardIdx < str.size(); reverseIdx--, forwardIdx++)
  {
    cout << str[reverseIdx];
    if (str[reverseIdx] == str[forwardIdx])
    {
      counter++;
    }
  }
  cout << endl;
  if (counter == str.size())
  {
    cout << "The string is a Palindrome!" << endl;
  }
  else
  {
    cout << "The string is not a Palindrome." << endl;
  }
}

I'm getting a string from the user, then printing out the same string (I know it's not needed in such small programs). Then using a for loop to check if every character when reversed is equal to the same character when read normally.

Then using a counter variable I am checking if it's equal to the string size, if it's then it's palindrome.


texts:
I'm thinking about how to do a color transition for a line in WPF. I'm looking for this to be as simple and succinct as possible, and also the "correct" way in the WPF world.

This is what I have, taking the line from it's previous color to Colors.LightGreen in 0.1 seconds.

Line TargetLine = GetMyTargetLine();

var s = new Storyboard(){ Duration = new Duration(TimeSpan.FromSeconds(0.1f)) };
s.Children.Add(new ColorAnimation(Colors.LightGreen, s.Duration));
Storyboard.SetTarget(s.Children[0], TargetLine);
Storyboard.SetTargetProperty(s.Children[0], new PropertyPath("Stroke.Color"));
s.Begin();

And it is functional. Is this the proper way to do it in the WPF mindset? It just seems very clunky and verbose way to express what I want to do. Thoughts?

Edit:
With Snowbear's advice I can at least get it to 4 lines. The entire context of the storyboard is right here so I don't think it's a big deal to reference the only child by index. If it were any more complex than this I'd agree that it should be a named variable.

    Line TargetLine = GetMyTargetLine();

    var story = new Storyboard() { Children = { new ColorAnimation(color, new Duration(TimeSpan.FromSeconds(0.1))) } };
    Storyboard.SetTarget(story.Children[0], TargetLine);
    Storyboard.SetTargetProperty(story.Children[0], new PropertyPath("Stroke.Color"));
    story.Begin();


texts: BlockingQueue Implemetation using ReentrantLock

texts:
I was writing my own implementation of BlockingQueue for practice. I am trying to avoid using the synchronized keyword for the methods. I would instead like to use ReentrantLock.

What is the best way to write this implementation? I am not a Java ninja and would greatly appreciate if someone could pinpoint the errors in my code here and suggest better ways of implementing it.

public class MyBlockingQueue<T> {

private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
private Condition put_condition = put_lock.newCondition();
private Condition take_condition = take_lock.newCondition();

public MyBlockingQueue(AtomicInteger limit){
    queue = new LinkedList<T>();
    this.limit = limit;
}

public boolean put(T item) throws InterruptedException{
    put_lock.lockInterruptibly();
    try {
        while(queue.size() == limit.get()) {
            put_condition.await();
        }
        put_condition.signal();
        queue.add(item);
    } finally{
        put_lock.unlock();
    }

    return true;
}

public T take() throws InterruptedException{
    take_lock.lockInterruptibly();
    try {
        while (queue.size() == 0) {
            take_condition.await();
        }
        take_condition.signal();
        return queue.poll();
    } finally {
        take_lock.unlock();
    }
}


texts:
I have an Outlook Module that contains the VBA Code below. The VBA code opens an Excel Add-In called TMAPAddIn.xlam, which then displays a User Form. I exported the Module and gave it to other colleagues so that they can import it to their Outlook, this allowed them to make a custom button on their Outlook Quick Access Toolbar.

The code works great, takes about 5 seconds for the User Form to display and the code executes without a problem. The file is open as ReadOnly to ensure multiple users can run the add in at the same time, without ever having to worry about them modifying its contents. I would like to know if my code can be written better for speed / efficiency.

I've written this code only for purposes of ensuring everyone runs and opens the latest version of TMAPAddIn.xlam, unfortunately I don't have the resources or time to develop a COM Add-In.

Code

Sub LaunchTMAP()
Dim ExApp As Object
Set ExApp = CreateObject("Excel.Application")

Dim informationalBox As UserForm2
Set informationalBox = New UserForm2
informationalBox.Show 'letting the user know the workbook is downloading so they dont think Outlook froze

Dim ExWbk As Workbook
Set ExWbk = ExApp.Workbooks.Open("Z/TMAPAddIn.xlam", ReadOnly:=True) 'Z is a network drive

informationalBox.Hide

ExWbk.Application.Run "Module1.example"

ExApp = Nothing
ExWbk = Nothing
End Sub


texts:
I did not have experience with organization project and http-client. I suppose this is the right way. I have data-storage service where I store my data from server. This is data-storage:

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class DataStorageServiceService {

  // URL to web api

  private cateogryUrl = 'api/cateogry';  // URL to web api

  constructor(private http: HttpClient) {  }

  /** GET heroes from the server */
  getCategory(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
       map(products => {
          return Object.values(products)

        }),
      catchError(this.handleError('getProduct', []))
    )
  }
}

I have another service ProductsService where I call the getCategory() from method getCagegoryFromServer() and store the data in my list categoryModule.

This is service ProductsService:

@Injectable()
export class ProductsService  {
  cateogoryChanged = new Subject<CategoryModel[]>();

  private categoryModule: CategoryModel[] = [];

  constructor(private shopService: ShopCartService, private dataStorageServiceServiceta: DataStorageServiceService) { }

  getCagegoryFromServer() {
    this.dataStorageServiceServiceta.getCategory().subscribe((category :CategoryModel[]) => {

      this.categoryModule = category;
    })
  }

  getCategory() {
    return this.categoryModule.slice();
  }
}

And finally in my component ProductsComponent I call the method getCagegoryFromServer() and store the data in my list.

This is my ProductsComponent:

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit  {

  constructor(private productsService: ProductsService) {

   }

  ngOnInit() {
    this.productsService.getCagegoryFromServer();

  }

}

Does anyone know a better approach?


texts:
I'm looking to create a model in JavaScript. Here is an example of the code that I have so far:

// Person model
function Person(firstName, age) {
    // Check first name
    if (firstName) {
        if (typeof firstName === 'string') {
            this.firstName = firstName;
        }
        else throw new Error('The first name is not a string.');
    }
    else throw new Error('First name is a required field.');

    // Check age
    if (age) {
        if (typeof age === 'number') {
            if (age < 0) {
                throw new Error('The age provided is a negative.');
            }
            else {
                this.age = age;
            }
        }
        else throw new Error('The age provided is not a number.');
    }
    else throw new Error('Age is a required field.');
}

// Example usage
try {
    var joel = new Person('Joel', 30);
    console.log(joel);
}

catch(err) {
    console.log(err.message);
}

Is this an idiomatic approach to the solution? And if so is there a way in which I can improve it?


texts: Proper way to execute parameterized commands within a method

texts:
This method allows for the execution of parameterized commands within a DAL class, and I tried to make it as reusable as possible. It works well but it feels a bit verbose to me. Is there a way to simplify this or is it good as is?

/// <summary>
/// Retrieves records from the specified data source.
/// </summary>
/// <param name="query">The command to be executed.</param>
/// <param name="dataSrc">The data source to use for the command.</param>
/// <param name="parameters">Optional parameters for a parameterized command.</param>
/// <returns>A System.Data.DataTable containing the returned records.</returns>
public static DataTable GetRecords(string query, DelConnection dataSrc, params SqlParameter[] parameters)
{
    if (query == "") throw new ArgumentException("No command provided.", "query");
    string conString = Dal.GetConnectionString(dataSrc);

    using (SqlConnection con = new SqlConnection(conString))
    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        // Add parameters to command
        foreach (SqlParameter p in parameters)
        {
            cmd.Parameters.Add(p);
        }

        // Fill data table
        DataTable data = new DataTable();
        using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
        {
            adap.Fill(data);
        }
        return data;
    }
}   //// End GetRecords()


texts: C code to calculate the binary period of an integer

texts:
A non-empty zero-indexed string S consisting of Q characters is given.
  The period of this string is the smallest positive integer P such
  that:

  \$P ≤ Q/2\$ and \$S[K] = S[K+P]\$ for \$0 ≤ K < Q−P.\$

  So for example, for the integers 955,1651 and 102, convert the numbers
  to binary and the function should return 4,5,-1 respectively.

  The function returns -1 if there is no binary period for the given
  integer.

  The int n can be any value between 1 to 99999999

Here is the original code given in the challenge. The Challenge states that by modifying at most 2 lines, in the function solution, the existing bug should be fixed.

Here is my Solution, Can someone please review this?

int solution(int n)
{
    int d[30];
    int l = 0;
    int p;
    //convert the integer to binary
    while(n > 0)
    {
        d[l]= n %2 ;
        n = n /2;
        l++;
    }
    //compute the length of the resulting binary number
    //and that is stored in the variable l

    for(p = l/2; p >0; p--){
        int ok = 1;
        int i;
        for(i = 0; i < (l - l/2); i++){
            if(d[i] != d[i + p]){
                ok = 0;
                break;
            }
        }
        if(ok){
            return p;
        }
    }
    return -1;
}

 int main(int argc, char** argv) {
         printf("%d\n",solution(102));
         printf("%d\n",solution(955));
         printf("%d\n",solution(1651));
         return 0;
    }


texts:
This is new code based on some new ideas to reduce calls to is_bad_version. Refer to the previous version of the code discussion from here.

Any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated. My major idea is divide and conquer like a binary search/quick select.

Problem:

  You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Source code:

def is_bad_version(number):
    if number == 0:
        return False
    else:
        return True

def find_first_bad_index(numbers):
    start = 0
    end = len(numbers) - 1
    if start == end:
        if is_bad_version(numbers[start]):
            return start
        else:
            raise Exception('all good!')
    while start < end:
        mid = start + (end - start) / 2
        if is_bad_version(numbers[mid]):
            end = mid
        else:
            start = mid + 1
    if start == end:
        if is_bad_version(numbers[start]):
            return start
        else:
            raise Exception('all good!')

if __name__ == "__main__":
    print find_first_bad_index([0,0,0,1,1,1,1,1])
    print find_first_bad_index([0,0,0,0,0,0,0,1])


texts:
I wrote a version of decorator pattern in c++ as I wasn't able to find any good source of decorator pattern implementation in C++. I want to know if I implemented it correctly. Here is the code-

//implementing the pizza example in c++

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

class Pizza{
protected:
    string description = "";
    int cost = 0;
public:
    string getdescription(){
        return description;
    }
    int getcost(){
        return cost;
    }
};
//pizzas
class PeppyPaneer: public Pizza{
public:
    PeppyPaneer(){
        cost = 100;
        description = description + " PeppyPaneer";
    }
};
class Magharita: public Pizza{
public:
    Magharita(){
        cost = 200;
        description = description + " Magharita";
    }
};

//toppings
class Barbeque: public Pizza{
public:
    Barbeque(Pizza *pizza){
        cost = pizza->getcost() + 50;
        description = pizza->getdescription()+ " Barbeque";
    }
};

class Paneer: public Pizza{
public:
    Paneer(Pizza *pizza){
        cost = pizza->getcost() + 60;
        description = pizza->getdescription() + " Paneer";
    }
};

int main(){

    Pizza *pizza = new PeppyPaneer();
    cout << pizza->getcost() << " " << pizza->getdescription() << "\n";

    pizza = new Barbeque(pizza);
    cout << pizza->getcost() << " " << pizza->getdescription() << "\n";

    pizza = new Paneer(pizza);
    cout << pizza->getcost() << " " << pizza->getdescription() << "\n";

    return 0;
}


texts: Is there any flaws in my code which let me to save settings to a file?

texts:
This code allows me to save some settings from my small app to the text file which later I can retrieve by using substring and delimiter.

I wonder if there's any better way of doing this. If not, how could I make my code better or more efficient?

This is my code:

using System;
using System.IO;

namespace NameSpace
{
    class LastUsed
    {
        private static string dir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Folder\";
        private static string file = dir + @"\Settings.txt";
        private string text;

        public void CheckFileStatus()
        {
            if (!Directory.Exists(dir))
            {
                DirectoryInfo directory = Directory.CreateDirectory(dir);
            }
            if (!File.Exists(file))
            {
                using (FileStream fileStream = File.Create(file))
                {
                }
            }
        }

        public bool EmptyFile()
        {
            FileInfo fileInfo = new FileInfo(file);

            if (fileInfo.Length == 0) return true;
            else return false;
        }

        private void SetFileText(string writeText)
        {
            using (StreamWriter streamWriter = new StreamWriter(file))
            {
                streamWriter.Write(writeText);
            }
        }

        private string GetFileText()
        {
            using (StreamReader streamReader = File.OpenText(file))
            {
                return streamReader.ReadLine();
            }
        }

        public string Text
        {
            set
            {
                text = value;
                SetFileText(text);
            }
            get
            {
                return GetFileText();
            }
        }
    }
}


texts: Trying multiple regexes against a single string

texts:
I have a huge list of regexes (>1,000 but <1,000,000) that I want to test against (many) single strings.

It is unlikely and unintended that more than one such expression would match a single string. I could just maintain a big list of each compiled, individual regex and iterate over that for every input string. However I have it in my head that I should be handing the problem over to the regex compiler to simplify the common substrings since it can (at least theoretically) produce a very neat single DFA.

import re
import uuid

class multiregex(object):
    def __init__(self,rules):
        merge = []
        self._messages = {}
        for regex,text in rules:
            name = "g"+str(uuid.uuid4()).replace('-','')
            merge += ["(?P<%s>%s)" % (name,regex)]
            self._messages[name] = text

        self._re=re.compile('|'.join(merge))

    def __call__(self,s):
        result = self._re.search(s)
        if result:
            groups = result.groupdict()
            return ((self._messages[x], groups[x]) for x in groups.keys() if groups[x]).next()

rules = [("foobar", "Hit a foobar"),
         ("f.*b.*r", "fbr"),
         ("foob.z", "Frobination"),
         ("baz", "Hit a baz"),
         ("b(ingo)?", "b with optional ingo")]

m=multiregex(rules)
tests=["foobar", "foobaz", "foobazr", "b", "bingo"]
for text,hit in (m(x) for x in tests):
    print "Message: '%s' (because of '%s')" % (text,hit)

The code above works, but am I have a few outstanding issues with it:

Is it needlessly over complicating the whole thing? Or is it pushing the problem off to code that's heavily researched and optimised.
Is there a neater way of finding just the named capture group that matched than what I've done with groupdict()?
Are there any more gotchas than the obvious one of two 'rules' each containing the same group name? e.g.:

rules = [("(?P<hello>foobar)", "Hit a foobar"),
         ("(?P<hello>foob.z)", "Frobination")]

(The issue of a single syntax error in a single 'rule' killing the whole thing is easy enough to workaround by validating the inputs at rule creation time)


texts: How can this this URL Checker be made cleaner?

texts:
I have a table full of URLs, some of which will occasionally become invalid. As part of a system I'm writing to go through the links periodically, and test if they are valid (or redirect to valid sites), I wrote the following class. The feedback I'm looking for is primarily related to clean code and best practices--how should the URL be passed into this class, for example? (I have not included the test cases, but they were written first. :) )

Originally, I wrote this with the URL passed in on the constructor, but I realized that if I set it later, I could both make the class a dependency of another class without needing to know the URL ahead of time, and use the same object to test multiple URLs.

But as it is, my URLisValid function is doing two things: setting a class variable and evaluating the URL. That doesn't seem ideal to me, but neither does having a separate Setter, nor does passing the URL around the class as an argument, nor does passing it in on the constructor.

(obviously, I think this works fine as-is, although feel free to point out any real bugs. I'm improving this class as a lesson to myself in making my code as clean as possible).

class URLChecker
{
private $curl;
private $url;

const HTTP_RESPONSE_OK = 200;

public function __construct()
{
    $this->curl = curl_init();
}

public function __destruct()
{
    curl_close( $this->curl );
}

public function URLisValid( $url )
{
    $this->url = $url;
    $httpcode = $this->getHttpCodeForURL();
    return $this->httpCodeIsValid( $httpcode );
}

private function getHttpCodeForURL()
{
    $this->executeCurlSessionForHeadersOnly();
    return $this->getHttpCodeFromLastTransfer();
}

private function executeCurlSessionForHeadersOnly()
{
    $this->setCurlOptions();
    curl_exec( $this->curl );
}

private function getHttpCodeFromLastTransfer()
{
    return curl_getinfo( $this->curl, CURLINFO_HTTP_CODE );
}

private function setCurlOptions()
{
    curl_setopt($this->curl, CURLOPT_URL, $this->url);
    curl_setopt($this->curl, CURLOPT_NOBODY, true);
    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
}

private function httpCodeIsValid( $httpcode )
{
    return $httpcode == self::HTTP_RESPONSE_OK;
}
}

EDIT: version 2, based in part on some feedback:

class URLChecker

{
private $session;

const HTTP_RESPONSE_OK = 200;

public function __construct()
{
    $this->session = curl_init();
    $this->initializeSessionOptions();
}

public function urlIsValid( $url )
{
    $this->setSessionUrl( $url );
    $this->executeSession();
    $httpcode = $this->getHttpCodeFromLastSession();
    return $this->httpCodeIsValid( $httpcode );
}

private function executeSession()
{
    curl_exec( $this->session );
}

private function getHttpCodeFromLastSession()
{
    return curl_getinfo( $this->session, CURLINFO_HTTP_CODE );
}

private function setSessionUrl( $url )
{
    curl_setopt($this->session, CURLOPT_URL, $url);
}

private function initializeSessionOptions()
{
    curl_setopt($this->session, CURLOPT_NOBODY, true);
    curl_setopt($this->session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->session, CURLOPT_FOLLOWLOCATION, true);
}

private function httpCodeIsValid( $httpcode )
{
    return $httpcode == self::HTTP_RESPONSE_OK;
}

function __destruct()
{
    curl_close( $this->session );
}
}

I've removed $url as a class variable entirely, I've changed some method names to remove references to "curl" where the implementation of the session is not relevant to the logic. I kept the one line functions, because I want someone who does not know exactly how curl works to still be able to read the code. It is now clear that $url is not a property of the class--it is rather a variable to be passed in once, and tested.


texts:
Here is implementation for singly linkedlist. Any suggestions are most welcome

package linkedlist;

import java.util.Scanner;

public class linkedlist {
    private int size=0;
    private Node newNode,oldNode,firstNode,displayNode;

    public void createNode(String value) {
        if(size==0) {
            newNode=new Node(value,null);
            firstNode=newNode;
            size++;
        }
        else {
            oldNode=newNode;
            newNode=new Node(value,null);
            oldNode.setNextNode(newNode);
            size++;

        }

    }

    public void DisplayLinklist() {
        displayNode=firstNode;
        while(true) {
            System.out.println(displayNode.getItem());
            displayNode=displayNode.next;
            if(displayNode.next==null) {
                System.out.println(displayNode.getItem());
                break;
            }

        }
    }

    private class Node{
        private String item;
        private Node next;

        Node(String item,Node next){
            this.item=item;
            this.next=next;
        }

        public String getItem() {
            return this.item;
        }

        public void setNextNode(Node address) {
            this.next=address;
        }
    }

    public static void main(String[] args) {
        linkedlist mylinklist=new linkedlist();
        Scanner in=new Scanner(System.in);
        System.out.println("Enter the string value you want to save or press 'n'");
        String input=in.next();
        while(!input.equalsIgnoreCase("n")) {
            mylinklist.createNode(input);
            System.out.println("Enter the string value you want to save or press 'n'");
            input=in.next();
        }

        mylinklist.DisplayLinklist();

    }

}

This is very basic version and first time I  am doing Linkedlist. I am not using any iteration, but just wanted to confirm am I on the right path?


texts: Generating all subarrays from an array of Integer

texts:
I want to generate all the subarrays from an array of integer as below:

func subarrays(_ arr: [Int]) -> [[Int]]{
    var result = [[Int]]()
    guard arr.count >= 1 else { return [arr] }
    for i in 0..<arr.count {
        for res in result {
            var resi = res
            resi.append(arr[i])
            result.append(resi)
        }

        result.append([ arr[i] ])
    }
    result.append([])
    return result
}

subarrays([1,2]) //{},{1,2},{1},{2}
subarrays([1,2,3]) //{} {1}{2}{3}{1,2}{2,3}{1,3}{1,2,3}

I have alternative implementations, but really want to know if it is acceptable to use

for res in result

while adding to the array, or whether this would be seen as unusual practice in any way.


texts: LeetCode Reverse Words in a String without using any java library

texts:
The following problem is from LeetCode:

  Given a string, you need to reverse the order of characters in each
  word within a sentence while still preserving whitespace and initial
  word order.

  Example 1: Input: "Let's take LeetCode contest"

  Output: "s'teL ekat edoCteeL tsetnoc"

The following code is working correctly, but its runtime is 8 ms, which is only faster than 42.44% of Java online submissions. How to make the following code faster?

class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int length = s.length();
        int start = 0;
        int end = 0;
        while(start < length){
            while( (end < length) && (s.charAt(end) != ' ')){
                end++;
            }
            doReverse(s, start, end -1, sb);
            start = ++end;
        }
        return sb.toString();
    }

    private void doReverse(String s, int start, int end, StringBuilder sb){
        if(start >0)
            sb.append(" ");
        while(end >= start){
            sb.append(s.charAt(end));
            end--;
        }
    }
}


texts:
I was looking over some code that I wrote years ago (that is still technically working, albeit on a very quiet production server) and I came across this segment of code.
if(isset($array2)){

    foreach($array2 as $key => $value)
    {

        if((isset($value['coord'])||isset($value['bookedbefore']))&&!isset($value['bookedslot'])){
            echo("
Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot
");
            die();
        }
        $slotcode = $value['bookedslot'];
        !empty($value['bookedbefore']) ? $bookedbefore = 1 : $bookedbefore=0; // not required
        !empty($value['coord']) ? $coord = 1 : $coord=0; // not required

        $valuearray = array($UserID, $slotcode, $bookedbefore, $coord);
        //echo("
debug...
");var_dump($valuearray);
        try{
            $sql =
            ("

                INSERT INTO
                    bookedslot(`FK_UserID`, `FK_SlotCode`, `booked_before`, `coordinator_approv`)
                VALUES
                (
                    :UserID,
                    :slotcode,
                    :bookedbefore,
                    :coord
                );
            ON DUPLICATE KEY UPDATE
            FK_UserID = :UserID,
            FK_SlotCode = :slotcode,
            booked_before = :bookedbefore,
            coordinator_approv = :coord

            ");

            $sth = $dbh->prepare($sql);
            $sth->bindValue(':UserID', $valuearray[0]);
            $sth->bindValue(':slotcode', $valuearray[1]);
            $sth->bindValue(':bookedbefore', $valuearray[2]);
            $sth->bindValue(':coord', $valuearray[3]);

            $sth->execute();
            $sth->closeCursor();
        }

            catch(PDOException $e) {
                $message = (implode($valuearray));
                echo("
Something seems to have gone wrong with your choices.
");
            }

    }
    unset($array2);
}

I am usually loath to touch things that aren't broken, but that foreach loop looks completely unjustified in my mind, or at the very least, surely it is making a large number of unnecessary calls to the database? Was I having a brainfart years ago, or now?


texts:
Out of curiosity, I built a recursive Sieve of Eratosthenes in Python and I was wondering how it could be improved for efficiency and how it can improved to be aligned with python best practices.

Essentially, there is a recursive function (coded horrendously IMO), filter_multiples, which removes the multiples of some number. Then there is a for loop which cycles through the list which needs to be filtered and uses each number in that list for the recursive function. After the numbers in the list runs out, the code stops and outputs the list which remains i.e. the list of primes. Below is the code:

# Generate odd numbers to filter through, add number 2 after filtering
odd_nums = range(3,100,2)

def filter_multiples(lst, n, counter):
    ''' A recursive method used to remove multiples of n in a list(lst)
        and using a counter to iterate through that list
    '''
    if len(lst) == counter:
        return lst
    else:
        # See if a number in a list is divisble by n and if so, remove it
        if lst[counter] % n == 0 and lst[counter] != n:
            lst.remove(lst[counter])
        if len(lst) == counter:
            return lst
        return filter_multiples(lst, n, counter+1)

# Cycle through the numbers and use filter_multiples to remove the factors and keep the primes
for i in odd_nums:
    filter_multiples(odd_nums, i, 0)

odd_nums.insert(0,2)
print odd_nums

I would like to know how to improve upon the recursive function and furthermore, how to improve my program so that is in line with python best practices.


texts: How can I improve this Node.js file's routing?

texts:
Being new to Node.js, I'd like to know of a better way of implementing this:

server = http.createServer( function(req, res) {
if (req.url === '/') {
        fs.readFile('index.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();
        });
}
 else if (req.url == '/new.html') {
        fs.readFile('new.html', function(err, page) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write(page);
                res.end();
        });
}
});
server.listen(8080);

Using something like this:

var Url = require('url')
...

// In request handler
var uri = Url.parse(req.url);
switch (uri.pathname) {
  case "/":
    ..
  case "/new.html":
    ..
}


texts: Form the largest number by swapping one pair of digits

texts:
You are given a number. You are given the opportunity to swap only once to produce the largest number.

My approach was to use buckets whose values were their indexes and their locations were their values.

I walked the array checking if the largest value was greater than the current value.

If the current value was smaller I would decrement the largest value. Checking if it existed and that, that bucket was in a location greater than the current location in the iteration.

At which point I would know the bucket's location and that it contained the largest value outside a successive set and the nearest lowest value it would replace, to produce the largest number.

Analysis:

Creating Buckets: O(n) time and O(n) space
Walking Values Space and Time: O(1) +  finding the lowest high and swapping: O(1)
Total: O(n)

const maximumSwap = function(array) {
  array = array.toString().split('');
  const buckets = []
  for (let location = 0; location < array.length; location++) {
    buckets[array[location]] = location
  }
  let largest = buckets.length - 1
  for (let current_location = 0; current_location < array.length; current_location++) {
    let current_val = array[current_location]
    for (; largest > current_val; largest--) {
      if (buckets[largest] > current_location) {
        array[current_location] = [array[buckets[largest]], array[buckets[largest]] = array[current_location]][0]
        return +array.join('')
      }
    }
  }
  return +array.join('')
};

console.log(maximumSwap(99739))
console.log(maximumSwap(9273))
console.log(maximumSwap(9732))


texts: Checking if two numbers have the same sign

texts:
Is there a more elegant way than the following to check if two numbers have the same sign?

 bool sameSign(int num1, int num2)
    {
        if (num1 > 0 && num2 < 0)
            return false;
        if (num1 < 0 && num2 > 0)
            return false;
        return true;
    }

It could also be written as the not case of all of this (e.g. check the true cases and return false at the end).

By design, the two integers will never contain a zero value.


texts:
I was asked to provide some example code for a job interview and didn't have anything to offer, so wrote the following function.
A barcode generator may seem a bit basic, but there's some logic behind the choice:

It's something I recently needed, so not entirely contrived.
It's simple enough to do in one function, so it can be reviewed easily.
It's complex enough that a new programmer would make a mess of it.
It's visual. You can render the result in a browser.
It's useful, so I could make a little gist out of it.

The barcode is in the Interleaved 2 of 5 Format. It's a simple format, and there's a Wikipedia article that covers it well.
Update: A new version of this code has been posted here. The new code includes many of the suggestions made below.
def render(digits):

    '''This function converts its input, a string of decimal digits, into a
    barcode, using the interleaved 2 of 5 format. The input string must not
    contain an odd number of digits. The output is an SVG string.

        import barcode
        svg = barcode.render('0123456789')

    Strings are used to avoid problems with insignificant zeros, and allow
    for iterating over the bits in a byte [for zipping].

    # Wikipedia, ITF Format: http://en.wikipedia.org/wiki/Interleaved_2_of_5
    '''

    # Encode: Convert the digits into an interleaved string of bits, with a
    # start code of four narrow bars [four zeros].

    bits = '0000'
    bytes = {
        '0': '00110', '5': '10100',
        '1': '10001', '6': '01100',
        '2': '01001', '7': '00011',
        '3': '11000', '8': '10010',
        '4': '00101', '9': '01010'
        }

    for i in range(0, len(digits), 2):

        # get the next two digits and convert them to bytes
        black, white = bytes[digits[i]], bytes[digits[i+1]]

        # zip and concat to `bits` 5 pairs of bits from the 2 bytes
        for black, white in zip(black, white): bits += black + white

    # Render: Convert the string of bits into an SVG string and return it.

    svg = '<svg height="50">'
    bar = '<rect x="{0}" y="0" width="{1}" height="50" {2}></rect>'
    pos = 5 # the `x` attribute of the next bar [position from the left]

    for i, bit in enumerate(bits):

        width = int(bit) * 2 + 2
        color = '0,0,0' if (i % 2 == 0) else '255,255,255'
        style = 'style="fill:rgb({0})"'.format(color)

        svg += bar.format(pos, width, style)
        pos += width

    return svg + '</svg>'

Note: This works in both Python 2 and Python 3


texts: Getting all (forward) permutations of a list of strings

texts:
I have the following concise-ish (and working) approach to getting all the forward permutations of a list of string. So with the list:

  w = ["Vehicula", "Sem", "Risus", "Tortor"]

the results should be:

  ['Vehicula', 'Vehicula Sem', 'Vehicula Sem Risus', 'Vehicula Sem Risus Tortor', 'Sem', 'Sem Risus', 'Sem Risus Tortor', 'Risus', 'Risus Tortor', 'Tortor']

To do this, we loop through each element, and perform an inner loop that looks ahead and saves slices of the remaining elements to a result array.

w = ["Vehicula", "Sem", "Risus", "Tortor"]
results = []

i = 0
l = len(w)
while i < l:
    j, k = i, i + 1
    while k <= l:
        results.append(" ".join(w[j:k]))
        k = k + 1
    i = i + 1
print results

With Python, I always feel like I'm missing a trick, so I'm curios to see if there are any native Python functions that will make this more efficient?

Edit

I tested all three with timeit and mine is definitely the slowest. I've got to get to grips with itertools - it is very powerful.

Verbose (Mine): 3.61756896973
Comprehensions: 3.02565908432
Itertools: 2.83112883568


texts: Next multiple with only 1 and 0 as digit

texts:
Problem:
Find a multiple of a given decimal number \$N\$ that looks like a binary number.

The input will consist of at most \$ 2 \times 10^5 \$ lines, each line consist of an integer \$N\$ (\$0 \lt N \lt 10^{12} \$). Find its described multiple \$M (\ne 0\$), this number \$M\$ must be less than \$10^{12}\$. If there is no such number, print '\$-1\$' on the output.

My solution to this problem is quite simple. Just generated all binary-like numbers less than \$10^{12}\$ excluding \$0\$ (there are \$4095\$ such numbers).

For each number from input, just do a linear search on the binary numbers list. Is it possible to do it faster?

#include <cstdio>
#include <vector>

std::vector<long long> bits;

void generateBits(){

    for (int i = 1; i < 4096; ++i) {

        long long e = 1; //e is the exponencial of 10
        long long n = i; //n will be used to extract the bits from the number i
        long long d = 0;//binary-like decimal number...

        while (n) {
            d += ((n&1)*e);
            n >>= 1, e *= 10;
        }

        bits.push_back(d);
    }
}

long long getBitMultiple(long long n){

    for (auto &bit : bits) {
        if(bit%n == 0){
            return bit;
        }
    }

    return -1;
}

int main(void){

    generateBits();

    long long n;

    while (scanf("%lld",&n) != EOF) {
        printf("%lld\n",getBitMultiple(n));
    }

    return 0;
}


texts: Using deftype to create a wrapper class for byte arrays

texts:
I want to create a wrapper class for byte arrays so that I can use them as keys in fastutil's Object2LongAVLTreeMap. I have created a wrapper like this:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [this other]
    (let [m (alength ^bytes (.ba this))
          n (alength ^bytes (.ba other))
          l (min m n)]
      (loop [i 0]
        (if (< i l)
          (let [a (aget ^bytes (.ba ^Bytes this) i)
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))

The wrapper needs to implement Comparable for the insertions in the AVL Tree.

I am looking for feedback regarding my overall approach and my implementation of compareTo. I will be inserting lots of entries into the tree so I don't want to be creating unnecessary objects, etc. during the comparison.

EDIT: I believe the code above has a bug. See my comment below.


texts:
I have this function which looks through ALL files found in a directory (including sub folders) and deleted the duplicated file.

private static void DeleteDuplicateFiles(string directoryPath)
    {
        Console.WriteLine("Finding files...");

        // get all files
        var allFiles = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
        Console.WriteLine("Files found: {0}", allFiles.Length);

        // get duplicate files
        var dupFiles = allFiles.Select(f =>
        {
            using (var fs = new FileStream(f, FileMode.Open, FileAccess.Read))
            {
                return new
                {
                    FileName = f,
                    FileHash = BitConverter.ToString(SHA1.Create().ComputeHash(fs))
                };
            }
        }).GroupBy(f => f.FileHash).Select(g => new { FileHash = g.Key, Files = g.Select(z => z.FileName).ToList() })
        .SelectMany(f => f.Files.Skip(1)).ToList();
        Console.WriteLine("Duplicate files: {0}", dupFiles.Count);

        // delete deuplicate files
        dupFiles.ForEach(File.Delete);

        Console.WriteLine("{0} files were deleted", dupFiles.Count);

    }

This algorithm isn't the most efficient obviously, but what I have in mind is to:

Group files by their size (so files with unique size wont get processed)
Calculate the hash of the remaining files.

Is this the best solution or is there a better way of doing it?


texts:
I wrote this code using jQuery, but I think it can be improved. Can you provide some feedback?

    var $i = 1,
    totalImg = $('.home-featured-bg .absolute div').length,
    $theWidth = $(window).width(),
    $theHeight = $(window).height();
    $('.home-featured-bg .absolute').css('width',$theWidth * totalImg+'px');
    $('.home-featured-bg .absolute .slide,.home-featured-bg .absolute .slide img').css({'width':$theWidth+'px','height' : $theHeight+'px'});

window.setInterval(function(){
    $('.events-links a').hide();
    if($i == 1)
    {

        var $el = $theWidth;
    }else{
        var $el = $theWidth * $i;
    }
    if($i < totalImg)
    {
        $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000);
        $i++;
        $('.events-links a').eq($i - 1).css('display','block');
    }else{
        $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000);
        $i = 1;
        $('.events-links a').eq($i - 1).css('display','block');
    }

},3000);

$(window).resize(function(){
    totalImg = $('.home-featured-bg .absolute div').length,
    $theWidth = $(window).width(),
    $theHeight = $(window).height();
    $('.home-featured-bg .absolute').css('width',$theWidth * totalImg+'px');
    $('.home-featured-bg .absolute .slide,.home-featured-bg .absolute .slide img').css({'width':$theWidth+'px','height' : $theHeight});
});


texts:
I have a list of records containing Id, DateFrom, DateTo. For the sake of this question we can use this one:

List<(int, DateTime, DateTime)> data = new List<(int, DateTime, DateTime)>
        {
            (1, new DateTime(2012, 5, 16), new DateTime(2018, 1, 25)),
            (2, new DateTime(2009, 1, 1), new DateTime(2011, 4, 27)),
            (3, new DateTime(2014, 1, 1), new DateTime(2016, 4, 27)),
            (4, new DateTime(2015, 1, 1), new DateTime(2015, 1, 3)),
        };

In my real case the List could be a lot bigger, for now I assume that there is only one entry for a certain Id.

The task is to find the two records that has the longest time overlap and to return the ids and the number of days overlapped.

Which in this sample case means that these should be records 1 and 3, because 2 is not overlapping with anyone, and 4 overlaps for shorter time.

My implementation of this is the following:

    public (int, int, int) GetLongestElapsedPeriod(List<(int, DateTime, DateTime)> periods)
    {
        int firstId = -1;
        int secondId = -1;
        int periodInDays = 0;

        foreach (var period in periods)
        {
            var Id = period.Item1;
            var dateFrom = period.Item2;
            var dateTo = period.Item3;

            for (int i = 0; i < periods.Count; i++)
            {
                if (Id != periods[i].Item1)
                {
                    var tempId = periods[i].Item1;
                    var tempDateFrom = periods[i].Item2;
                    var tempDateTo = periods[i].Item3;

                    if (tempDateFrom < dateTo && tempDateTo > dateFrom)
                    {
                        DateTime commonStartingDate = tempDateFrom > dateFrom ? tempDateFrom : dateFrom;
                        DateTime commonEndDate = tempDateTo > dateTo ? dateTo : tempDateTo;

                        var elapsedPeriod = commonEndDate - commonStartingDate;

                        if ((int)elapsedPeriod.TotalDays > periodInDays)
                        {
                            periodInDays = (int)elapsedPeriod.TotalDays;
                            firstId = Id;
                            secondId = tempId;
                        }
                    }
                }
            }
        }
        return (firstId, secondId, periodInDays);
    }

But I think this way is not very efficient and I'm looking for ideas to optimize this logic. Also, I suspect that this is variation of some more general algorithmic problem.


texts: improvement of a database register function

texts:
Here is a function in a django rest api, that takes data in json and registers a category for a given website. I'd like to merge two try...except parts that check 'site_id' and 'category_id' but I am not sure how to do it. Also any other suggestion to make it pythonic is appreciated:

@myql_view(['POST'])
def register_category(request):

    try:
        site_id = request.data['site_id']
    except Exception as e:
        print('Request error or missing site_id:', e)
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        category_id = request.data['category_id']
    except Exception as e:
        print('Request error or missing category_id', e)
        return Response(status=status.HTTP_400_BAD_REQUEST)

    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO productCategory (site_id, category_id) VALUES (%s, %s)',
                       [site_id, category_id])
    except Exception as e:
        print('Could not register product', e)
        return Response(status=status.HTTP_409_CONFLICT)
    finally:
        cursor.close()

    return Response(status=status.HTTP_200_OK)


texts: How can I apply an Optional in which I want to call a method?

texts:
I have this piece of code:
final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class);

return Optional.ofNullable(response)
            .map(results -> createPOIs(Collections.singletonList(response), providerResponse))
            .orElse(Collections.emptyList());

The important part is that: response is an object of type ResultDO. Within an Optional I want to call that method createPois(). Methot createPois wants a list of ResultDO, but there I will always have it only element because of that I wrapped in a Collections.singletonList().
As I wrote it, is it the right way, with that .map() ?
I don't want to use if(response != null) ...
Maybe it is worth to mention that createPois() return a list of some other types. A list of Points.