texts: Comparing columns in pandas different data frames and fill in a new column

texts:
I have two dataframes:
One contains of company and its corresponding texts. The texts are in lists

**supplier_company_name   Main_Text**

JDA SOFTWARE          ['Supply chains','The answer is simple -RunJDA!']

PTC                    ['Hello', 'Solution']

The second dataframe is texts extracted from the company's website.

      Company            Text
0   JDA SOFTWARE    About | JDA Software
1   JDA SOFTWARE    833.JDA.4ROI
2   JDA SOFTWARE    Contact Us
3   JDA SOFTWARE    Customer Support
4   PTC             Training
5   PTC             Partner Advantage

I want to create the new column in second dataframe if the text extracted from the web matches with the any item inside the list in the Main_Text column of the first data frame, fill True else fill False.

Code:

target = []
for x in tqdm(range(len(df['supplier_company_name']))): #company name in df1
    #print(x)
    for y in range(len(samp['Company']): #company name in df2
        if samp['Company'][y] == df['supplier_company_name'][x]: #if the company name matches
            #check if the text matches
            if samp['Company'][y] in df['Main_Text'][x]:
                target.append(True)
            else:
                target.append(False)

How can I change my code to run efficiently?


texts:
I have created a test, also the interfaces to be implemented for each test case based on user's role because I think it would make it easier to understand what the test case will and should do, also forces each test that has similar requirements to have consistent method naming. I want to make sure what I did is a best practice before I implement them to all my test cases.
To have a better sight of what am I doing, please have a look at this folder structure.

Based on that, I have implemented them in one class, the file looks like this. It applies to other test cases like Showing, Updating, Destroying, Uploading, and so on...
<?php

namespace Tests\Feature\Specialization;

use App\Models\Specialization;
use App\Models\User;
use Database\Seeders\SpecializationSeeder;
use Database\Seeders\RolesAndPermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Spatie\Permission\PermissionRegistrar;
use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByCustomer;
use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByEmployee;
use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByInternal;
use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByModerator;
use Tests\_Interfaces\Feature\Basic\NotIndexable\NotIndexableByGuest;
use Tests\TestCase;

class SpecializationIndexTest extends TestCase implements
    IndexableByCustomer,
    IndexableByEmployee,
    IndexableByInternal,
    IndexableByModerator,
    NotIndexableByGuest
{
    use RefreshDatabase;

    public function setUp(): void
    {
        parent::setUp();
        $this->app->make(PermissionRegistrar::class)->registerPermissions();
        $this->seed(RolesAndPermissionSeeder::class);
        $this->seed(SpecializationSeeder::class);
    }

    public function testIndexShouldBeInaccessibleByGuest()
    {
        $this
            ->getJson(route('specializations.index'))
            ->assertUnauthorized()
            ->assertJsonMissing(Specialization::first()->toArray());
    }

    public function testIndexShouldBeAccessibleByInternal()
    {
        $user = User::factory()->createOne()->assignRole('internal');

        $this->actingAs($user, 'api')
            ->getJson(route('specializations.index'))
            ->assertOk()
            ->assertJsonFragment(Specialization::first()->toArray());
    }

    public function testIndexShouldBeAccessibleByModerator()
    {
        $user = User::factory()->createOne()->assignRole('moderator');

        $this->actingAs($user, 'api')
            ->getJson(route('specializations.index'))
            ->assertOk()
            ->assertJsonFragment(Specialization::first()->toArray());
    }

    public function testIndexShouldBeAccessibleByCustomer()
    {
        $user = User::factory()->createOne()->assignRole('customer');

        $this->actingAs($user, 'api')
            ->getJson(route('specializations.index'))
            ->assertOk()
            ->assertJsonFragment(Specialization::first()->toArray());
    }

    public function testIndexShouldBeAccessibleByEmployee()
    {
        $user = User::factory()->createOne()->assignRole('employee');

        $this->actingAs($user, 'api')
            ->getJson(route('specializations.index'))
            ->assertOk()
            ->assertJsonFragment(Specialization::first()->toArray());
    }
}

So the question is, is this a good idea to have interfaces for tests? Or should I avoid it?


texts: Simplify javascript redirecting functions logic

texts:
I have javascript file which is ugly but I have not idea how to make it better.
There are many function for redirecting with different number of parameters.
Just few functions are used for other thinks. All this functions will be called from Jquery event.
Like this:

$("#btnSomeButtonID").click(function () { SelectPTO(); });

I would like to simplify logic.
Do you have any ideas for refactoring?
Thank you for your help.

// Require refactoring, all is  public. Need to investigate what is best way.

var pushupdatesList; //public
var pushupdatesListRun = true;//public
var loading = false;//public

// functions with 0 parameters
function StartLoading() {
    if (loading)
        return;

    loading = true;
    $("#loadingbar").show();
}

function StopLoading() {
    loading = false;
    $("#loadingbar").hide();
}

// redirect functions with 0 parameters
function OpenAddCompany() {
    location.href = "/Administration/AddCompany";
}

function OpenAdminTools() {
    StartLoading();
    location.href = "/Administration/GetCompanies";
}

function Logout() {
    StartLoading();
    AbortPushUpdates();
    loading = 0;
    location.href = "/Home/Logoff";
}

function SelectPTO() {
    StartLoading();
    AbortPushUpdates();
    loading = 0;
    location.href = "/Home/SelectEquipmentCollection";
}

function OpenChangePassword() {
    StartLoading();
    loading = 0;
    location.href = "/Home/ChangePassword";
}

// functions with 1 parameter
function OpenGetPTOs(ID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/GetEquipmentCollections/" + ID;
}

function OpenAddPTO(ID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/AddEquipmentCollection/" + ID;
}

function OpenGetAccountsForCompany(ID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/GetAccountsForCompany/" + ID;
}

function OpenAddAccount(ID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/AddAccount/" + ID;
}

// functions with 2 parameters
function OpenGetAccountsForPTO(ID, CompanyID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/GetAccountsForEquipmentCollection/" + ID + "?CompanyID=" + CompanyID;
}

function OpenAddAccountToPTO(ID, CompanyID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/AddAccountToEquipmentCollection/" + ID + "?CompanyID=" + CompanyID;
}

function OpenGetVehiclesForPTO(ID, CompanyID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/GetEquipmentForCollection/" + ID + "?CompanyID=" + CompanyID;
}

function OpenAddVehicleToPTO(ID, CompanyID) {
    StartLoading();
    loading = 0;
    location.href = "/Administration/AddEquipmentToCollection/" + ID + "?CompanyID=" + CompanyID;
}


texts: Python RPC Design Pattern - is bidrectional coupling a good idea?

texts:
I want to build a barebones system according to the following spec:
Given a setup of n computers, if the ith computer receives an operation to update a given key-value pair, it should perform the update, and propagate it to all other nodes. I'd like communication between nodes to be done with RPC.
I have the following runnable code that works fine:
import aiomas

class RpcCall:
    def __init__(self, port, method):
        self.port = port
        self.method = method

    async def __call__(self, *args, **kwargs):
        rpc_con = await aiomas.rpc.open_connection(("localhost", self.port))
        rep = await getattr(rpc_con.remote, "redirect")(*args, **kwargs, method_name=self.method)
        await rpc_con.close()
        return rep

class Node:
    def __init__(self, port, neb_ports):
        self.server = None
        self.port = port
        self.table = {}
        self.neb_ports = neb_ports

    def start(self):
        self.server = aiomas.run(aiomas.rpc.start_server(("localhost", self.port), Server(self)))

    def close(self):
        self.server.close()
        aiomas.run(self.server.wait_closed())

    async def update(self, key, value, replicate=True):
        self.table[key] = value
        if replicate:
            for neb in self.neb_ports:
                await self.replicate(neb, "update", key=key, value=value, replicate=False)

    async def replicate(self, node, method_name, *args, **kwargs):
        rpc_call = RpcCall(node, method_name)
        await rpc_call(*args, **kwargs)

class Server:
    router = aiomas.rpc.Service()

    def __init__(self, node: Node):
        self.node = node

    @aiomas.expose
    async def redirect(self, method_name, *args, **kwargs):
        func = getattr(self.node, method_name)
        await func(*args, **kwargs)

if __name__ == "__main__":
    n1 = Node(5555, [5556])
    n2 = Node(5556, [5555])
    n1.start()
    n2.start()

    aiomas.run(n1.update("foo", "bar"))

    print(n1.table)
    print(n2.table)

As the output should show, the table is replicated onto both nodes, ensuring there's no data loss in case one node dies.
I'm looking for a review specifically on the design pattern used in the above.
I've coupled the Node and Server classes so that whenever the Server receives an RPC call, it delegates it back to the Node, which then performs the operation on the underlying table
Good idea/bad idea?


texts: Using decorated methods in a subclass of deque to dump its state to a JSON file

texts:
I am sub-classing an object in python and I need to overload a bunch of the methods with very similar logic, essentially a call to super() and then some additional operations. I want to avoid explicitly writing out each of those overloaded methods in that way, so I implemented a decorator.

Is there anything wrong with doing the following:

def decorator(function):
    def wrapper(*args, **kwargs):
        # Logic + operations here
        function()
        # Logic and operations here

    return wrapper

class SubClass(SuperClass):
    method1 = decorator(SuperClass.method1)
    method2 = decorator(SuperClass.method2)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Extra logic here

Here is my actual implementation:

def updates_file(function):
    """
    Decorator to call update file method after super call.
    """
    def wrapper(*args, **kargs):
        function(*args, **kargs)
        args[0]._update_file()

    return wrapper

class FileMirroredDeque(deque):

    __delitem__ = updates_file(deque.__delitem__)
    __iadd__    = updates_file(deque.__iadd__)
    __imul__    = updates_file(deque.__imul__)
    __setitem__ = updates_file(deque.__setitem__)
    append      = updates_file(deque.append)
    appendleft  = updates_file(deque.appendleft)
    extend      = updates_file(deque.extend)
    extendleft  = updates_file(deque.extendleft)
    insert      = updates_file(deque.insert)
    pop         = updates_file(deque.pop)
    popleft     = updates_file(deque.popleft)
    remove      = updates_file(deque.remove)
    reverse     = updates_file(deque.reverse)
    rotate      = updates_file(deque.rotate)

    def __init__(self, cache_path, maxlen=None, clean=False, file_indent=None):
        super().__init__((), maxlen)  # Initializes the deque as well TODO: Check the implication of this calling __setitem__

        self.path = cache_path
        self._indent = file_indent
        self._bak_file = None

        if clean:
            self._update_file()  # Overwrite contents of file.
            return  # Don't import data from file.

        with open(self.path, 'a+') as f:  # Creates file if it doesn't exist
            f.seek(0, 0)  # Seek back to beginning of file for json decode.
            contents = f.read()

        try:
            self.extend(json.loads(contents or "[]"))  # initializes internal list with persistent data or empty list.

        except json.decoder.JSONDecodeError:
            new_file = os.path.basename(self.path) \
                       + datetime.datetime.utcnow().strftime("_%Y_%m_%d_%H_%M_%S") + ".bak"

            new_path = os.path.join(os.path.dirname(self.path), new_file)

            logger.warning(f"File: {self.path} was not valid JSON. It will be copied to {new_path} and a new "
                           f"file will be created.")

            shutil.copyfile(self.path, new_path)
            self._bak_file = new_path

    def _update_file(self):
        with open(self.path, 'w') as f:
            json.dump(list(self), f, indent=self._indent)


texts:
Description:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Leetcode

Code:

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        return recur(root, 1);
    }

    private int recur(TreeNode root, int depth) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) {
            return depth;
        }
        int ldepth = recur(root.left, depth + 1);
        int rdepth = recur(root.right, depth + 1);

        // either left or right subtree was not a leaf node
        // ignore non leaf node.
        if (ldepth == 0 || rdepth == 0) {
            return Math.max(ldepth, rdepth);
        }
        else {
            return Math.min(ldepth, rdepth);
        }
    }
}

Question:

I need to know if the given logic can be simplified?


texts: Adding multiple events in gcalcli using a bash script

texts:
#!/bin/bash

#assigning variables
start="14:00"
duration="150"
title="Exper. Lab"
year="2016"
start2="17:30"
duration2="230"
title2="Calc1"

# Here I refer to dates that the event occurs on piping the variables into gcalcli (Google calendar command line interface) creating a repeated event on my Google calender

for monthday in {09/{1..29..7},09/{6..27..7},10/{4..25..7},10/{6..27..7},11/{1..29..7},11{3..24..7},12/{6..20..7},12/{1..15..7}}
do
(echo $title ; echo "'$monthday/$year $start'"; echo $duration) | ../../../../usr/bin/gcalcli add --calendar 'Class'

done

# Same thing different repeated event

for monthday2 in {09/{12..26..7},10/{3..31..7},11/{7..28..7},12/{5..19..7}}
do
(echo $title2 ; echo "'$monthday2/$year $start2'"; echo $duration2) | ../../../../usr/bin/gcalcli add --calendar 'Class'

done

exit 0

Is there a way I could do this in one loop? Or should I be using another method?


texts: Not feeling 100% about my Controller design.

texts:
Basically, I'm uploading an excel file and parsing the information then displaying what was parsed in a view.

using System.Data;
using System.Data.OleDb;
using System.Web;
using System.Web.Mvc;
using QuimizaReportes.Models;
using System.Collections.Generic;
using System;

namespace QuimizaReportes.Controllers
{
    public class UploadController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase excelFile)
        {
            if (excelFile != null)
            {
                //Save the uploaded file to the disc.
                string savedFileName = "~/UploadedExcelDocuments/" + excelFile.FileName;
                excelFile.SaveAs(Server.MapPath(savedFileName));

                //Create a connection string to access the Excel file using the ACE provider.
                //This is for Excel 2007. 2003 uses an older driver.
                var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", Server.MapPath(savedFileName));

                //Fill the dataset with information from the Hoja1 worksheet.
                var adapter = new OleDbDataAdapter("SELECT * FROM [Hoja1$]", connectionString);
                var ds = new DataSet();
                adapter.Fill(ds, "results");
                DataTable data = ds.Tables["results"];

                var people = new List<Person>();

                for (int i = 0; i < data.Rows.Count - 1; i++)
                {
                    Person newPerson = new Person();
                    newPerson.Id = data.Rows[i].Field<double?>("Id");
                    newPerson.Name = data.Rows[i].Field<string>("Name");
                    newPerson.LastName = data.Rows[i].Field<string>("LastName");
                    newPerson.DateOfBirth = data.Rows[i].Field<DateTime?>("DateOfBirth");

                    people.Add(newPerson);
                }

                return View("UploadComplete", people);
            }

            return RedirectToAction("Error", "Upload");
        }

        public ActionResult Error()
        {
            return View();
        }
    }
}

Not feeling so confident this is the best approach. Any suggestion any of you MVC3 vets have for this aspiring senior programmer? :)


texts:
#include <cassert>
#include <string>
#include <vector>
using namespace std;

inline size_t min(size_t x, size_t y, size_t z)
{
    if (x < y)
        return x < z ? x : z;
    else
        return y < z ? y : z;
}

size_t edit_distance(const string& A, const string& B)
{
    size_t NA = A.size();
    size_t NB = B.size();

    vector<vector<size_t>> M(NA + 1, vector<size_t>(NB + 1));

    for (size_t a = 0; a <= NA; ++a)
        M[a][0] = a;

    for (size_t b = 0; b <= NB; ++b)
        M[0][b] = b;

    for (size_t a = 1; a <= NA; ++a)
        for (size_t b = 1; b <= NB; ++b)
        {
            size_t x = M[a-1][b] + 1;
            size_t y = M[a][b-1] + 1;
            size_t z = M[a-1][b-1] + (A[a-1] == B[b-1] ? 0 : 2);
            M[a][b] = min(x,y,z);
        }

    return M[A.size()][B.size()];
}

int main()
{
    assert(edit_distance("ISLANDER", "SLANDER") == 1);
    assert(edit_distance("MART", "KARMA") == 5);
    assert(edit_distance("KITTEN", "SITTING") == 5);
    assert(edit_distance("INTENTION", "EXECUTION") == 8);
}


texts:
I wrote a class to generate URL as I need. (Using http or https and switching off the rewrite rules)
That is my first OOP code. It's the right approach, any suggestion?

inc/class.urls.inc.php

    class Url {

    public function __construct() {

        $this->rewrite = SITE_REWRITE;
        $this->domain = SITE_URL;
    }

    public function home() {
        return $this->domain;
    }

    public function page($page) {
        if ($this->rewrite == 1) {
            return $this->domain . '/' . $page . '.html'; // https://www.example.com/contact.html
        } else {
            return $this->domain . '/' . $page . '.php'; // https://www.example.com/cantact.php
        }
    }

    public function manufacter($slug) {
        if ($this->rewrite == 1) {
            return $this->domain . '/' . $slug; // https://www.example.com/apple
        } else {
            return $this->domain . '/manufacter.php?s=' . $slug; // https://www.example.com/manufacter.php?s=apple
        }
    }

    public function product($slug, $manufacter) {
        if ($this->rewrite == 1) {
            return $this->domain . '/' . $manufacter . '/' . $slug; // https://www.example.com/apple/iPhone
        } else {
            return $this->domain . '/product.php?s=' . $slug; // https://www.example.com/product.php?s=iPhone
        }
    }

    public function category($slug) {
        if ($this->rewrite == 1) {
            return $this->domain . '/' . 'categories/' . $slug; // https://www.example.com/categories/phone
        } else {
            return $this->domain . '/category.php?s=' . $slug; // https://www.example.com/category.php?s=phone
        }
    }

}

Page

<?php

DEFINE('SITE_NAME','Site Name');
DEFINE('SITE_DOMAINS','www.exemple.com');
DEFINE('SITE_HTTP','https://');
DEFINE('SITE_URL',SITE_HTTP.SITE_DOMAINS);
DEFINE('SITE_REWRITE',1);

include_once 'inc/class.urls.inc.php';

$url = new Url();

echo 'Home: '.$url->home() ."
";
echo 'Page: '.$url->page('contacts') ."
";
echo 'Category: '.$url->category('ipa') ."
";
echo 'Product: '.$url->product('punk-ipa','brew-dog') ."
";
echo 'Manufacter: '.$url->manufacter('brew-dog') ."
";
?>

Result

Home: https://www.exemple.com
Page: https://www.exemple.com/contacts.html
Category: https://www.exemple.com/categories/ipa
Product: https://www.exemple.com/brew-dog/punk-ipa
Manufacter: https://www.exemple.com/brew-dog


texts: Determine closest ancestor that has a certain HTML class

texts:
When writing JavaScript code for my own projects, this functionality is the singlemost used algorithm that does not already exist: Finding an ancestor element that has a certain HTML class.

Algorithm:

Does the current element have a parent element?

Yes: Continue with step 2
No: There are no solutions to the task, return a null value

Does the parent element of the current element have the required class?

Yes: Return the parent element
No: Set the current element to its parent element and repeat step 1

Code:

Element.prototype.getAncestorByClassName = function(className) {
    var currentParent = this.parentElement
    while (true) {
        // If the root of the DOM is reached, an ancestor cannot be found anymore.
        if (currentParent === null) {
            return null
        }

        if (currentParent.classList.contains(className)) {
            return currentParent
        }

        var currentParent = currentParent.parentElement
    }
}

Notes:

I want to be able to call element.getAncestorByClassName("class-name") hence the use of Element.prototype. Does this approach yield any problems? I am aware that I would override any getAncestorByClassName() functions that are introduced in future versions of ECMAScript
There are possibly multiple results for the task I specified. The algorithm will return the closest ancestor that has the given class.
If there are no results, null is returned as other functions like getElementById() do the same.
Browser support should cover all modern browsers. I do not consider IE8–IE10 modern browsers. The lack of support for classList on these is noted but not essential to me right now.


texts: Using delegates to avoid duplicate creation of resources

texts:
I'm writing a PCL that uses an HttpClient to go visit a few sites and extract data from them. My initial code looked like this:

public static class Download
{
    public async static Task<byte[]> FromYouTubeAsync(string videoUri)
    {
        using (var client = new HttpClient())
        {
            string source = await client
                .GetStringAsync(videoUri);

            // get links...

            return await client
                .GetByteArrayAsync(links.First());
        }
    }
}

I realized, however, that this would be a waste of resources if the user of my library already had a HttpClient in hand. For example:

// Caller code
using (var client = new HttpClient())
{
    // Do some work with client

    byte[] bytes = await Download.FromYouTubeAsync("some://uri"); // A second HttpClient is created here, wasting resources and time...

    // Do some work with client and bytes
}

One solution could be to add an overload taking an HttpClient as a parameter, but what if the user wanted to use a WebClient instead? Or an HttpWebRequest? Or some other kind of client that wasn't availsble in the PCL?

My solution

I decided to take delegate parameters to get the page source and to download the file based on the URI. My code now looks like this:

public static class Download
{
    public async static Task<byte[]> FromYouTubeAsync(string videoUri)
    {
        using (var client = new HttpClient())
        {
            return await FromYouTubeAsync(
                () => client
                .GetStringAsync(videoUri),
                uri => client
                .GetByteArrayAsync(uri));
        }
    }

    public async static Task<byte[]> FromYouTubeAsync(
        Func<Task<string>> sourceFactory, Func<string, Task<byte[]>> downloadFactory)
    {
        string source = await sourceFactory();

        // get links...

        return await downloadFactory(links.First());
    }
}

The problem

Hm. Wait, what if the caller is using a client that doesn't support async, like HttpWebRequest? Better add another overload taking a Func<string> and a Func<string, byte[]>. What if s/he wants to make the first call synchronous, but the second call async? Or vice versa? OK, just add 2 more overloads. Wait, what if the caller wants the whole operation to be synchronous? Let's go add 4 Download.FromYouTube overloads wrapping each of the async methods. Whoops, it turns out we need to visit another page of YouTube in case the video's signature is encrypted! Sure, let's go add 8 mor-

I think you can see where this is going. How do I maintain this flexibility without scaring the user away when Visual Studio says that there are 17 different overloads for this method?


texts:
I have a situation where I have a program will start up another program and it will do some work.  I need to be able to stop this work if certain conditions arise.  I want to use a CancellationToken on the worker side but as far as I know these can't be used across process boundaries.

I wrote the following code to accomplish this.  There are two parts, the the controller and the worker.  Here is the code for the controller:

class Program
{
    static void Main(string[] args)
    {
        var eventName = Guid.NewGuid().ToString();

        EventWaitHandle waitHandle;
        if (!EventWaitHandle.TryOpenExisting(eventName, out waitHandle))
        {
            waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);
        }

        Process.Start("Worker", eventName);

        Console.WriteLine("Press ENTER to cancel...");
        Console.ReadLine();

        waitHandle.Set();
    }
}

Here is the code for the worker:

public sealed class EventWaitHandleCancellationTokenSource : IDisposable
{
    private readonly EventWaitHandle waitHandle;
    private readonly CancellationTokenSource cancellationTokenSource;

    public EventWaitHandleCancellationTokenSource(string eventName)
    {
        if (!EventWaitHandle.TryOpenExisting(eventName, out waitHandle))
        {
            waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);
        }

        cancellationTokenSource = new CancellationTokenSource();
        ThreadPool.RegisterWaitForSingleObject(
            waitHandle,
            delegate
            {
                cancellationTokenSource.Cancel();
            }, null, Timeout.InfiniteTimeSpan, true);

    }

    public bool IsCancellationRequested => waitHandle.WaitOne(0);
    public CancellationToken Token => cancellationTokenSource.Token;

    public void Dispose()
    {
        waitHandle.Dispose();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cancellationTokenSource = new EventWaitHandleCancellationTokenSource(args[0]);

        Console.Write("Waiting for cancellation...");
        cancellationTokenSource.Token.WaitHandle.WaitOne();
    }
}

Is this the best way to do this?  It is the only reasonable way I can think of.


texts:
Write a program that prints the numbers from 1 to 100.
But for multiples of three print “Fizz” instead of the number
and for the multiples of five print “Buzz”. For numbers which are
multiples of both three and five print “FizzBuzz”.

Is this the best way of doing this?

def fizz_buzz(num):
    if num%3==0 and num%5==0:
        return 'FizzBuzz'

    elif num % 3 == 0:
        return 'Fizz'

    elif num % 5==0:
        return 'Buzz'
    else:
        return num

for n in range(1,100):
    print(fizz_buzz(n))


texts: Matching a type T to a list of case statements

texts:
I have a compile-time switch_ template that matches a given type T to a list of case_ statements (of which default_ is a special case, no pun intended). A case<Key, Value is two-parameter class for which its Key is matched against the class T using a match<T, Key> variable template, which is a modified std::is_same_v.

#include <cstdint>      // uint8_t, uint16_t, uint32_t, uint64_t
#include <type_traits>  // conditional_t, is_same_v, true_type, false_type

namespace meta {

template<auto N>
using int_c = std::integral_constant<decltype(N), N>;

struct true_;
struct false_;

template<class Key, class Value>
struct case_;

template<class Value>
using default_ = case_<true_, Value>;

template<class T, class Key>
constexpr auto match = std::is_same_v<T, Key>;

template<class T> constexpr auto match<T, true_> = true;
template<class T> constexpr auto match<true_, T> = true;

template<class T> constexpr auto match<T, false_> = false;
template<class T> constexpr auto match<false_, T> = false;

template<class T, class... Cases>
struct switch_;

template<class T, class... Cases>
using switch_t = typename switch_<T, Cases...>::type;

template<class T, class Key, class Value>
struct switch_<T, case_<Key, Value>>
:
        std::conditional<match<T, Key>, Value, false_>
{};

template<class T, class Key, class Value, class _, class Else>
struct switch_<T, case_<Key, Value>, case_<_, Else>>
:
        std::conditional<match<T, Key>, Value, Else>
{};

template<class T, class Key, class Value, class Head, class... Tails>
struct switch_<T, case_<Key, Value>, Head, Tails...>
:
        std::conditional<match<T, Key>, Value, switch_t<T, Head, Tails...>>
        //                                     ^^^^^^^^ <= can this recursion be avoided?
{};

}   // namespace meta

using namespace meta;

template<auto N>
using unsigned_ = switch_t<         // will return associated type of first match, case_ has "break" semantics
    int_c<N>,
    case_<int_c<8>, uint8_t>,
    case_<int_c<16>, uint16_t>,
    case_<int_c<32>, uint32_t>,
    case_<int_c<64>, uint64_t>,
    default_<unsigned>              // will always match, so put this last!
>;

int main()
{
    static_assert(std::is_same_v<unsigned_<  8>, uint8_t>);
    static_assert(std::is_same_v<unsigned_< 16>, uint16_t>);
    static_assert(std::is_same_v<unsigned_< 32>, uint32_t>);
    static_assert(std::is_same_v<unsigned_< 64>, uint64_t>);
    static_assert(std::is_same_v<unsigned_<128>, unsigned>);
}

Live Example using gcc 7.1 in C++17 mode.

Question: Please comment on the clarity of the code. In particular, I am curious if the compile-time recursion over the variadic parameter pack can somehow be avoided by mapping it to tuple or integer_sequence land where there are efficient compiler-intrinsics that pay off for long lists.

UPDATE: See this link for the updated code with changes that reflects the accepted answer.


texts: Getting initial values of non-primitive types from another Javascript file?

texts:
I have a file where I keep some initial values for some form fields base on field type. Some of them are primitive values, like '' or 0 or false but some of them are non-primitive reference values, like [] or {}. For example:

INITIAL_VALUES.js

const INITIAL_VALUES= {
  SINGLE_CHOICE: '',
  MULTIPLE_CHOICE: [],
  OBJECT: {},
  BOOLEAN: false,
  NUMBER: 0,
  STRING: ''
};

export default INITIAL_VALUES;

The fact is that I have to be careful when using non-primitive initial values, because since they come as reference, I might change them, and get them a second time with some residual value, instead of being empty.

I've tought about some options to deal with this:

OPTION #1

Make the INITIAL_VALUES.js export a function that returns the new values object and call that function inside my component.

Example:

getInitialValues.js

function getInitialValues() {
  return({
    SINGLE_CHOICE: '',
    MULTIPLE_CHOICE: [],
    OBJECT: {},
    // and so on...
  });
}

export default getInitialValues;

SomeComponent.js

import getInitialValues from './getInitialValues'

function SomeComponent() {
  const INITIAL_VALUES = getInitialValues();
}

OPTION #2

Keep the initial values as an object and everytime I use them, I need to check if it's a non-primitive and create a new one (instead of using the same reference from INITIAL_VALUES).

Example:

SomeComponent.js

myVariable = INITIAL_VALUES[fieldType];

if (Array.isArray(myVariable)) {
  myVariable = [...myVariable];                   // CREATE A NEW ARRAY
}
else if (typeof(myVariable)  === 'object') {
  myVariable = {...myVariable};                   // CREATE A NEW OBJECT
}

OPTION #3

Use only non-primitive values. And set null instead of empty arrays [] and empty objects {}.

Example:

INITIAL_VALUES.js

const INITIAL_VALUES= {
  SINGLE_CHOICE: '',
  MULTIPLE_CHOICE: null,
  OBJECT: null,
  BOOLEAN: false,
  NUMBER: 0,
  STRING: ''
};

But doing so, whenever I try to populate those fields, I'll need to check if the object/array exists, and create it if it doesn't.

Example

SomeComponent.js

function pushValueToArrayField(newValue) {
  setState((prevState) => {
    const aux = {...prevState};
    if (aux.someArrayField === null) {
      aux.someArrayField = [];
    }
    aux.someArrayField.push(newValue);
    return aux;
  });
}

What is my best option here?


texts: Join and map command line arguments in Rust

texts:
Is there a more natural way to do this in rust? I'm having a lot of difficulty trying to make this look clean. Type mismatches and borrowing have me stumped. What are some refactors that I could make?

Input

Take in list of space-separated, command-line arguments

Output

Book (join all arguments except the last)
Reference (the last argument)
File (looked up via the book)

I abbreviated the books_to_files mapping to only include a couple examples of books with different word lengths.

Examples

In:                             Out:

Genesis 1:1                     Genesis, 1:1, mhc1.txt
Song of Solomon 2:2-4           Song of Solomon, 2:2-4, mhc3.txt
Acts of the Apostles 3:3-9      Acts of the Apostles, 3:3-9, mhc6.txt

Source Code

use std::env;
use std::collections::HashMap;

fn main() {
    let args: Vec<String> = env::args().collect();

    let book: String;
    if args.len() == 3 {
        book = args[1].clone();
    } else if args.len() == 4 {
        book = args[1].clone() + " " + &args[2].clone();
    } else if args.len() == 5 {
        book = args[1].clone() + " " + &args[2].clone() + " " + &args[3].clone();
    } else if args.len() == 6 {
        book = args[1].clone() + " " + &args[2].clone() + " " + &args[3].clone() + " " + &args[4].clone();
    } else {
        panic!("Wrong number of arguments");
    }
    let reference: String = args[args.len()-1].clone();
    let file: String = get_file(&book);

    println!("{}, {}, {}", book, reference, file);
}

fn get_file(book: &String) -> String {
    let books_to_files: HashMap<&str, &str> = [
        ("Genesis", "mhc1.txt"),
        ("First Samuel", "mhc2.txt"),
        ("Song of Solmon", "mhc3.txt"),
        ("Acts of the Apostles", "mhc6.txt"),
        ("First Corinthians", "mhc6.txt"),
        ("Galatians", "mhc6.txt"),
    ].iter().cloned().collect();

    books_to_files.get::<str>(&book.to_string()).unwrap().to_string()
}

```


texts: Find number of unique paths to reach opposite grid corner

texts:
I have m x n grid. m >= 1 ; n >= 1

I have item in the top-left corner and need to reach bottom-right corner of the grid.

Item can only move either down or right.

I need to find possible unique paths to do it.

I made two solutions for the problem: recursion (slower than the below one) and the one below.

The problem is that I run out of memory when m and n are big e.g. m == 20 and n >= 15 (more than 4 Gb is used - all free memory I have).

How can I improve my solution or there should be absolutely other way to solve the problem?

def unique_paths(m, n):
    assert isinstance(m, int), "m should be integer"
    assert isinstance(n, int), "n shoudl be integer"
    assert m >= 1, "m should be >= 1"
    assert n >= 1, "n should be >= 1"
    if m == 1 and n == 1:  # border case
        return 1

    ch = [(m, n,)]  # for first start
    s = 0  # number of unique paths
    while True:
        new_ch = []
        while ch:
            i = ch.pop()  # I assumed that if decrease len of list it would decrease memory use
            if i[0] == 1 and i[1] == 1:  # we reached opposite corner
                s += 1

            # all other cases:

            elif i[0] != 1 and i[1] != 1:
                new_ch.append((i[0], i[1] - 1, ))
                new_ch.append((i[0] - 1, i[1]))

            elif i[0] == 1 and i[1] != 1:
                new_ch.append((i[0], i[1] - 1,))

            else:
                new_ch.append((i[0] - 1, i[1],))

            del i  # do not need i anymore

        if not new_ch:
            return s
        del ch
        ch = new_ch
        del new_ch

if __name__ == '__main__':
    print(unique_paths(7, 3))  # = 28 - test case

Edit:

lru_cache is really amazing:

from functools import lru_cache

@lru_cache(128)
def numberOfPaths(m, n):
    if m == 1 and n == 1:  # border case
        return 1

    if m != 1 and n != 1:
        return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1)

    if m != 1 and n == 1:
        return numberOfPaths(m - 1, n)

    if m == 1 and n != 1:
        return numberOfPaths(m, n - 1)

if __name__ == '__main__':
    print(numberOfPaths(100, 100))  # 22750883079422934966181954039568885395604168260154104734000

```


texts: Checking the balanced parenthesis as asked in interview

texts:
Input:

  Input contains one string S which consists of big and small latin
  letters, digits, punctuation marks and brackets from the set []{}().

  Constraint:

  Constraints. The length of S is at least 1 and at most 105

  Output:

  If the code in S uses brackets correctly, output “Success" (without
  the quotes). Otherwise, output the 1-based index of the first
  unmatched closing bracket, and if there are no unmatched closing
  brackets, output the 1-based index of the first unmatched opening
  bracket.

Code:

console.clear();

function hashBalancedParanthesis(string) {
  // Pre: The string should have ASCII characters
  var len = string.length;
  var stack = [];

  for (var i = 0; i < len; i++) {
    var char = string[i];
    //console.log(stack + " : " + char);
    if ('([{'.indexOf(char) !== -1)             // O(3 * len)
      stack.push(char);
    else if (')]}'.indexOf(char) !== -1) {      // O(3 * len)
      // Below operations are O(n) time
      var top = stack.pop();

      if (top === '[' && char !== ']') return string.indexOf(char) + 1;
      if (top === '{' && char !== '}') return string.indexOf(char) + 1;
      if (top === '(' && char !== ')') return string.indexOf(char) + 1;
    }
  }
  // Post: When here the stack should be empty for balanced case
  if (stack.length !== 0) return string.indexOf(stack.pop()) + 1;
  return true;
};

// False
console.log(hashBalancedParanthesis('('));
console.log(hashBalancedParanthesis('{[}'));
console.log(hashBalancedParanthesis('foo(bar[i);'));

// True
console.log(hashBalancedParanthesis(''));
console.log(hashBalancedParanthesis('{}[]'));
console.log(hashBalancedParanthesis('[()]'));
console.log(hashBalancedParanthesis('(())'));
console.log(hashBalancedParanthesis('foo(bar);'));

Description:

Instead of hard work since last three years I got rejected in one of the dream companies so, now I would like to have clear understanding of running time and edge cases as well as code quality.

Naming is now second priority.

As per my knowledge the above code runs in linear time \$\Theta(n)\$ where n is the string length.

PS: I am going to write a detailed analysis of my interview experience I would like to know which place would be better for it.


texts: An algorithm to calculate the check digit for 18-digit SSCC GS1 codes

texts:
I'm calculating the GS1 SSCC codes that are 18-digit barcodes. The 18th digit is a check digit which is used to validate the rest of that code and check that it is correct. the check digit is a number between 0-9 and is calculated using a specific algorithm on the preceding 17 digits which are the input for this code. You can find more information on: http://www.morovia.com/kb/Serial-Shipping-Container-Code-SSCC18-10601.html

static int getCheckDigit(string SSCC)
{
    int[] SSCCArray = SSCC.ToCharArray().Select(c => (int)char.GetNumericValue(c)).ToArray();

    int position = 0;
    int oddPisitonsSUM = 0;
    int evenPositionsSUM = 0;
    int oddSumMultiply3;
    int totalSUM;
    int mod10Remainder;
    int CheckDigit;

    foreach (int i in SSCCArray)
    {
        position += 1;

        if (position % 2 == 0)
        {
            evenPositionsSUM += i;
        }
        else
        {
            oddPisitonsSUM += i;
        }
    }
    oddSumMultiply3 = oddPisitonsSUM * 3;
    totalSUM = oddSumMultiply3 + evenPositionsSUM;
    mod10Remainder = totalSUM % 10;

    if (mod10Remainder == 0)
    {
        return mod10Remainder;
    }
    else
    {
        CheckDigit = (10 - mod10Remainder);
        return CheckDigit;
    }
}

There is no doubt a more elegant solution to this, but this is my first crack at it.
All constructive criticisms are welcome.


texts:
This isn't so much, HOW do I make it work, as this code works, rather how could I make it better. The way this code works is it guides a person to the correct answer by getting "Yes", "No" or "I don't know" (in some cases from the person).

It's intended to run in HTML5/JavaScript (kind of like an online interactive guide). This code actually works, but it uses the JavaScript "prompt" for the input, and frankly, it's pretty ugly. Any suggestions on how to make it either look or work better?

First the JavaScript, as it's the main engine:

function mc1() {
var n = prompt("Do you have Medicare benefits (Y=Yes, N=No, I=I don't know)", " ");

if( n == "Y"){
   mcs2();
}
else if (n="N"){
    mcs1a();
   }

else if (n="I"){
   mcs1b();
 }

else {
alert("Enter a valid choice Y,N or I!");
mc1();
}
}

function mcs1a(){
var n1=prompt("Have you applied and been denied Medicare Coverage (Y= Yes,  N= No,  I = I don't know)", "");
if (n1=="Y"){
mc3a();
}
else if (n1=="N"){
mc2b();
}
else if (n1=="I"){
mc2b();
}
else {
alert("Enter a valid choice:  Y, N or I!");
}
}

function mcs1b(){
alert("Refer to Social Security Administration to check status, (CODE E01M1)!");
}

function mcs2(){
var n2=prompt("Do you have Medicare Part A AND B ( Y=Yes, N=No, I=I don't know)","");
if (n2=="Y"){
mcs3();
}
if (n2=="N"){
alert("Refer to Social Security to apply for the other part (Code E01M1)!");
}
if (n2=="I"){
alert("Refer to Social Security Administration to check status (Code E01M1)!");
}
else {
alert("Enter a valid choice: Y, N, or I!");
}
}

function mcs3(){
var n3=prompt("Would you like to apply for HF MEdicare (Y=Yes, N=No)","");
if (n3=="Y"){
mcs4a();
}
if (n3=="N"){
mcs4();
}
else {
alert("Enter a valid choice: Y or N!");
}
}

function mcs4(){
var n4=prompt("Do you have a caretaker relative who claims you on their taxes (Y=Yes, N=No)","");
if (n4=="Y"){
alert("Follow standard prequalification with caretaker relative as the income");
}
if (n4=="N"){
alert("Refer to the HRA/LDSS/SLDSS to apply for benefits (CODE E01H)");
}
else {
alert("Enter a valid choice: Y or N!");
}
}

function mcs4a(){
alert("Warm transfer to Medicare Advertising to apply for HealthFirst Medicare (Code WTS)");}

mc1();
<html>
<head />
<body>
<script src="testdrop.js"></script>

</body>
</html>


texts:
This is an update from An Update on my TileMap Class. It's a tileMap class for a top-down old-school final fantasy game. User @Tim gave me suggestions and I updated some of the code accordingly.

Tile.java

import com.stardust.rpgtest2.gfx.Assets;
import java.awt.image.BufferedImage;

public enum Tile
{
    Grass(1, Assets.grass, false),
    Dirt(2, Assets.dirt, false),
    Tree(3, Assets.tree, true),
    Blank(36, Assets.blankTile, false);

    public int texKey;
    public BufferedImage texture;
    public boolean collidable;
    Tile(int texKey, BufferedImage texture, boolean collidable)
    {
       this.texKey = texKey;
       this.texture = texture;
       this.collidable = collidable;
    }
    public static BufferedImage getTileImage(int texKey1)
    {
        BufferedImage image;
        switch(texKey1)
        {
            case 1:
            {
                image = Grass.texture;
                break;
            }
            case 2:
            {
                image = Dirt.texture;
                break;
            }
            case 3:
            {
                image = Tree.texture;
                break;
            }

            case 36:
            {
                image = Blank.texture;
                break;
            }
            default:
            {
                image = Blank.texture;
                break;
            }
        }
        return image;
    }
}

TileMap.java render() method

public void render(Graphics g)
    {

        for(int y = 0; y < tilemap.length; y++)
        {
            for(int x = 0; x < tilemap.length; x++)
            {
                int textureType = tilemap[x][y];

                BufferedImage texture =  Tile.getTileImage(textureType);
                g.drawImage(texture, posX, posY, null);
                posY += 32;
            }
            posX += 32;
            posY = Game.mapY;
        }
        posX = Game.mapX;
        posY = Game.mapY;
    }


texts: Generating (presumably) unique `nonce` fields for Twitter OAuth

texts:
This is code that's part of a library (closed source) that I have that generates a unique nonce value for Twitter OAuth. Essentially, it generates a random number, combines it in string form with an extra string separated by a pipe, computes a Sha-1 hash, and then repeats the process if the Sha-1 hash (when converted to Base64) contained any non-alpha-numeric characters, which are subsequently stripped.

/// <summary>
/// Generates a (presumably) unique NONCE string for use in Twitter OAuth requests.
/// </summary>
/// <param name="extra">Extra data to add during generation.</param>
/// <returns>
/// A (presumably) unique NONCE string.
/// </returns>
/// <remarks>
/// While we can assume the generated NONCE strings will be somewhat unique, there is a small possibility that they will not be, and in such cases a new NONCE should be generated.
///
/// The generated NONCE values are 32 characters in length, and are generated by a Sha-1 hash and a Random generator, which generates four random numbers to be hashed until the generated string is 32 characters in length.
/// </remarks>
public string GenerateNonce(string extra = "")
{
    string result = "";
    SHA1 sha1 = SHA1.Create();

    Random rand = new Random();

    while (result.Length < 32)
    {
        string[] generatedRandoms = new string[4];

        for (int i = 0; i < 4; i++)
        {
            generatedRandoms[i] = rand.Next().ToString();
        }

        result += Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(string.Join("", generatedRandoms) + "|" + extra))).Replace("=", "").Replace("/", "").Replace("+", "");
    }

    return result.Substring(0, 32);
}

The idea is to generate somewhat unique nonce strings for use with Twitter OAuth (et al.).

I use the term "presumably," because, while it's not considered a bug that the nonce strings will not be guaranteed to be unique, collisions are expected to be fairly rare. I do welcome any and all suggestions that would lead to more uniqueness.


texts: Direct to another folder with .htaccess file

texts:
Lets say my folder structure looks like this

someproject/v5/.htaccess
someproject/5.0.1/lib.js
someproject/5.0.1/assets/img/png/anotherfolder/helloworld.png
someproject/5.0.2/lib.js
someproject/5.0.2/assets/img/png/anotherfolder/helloworld.png

When user enters url's like (and lets say I am the owner of google.com):

www.google.com/someproject/v5/lib.js
www.google.com/someproject/v5/assets/img/png/anotherfolder/helloworld.png

I want him to be redirected to version i want using the .htaccess file, example if i want to serve version 5.0.1, then the user will be redirected to this:

www.google.com/someproject/5.0.1/lib.js
www.google.com/someproject/5.0.1/assets/img/png/anotherfolder/helloworld.png

Only one thing may change the version number, this does not work (.htaccess file content):

AddType application/javascript .js
AddType text/css .css

AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)/(.*) "https://google.com/release/theme/5.0.1/$1/$2" [R=302,L]

How can I make it only change v5 with my version number (syntax) ?


texts: Loading articles dynamically on page change

texts:
I just created a script on jQuery which loads my articles dynamically with an AJAX call if the user changes the page.

I added some cool effects like the articles move on the left, then the new ones appear in fade while a loading black screen cover the articles.

The thing is, I'm afraid my code is too heavy and not really well optimized. Could you give me your feedback about it? By the way, do you have any idea if Google is going to be able to read all my articles with that system?

$(".pages li a").click(function(e){ // IF PAGE NUMBER IS CLICKED
    e.preventDefault();
    $(".pages li a").removeClass("active");
    $(this).addClass("active");

    //VARIABLES
    var currentPage=currentPage;
    var nextPage=$(this).attr("data-page");
    var currentCategory="1";

    //SHOW DYNAMIC LOADING WINDOW
    $(".layerarticles").before("

");
    $(".layerloading").height($(".layerarticles").height());
    $(".layerloading img").css("margin-top",$(".layerarticles").height()/2-16);
    $(".layerloading").fadeIn("slow",function(){

    //DATA LOAD
    $.post("ajax/articles-request.php", { currentPage: currentPage, nextPage: nextPage },function(data){ //AJAX CALL

            //WE KICK ALL OLD ARTICLES
            $(".layerarticles").animate({"margin-left":"-=630px"},'slow','easeOutQuint',function(){
                $(".layerarticles").css("height",$(".layerarticles").height());
                $(".layerarticles article").remove();
                $(".layerarticles").css("margin-left","0px");

                //WE MAKE APPEAR THE OTHERS IN THE HTML
                $.each(data, function(){
                    $(".layerarticles").append("

"+this.title+"

"+this.chapeau+"

");
                });

                //WE SHOW THEM WITH FADE EFFECT
                $('.layerarticles article:hidden:first').delay(100).fadeIn("fast",function(){
                     if($('.layerarticles article:hidden').length!=0){
                        $(this).next().delay(100).fadeIn("fast",arguments.callee);
                     }else{

                        //ONCE ALL ARTICLES APPEARED WE REMOVE THE LOADING
                        $(".layerloading").fadeOut("slow",function(){
                            $(".layerloading").remove();
                        });

                     }
                });

            });
        }, "json");

    });
});


texts: Recursive factorial calculations in Rust

texts:
I am trying to calculate very large factorials. I am looking to speed it up as 10000! takes approximately a minute and a half.

extern crate num;
use num::bigint::BigInt;
use num::bigint::ToBigInt;

fn tree_fact(n: u64) -> BigInt {
    if n < 2 {
        return 1.to_bigint().unwrap();
    }
    return factorial(1, n)
}

fn factorial(low: u64, high: u64) -> BigInt {
    if low +1 < high {
        let mid = (low + high) / 2;
        return factorial(low, mid) * factorial(mid + 1, high)
    }
    if low == high {
        return low.to_bigint().unwrap();
    }
    return low.to_bigint().unwrap() * high.to_bigint().unwrap();

}

fn main() {
    let fac_value = tree_fact(10000);
    println!("{}", fac_value);
}

I am also concerned with following best practices as I am new to programming in Rust so feel free to point out where I am bending any rules.


texts: Generating table rows for a form using js

texts:
As you can see, the following is pretty ugly and seems to be unnecessarily long.
Is there a shorter/neater way to do this?

function addNewRow(body, id){
    var myRow = document.createElement("tr");
    myRow.id = id+'';
    var c1 = document.createElement("td");
    var c2 = document.createElement("td");
    var c3 = document.createElement("td");
    var c4 = document.createElement("td");
    var d = document.createElement("div");
    myRow.appendChild(c1);
    myRow.appendChild(c2);
    myRow.appendChild(c3);
    myRow.appendChild(c4);
    myRow.appendChild(d);

    var i1 = document.createElement("input");
    var i2 = document.createElement("input");
    var i3 = document.createElement("input");
    var i4 = document.createElement("input");

    i1.type = 'text';
    i1.id = 'drwID_' + id;
    i1.name = 'drwID_' + id;
    i1.disabled = !editing;

    i2.type = 'text';
    i2.id = 'pos_' + id;
    i2.name = 'pos_' + id;
    i2.disabled = !editing;

    i3.type = 'text';
    i3.id = 'stm_' + id;
    i3.name = 'stm_' + id;
    i3.disabled = !editing;

    i4.type = 'text';
    i4.id = 'note_' + id;
    i4.name = 'note_' + id;
    i4.disabled = !editing;

    c1.appendChild(i1);
    c2.appendChild(i2);
    c3.appendChild(i3);
    c4.appendChild(i4);
    body.appendChild(myRow);
}


texts: Find the product of digits at odd/even places

texts:
The 'score' of a race is given.

We have to calculate the 'bonus points' to be given to the participant.

The 'bonus points' are dependent on the relation between product of digits at even places and product of digits at odd places.

So essentially I have to find the product of digits at even and odd places.

I first counted the number of digits in 'score' and then went on storing the product of digits in odd/even places in separate integers reducing one digit at a time

Code in Java

import java.util.Scanner;

class BonusPoints {
    public static int countDigits(int dist) {
        int counter=0;
        while (dist>0) {
            dist /= 10;
            counter++;
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int dist = sc.nextInt();
        int bonus=0;
        int prodOdd = 1;
        int prodEven = 1;
        int currDigit = 0;

        if (dist < 0) {
            System.out.printf("Invalid Input ");
            System.exit(0);
        }

        int counter = countDigits(dist);
        int lol = counter;
        //System.out.println("Number of Digits are " + counter);

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

            //System.out.println("Current Dist " + dist);

            currDigit = dist % 10;
            //System.out.println("Current Digit " + currDigit);

            if (counter % 2 == 0){
                prodEven *= currDigit;
                //System.out.println("Current ProdEven "+prodEven);
            }
            else {
                prodOdd *= currDigit;
                //System.out.println("Current ProdOdd " +prodEven);
            }

            dist /= 10;
            counter--;
        }

        if (prodOdd == prodEven)
            bonus = 2 * prodOdd;
        else
            bonus = prodOdd > prodEven ? prodOdd : prodEven;

        System.out.println("The bonus is "+bonus);
    }
}

Those comments were used for debugging process while writing the code

Is there a better method to do this and what are changes that one can make to this code to optimize it?


texts: Best way to handle elements of a private array

texts:
This feels like a simple question, but I'm wondering what the best way would be to manage the elements of a private, fixed-size array.

Context: I'm making a simple particle engine, and my Emitter class will smoothly interpolate between up to 8 colors per Particle, depending on the Particle's Life value. I have that part implemented and it works great. However, my question is more concerning the Color[] array itself.

Suppose I have the following code. What I would like to do is be able to alter the 8 values in a simple and logical way:

public sealed class Emitter
{
    private readonly Color[] _colors = new Color[8];
}

One option would be to return the whole array, but according to CA1819, a property should not return an array, since it warns the array is mutable unless a copy is made. However, this is the behavior I want, so it might make sense to do it:

public Color[] Colors
{
    get { return _colors; }
}

Another option would be to do a simple get/set and pass a desired index as a parameter; this has the benefit of checking for success, but is more cumbersome to use because of the out parameter. In addition, there's nothing that explicitly states the min/max values of the color array, which means I'd have to have a const byte MaxColors = 8; or the like:

public bool GetColor(int id, out Color result)
{
    if (id >= 0 && id < 8)
    {
        // Valid index, return the color at that position
        result = _colors[id];
        return true;
    }
    // Invalid index, return the default color (R:0, G:0, B:0, A:0)
    result = default(Color);
    return false;
}

public void SetColor(int id, Color value)
{
    if (id >= 0 && id < 8)
    {
        _colors[id] = value;
    }
}

public void SetColor(param Color[] values)
{
    // Set all 8 colors, using default values if not enough arguments are supplied
    if(values != null)
        for(int i = 0; i < 8; i++)
            if (i > values.Length)
                _colors[i] = default(Color);
            else
                _colors[i] = values[i];
}

Finally, I could do the brute force approach and make a property for each color value, and I probably don't need to explain why that's a bad idea:

public Color Color1
{
    get { return _colors[0]; }
    set { _colors[0] = value; }
}
...
public Color Color8
{
    get { return _colors[7]; }
    set { _colors[7] = value; }
}

So... yeah. Based on my needs, which approach seems to make the most sense? I'm leaning towards the getter/setter pattern. Is there another way I haven't considered that would be desireable in this situation?


texts: Making 90% similar code for 20 different objects

texts:
Basically, I have 20 very similar objects and most importantly I want to do the same thing for all of them.
This is the ImportProcessor class for AutomobileExpense (AutomobileExpenseDataImportProcessor). And in this scenario I would need another 19 ImportProcessor classes for the other similar objects.
I have made common logic with generic methods or not in the base class. The only things I cannot make generic or without some deep reflection logic are:

the enums in the constructor
the repository in the constructor
the specific Object properties in if and else statements, method which returns Guid -> this.ProcessDebt() and his second and third arguments xrefDebt.DebtsAutomobileExpense and converted.DebtsAutomobileExpense

public class AutomobileExpenseDataImportProcessor : BaseDebtDataImportProcessor
    {
        private GenericRepository<DebtsAutomobileExpense> _repo;
        public AutomobileExpenseDataImportProcessor(MyCompanyIUnitOfWork unitOfWork, IAuthenticationUserSession user, SystemDecision systemDecisons, params Expression<Func<XRefClientBusiness, object>>[] include)
            : base(unitOfWork, user, systemDecisons, include)
        {
            this._repo = this._unitOfWork.DebtsAutomobileExpenseRepository;
            this._objectType = ObjectType.DebtsAutomobileExpense;
            this._importObjType = ImportObjectType.DebtAutomobileExpense;
            this._flag = ClientDebtFlag.AutomobileExpense;
        }

        protected override void ImportDebt(XRefClientBusiness xrefDb, XRefClientBusinessDebt converted)
        {
            if (this.IsDebtForUpdate(xrefDb, this._flag)) // Update
            {
                var xrefDebt = xrefDb.XRefClientBusinessDebts.FirstDefault(f => f.DebtSection.HasFlag(this._flag));
                Guid updatedId = this.ProcessDebt(xrefDb, xrefDebt.DebtsAutomobileExpense, converted.DebtsAutomobileExpense, this._flag, this._repo);

                this.AddUpdatedObjectToResult(updatedId, this._flag.ToString(),this._importObjType);
                this.AddSystemDecisionObject(updatedId, this._objectType, ActivityAction.Modified);
            }
            else // Insert
            {
                Guid insertedId = this.ProcessDebt(xrefDb, null, converted.DebtsAutomobileExpense, this._flag, this._repo);

                this.AddCreatedObjectToResult(insertedId, this._flag.ToString(), this._importObjType);
                this.AddSystemDecisionObject(insertedId, this._objectType, ActivityAction.Added);
            }
        }
    }

I have set up everything needed to change in the constructur, except two properties in the If Else statement. Imagine when I create the another 19 super similar cases, I will update the constructor enums and 3 places inside the If else statement like this:
        {
            this._repo = this._unitOfWork.DebtsAutomobileExpenseRepository; // Update
            this._objectType = ObjectType.DebtsAutomobileExpense; // Update
            this._importObjType = ImportObjectType.DebtAutomobileExpense; // Update
            this._flag = ClientDebtFlag.AutomobileExpense;
        }

and
// update second and third arguments (after the xrefDebt. and coverted. )
Guid updatedId = this.ProcessDebt(xrefDb, xrefDebt.DebtsAutomobileExpense, converted.DebtsAutomobileExpense, this._flag, this._repo);

I think this is the best approach, because it is clearer, the approach when every object deal with its own insert/update logic sound way more OOP correct.
But anyway, do you think there is a better way?
I was thinking for example, trying to make one generic ImportProcessor class, instead of 20, which will be called with all the needed enums in the constructor. The correct repository again in the constructor and for this part xrefDebt.DebtsAutomobileExpense to use some kind of reflection logic to take the correct property, but that sounds a bit confusing.


texts: Project Euler #18 in Python: Maximum sum down a triangle of numbers

texts:
I've solved Project Euler #18 in Python but think my code and algorithm can be improved. Here is the problem:

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

3
7 4
2 4 6
8 5 9 3

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

  Find the maximum total from top to bottom of the triangle below:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

  NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method!

And I want with an bottom-up calculation to find the best path down. Here is my code:

import time

num_pyr = '''75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'''

def break_pyramid(num_pyr):
    '''
    Breaks the number string into an array
    '''
    pyramid = []
    rows = num_pyr.split('\n')
    for row in rows:
        pyramid.append([int(i) for i in row.split(' ')])
    return pyramid

def add_from_under(upper_row, lower_row):
    '''
    Takes the maximum of the legs under upper row to each index to add up from bottom
    Parameters
    ----------
    upper_row : len n
    lower_row : len n + 1

    Returns
    -------
    new_upper_row
    '''
    greater_vals = [max(lower_row[i:i+2]) for i in range(len(upper_row))]
    return [x + y for x, y in zip(upper_row, greater_vals)]

def main():
    pyramid = break_pyramid(num_pyr)[::-1]
    for i in range(len(pyramid)-1):
        new_upper = add_from_under(pyramid[1], pyramid[0])
        pyramid[1] = new_upper
        del pyramid[0]
    return pyramid[0][0]

if __name__ == '__main__':
    t1 = time.time()
    best_path = main()
    op_time = 1000000 * (time.time() - t1)  # us
    print("Calculated {} in {:.1f} us".format(best_path, op_time))

I think improvements can be made in my main() since I am using del. Should del be avoided for any reason?


texts: Java Max-Stack implementation to return maximum value in the stack

texts:
I have written the below program to write a Java stack implementation. I have added a method which returns the maximum value in the stack, e.g, a pop. The implementation for this is based on the Max Heap Sort algorithim. I have little doubt on the time complexity analysis - it's not \$O(\log n)\$ is it?

public class Stack {

    int top = -1;
    int[] stack;

    public Stack(int size) {
        stack = new int[size];
    }

    public void push(int v) {
        if (top == stack.length - 1) {
            System.out.println("Oveflow!!");
            return;
        }
        stack[++top] = v;
    }

    public void pop() {
        if (top < 0) {
            System.out.println("Empty stack");
            return;
        }

        stack[top] = 0;
        top--;

    }

    public int getMax() {

        int[] c = stack.clone();
         // not a complete heap sort, but with below approach, i am trying bubble up.
        // build the heap starting from n/2, as any nodes after n/2 are leaf(s)
        for (int j = stack.length / 2; j >= 0; j--) {
            buildMaxHeap(c, j, c.length - 1);
        }

        return c[0];
    }

    private void buildMaxHeap(int[] clone, int i, int j) {
        int root = i;

        while (root * 2 + 1 <= j) {
            int c = root * 2 + 1;

            if ((c + 1) <= j && clone[c] <= clone[c + 1]) {
                c = c + 1;

            }

            if (clone[root] < clone[c]) {
                int t = clone[root];
                clone[root] = clone[c];
                clone[c] = t;
                root = c;
            } else {
                root++;
            }
        }

    }

    public void display() {
        System.out.println("------------------------");
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }
    }
}


texts: Swapping variable length strings asynchronously with connected microcontroller (Byte-banging)

texts:
I have an AT89S52 and an AT89C4051 microcontroller (both in the 8052 family) in which the bit lines of the data bus, one control pin and one status pin are connected together. In code, the data bus is labelled "D", the status pin is labelled "ACK" and the control pin is labelled "ACT".

The AT89S52 does many tasks, it cannot afford to hold up other tasks over data transfer to the AT89C4051.

The AT89C4051 is ok with putting everything else on hold when it communicates with the AT89S52.

My code for processing one byte from the AT89C4051 to AT89S52 is as follows:

uCdat:
      mov D,A       ;Prepare to send one byte
      clr ACT       ;Send one byte now
      jb ACK,$      ;Wait until remote received it
      mov D,#0FFh   ;Tristate bus
      setb ACT      ;Tell remote were ready
      jnb ACK,$     ;Wait until remote has data
      mov A,D       ;Read result
    ret

It simply takes the value of the local accumulator, sends it down to AT89S52 and waits until AT89S52 has a response then its stored back in the local accumulator. This is perfect for the AT89C4051 but not for the AT89S52 since its a busy microcontroller.

I made the following code as an attempt to receive a set of data from the AT89C4051 to memory and send code back. I feel I have to do one byte at a time back and forth and the direction in which data is sent is the level of the ACT and ACK lines.

The local memory format is as follows.

data at start address of REQMEM represents number of data bytes to follow and can be any value from 0 to 15.

So if REQMEM = 2, then REQMEM+1 = 1st byte of data and REQMEM+2 = 2nd (and last) byte of data.

I'd like to know if this code can be simplified, but still can be run asynchronously. This function will be called very frequently from the busy AT89S52.

miniuCdat:
  ;UCIO=memory bit for data direction: 0=incoming, 1=outgoing
  jb UCIO,noucinc
    ;mode here is accept data...
    jb ACT,noUdat  ;...only if remote lowered ACT line
      mov D,#0FFh  ;tristate data line
      setb UCIO    ;change mode to "send result"
      mov A,D      ;get a byte from remote
      clr ACK      ;tell remote we got byte
      ;REQRES=memory bit to know what were doing.
      ;REQRES: 0=requesting data. 1=sending result
      jb REQRES,noUdat
        ;here we store data into local request memory (REQMEM)
        mov @R0,A
        cjne R0,#REQMEM,noUCs
          ;We are on byte 1 which is length of data
          anl A,#0Fh ;make length 15 bytes max
          mov R2,A
          inc R2     ;make counter = length + 1
        noUCs:
        inc R0 ;go to next byte in REQMEM
        djnz R2,noUCe
          ;here the length went back to 0, so reset pointer
          mov R0,#REQMEM
        noUCe:
    noUdat:
    ret
  noucinc:
  ;Here we are sending a 1-byte response back...
  jnb ACT,noUdat2 ;...only if remote raised the ACT line
    mov A,@R1           ;Load byte from memory
    jb REQRES,noUdat2b  ;If we are requesting data
      clr A             ;Make zero as the result
    noUdat2b:
    mov D,A             ;Send result out to data line
    setb ACK            ;Tell remote we sent data out
    clr UCIO            ;switch mode to "accept data"
    jnb REQRES,noUdat2
      cjne R1,#REQMEM,noUCs2 ;Again, 1st byte is length
        anl A,#0Fh
        mov R3,A
        inc R3
      noUCs2:
      inc R1
      djnz R3,noUCe2
        mov R1,#REQMEM ;Go to beginning of ram if all bytes are processed
      noUCe2:
  noUdat2:
ret


texts:
Assume the server is sending data to our app at regular intervals, at least once per second. The received data is parsed and stored in memory as a POJO. A blocking queue is processing data in a worker thread.

Suppose I want to use a very simple object pool, so I don’t have to create a new POJO for each server response. I don’t want to use e.g. Apache Commons Pool.

Would the following implementation suffice?

public abstract class ObjectPool<T> {

    private final Stack<T> mPool;

    public ObjectPool() {
        mPool = new Stack<T>();
    }

    public T obtain() {
        if (mPool.isEmpty()) {
            return create();
        } else {
            return mPool.pop();
        }
    }

    public void recycle(T object) {
        if (null != object) {
            destroy(object);
            mPool.push(object);
        }
    }

    public void clear() {
        mPool.clear();
    }

    public int getSize() {
        return mPool.size();
    }

    protected abstract T create();

    protected abstract void destroy(T object);

}

Can I shoot myself in the foot using this? Any caveats I’m not seeing?

Thanks!


texts:
I am brushing up my Data Structure knowledge (for preparation for internship interviews) and I started by implementing a very simple Linked List class. This is by no means intended to be able to replace the Java library just to be something robust enough for making me understand and remember how to implement a Linked List.

LinkedList class with private Node class:

public class LinkedList<T> {

    private Node _first;
    private int _size;

    public LinkedList() {
        _first = null;
        _size = 0;
    }

    public int getSize() {
        return _size;
    }

    public void add(T data) {
        Node current = _first;

        if (current == null) {
            _first = new Node(data);
            _size++;
            return;
        }

        while (current.getNext() != null) {
            current = current.getNext();
        }

        current.setNext(new Node(data));
        _size++;
    }

    public void add(T[] array) {
        for (T data : array) {
            add(data);
        }
    }

    public void remove(T data) {
        Node current = _first;
        Node next = current.getNext();

        if (_first.getData().equals(data)) {
            if (_size == 1) {
                _first.setData(null);
                _size--;
                return;
            }
            _first.setData(null);
            _first = _first.getNext();
            _size--;
            return;
        }

        while (next != null) {
            if (next.getData().equals(data)) {
                current.setNext(next.getNext());
                next = null;
                _size--;
                return;
            }
            current = next;
            next = current.getNext();
        }
    }

    private class Node<T> {

        private T _data;
        private Node _next;

        public Node(T data) {
            _data = data;
            _next = null;
        }

        public void setData(T data) {
            _data = data;
        }

        public T getData() {
            return _data;
        }

        public void setNext(Node next) {
            _next = next;
        }

        public Node getNext() {
            return _next;
        }
    }
}

Anything I could do to make it better?


texts: Directory listing, sorting and filtering in F#

texts:
Here is my first try at F#. My only functional experience is from JS.

This program takes a path as an argument and presents the user with numbered subdirs in that path. The user then selects one of the subdirs by entering it's number and the program opens explorer with the newest subdir of the selected subdir.

Any comments will be greatly appreciated — shorter and better syntax, conversions to point-free style, structuring...

open System
open System.IO

let toDirWithCreationDate path =
    (path, Directory.GetCreationTime(path))

let getLatestSubDir =
    Seq.map toDirWithCreationDate
    >> Seq.sortByDescending snd
    >> Seq.head
    >> fst

let getNumberedSubDirTuples =
    let ints = Seq.initInfinite (fun n -> n + 1)
    Directory.GetDirectories
    >> Seq.sort
    >> Seq.zip ints

let printDirMenu =
    Seq.iter (fun (a, b) -> printfn "%A %A" a b)

let openDir (dir:string) =
    ignore (System.Diagnostics.Process.Start(dir))

[<EntryPoint>]
let main argv =
    let path = argv |> Seq.head
    let dirsSeq = getNumberedSubDirTuples path
    printDirMenu dirsSeq
    let dirNr = System.Console.ReadLine()
    let dir =
        dirsSeq
        |> Seq.tryFind(fun (a,b) -> a = int(dirNr))
    let latestSubdir =
        match dir with
            | Some d -> Directory.GetDirectories (snd d) |> getLatestSubDir |> openDir
            | None -> printfn "Invalid input"
    0


texts: Scaling up the intelligent concatenation of 2 columns in R

texts:
I've got a huge dataset in R which contains (among other things) 2 columns indicating "Term Code", which are "Term Code" and "Term Code1".

"Term Code" is the mostly-correct column, which usually contains a 6-digit code for year and academic term:

> head(data$Term_code)
[1] 201230 201230 201230 201230 201230 201230

however, over the years that this field was populated, on occassion this field was either left blank or populated with only the last 2 digits:

> head(data$Term_code[nchar(data$Term_code) < 6], 100)
  [1] NA NA NA 70 NA NA 10 NA NA 30 NA 30 NA 40 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [35] NA 10 NA 30 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [69] NA NA NA 50 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

A SAS analyst did his best to fill construct another field, "Term_code1", with the preferred 6-digit version of the code where it's missing or truncated in "Term_code".

Now I need to combine these 2 columns into a single, maximally-complete column vector within the dataframe.

I did this using a for loop, which works on the small scale, but is slow at best with Big Data and at worse breaks by hitting the max memory size (even when that value is maxed out).

This is how I wrote it:

  for(i in 1:nrow(data)){
    if(is.na(data$Term_code[i]) && !(is.na(data$Term_code1[i]))){
      data$Term_code[i] <- data$Term_code1[i]
    }
  } # Took a very long time to run, but improves data a lot

  for(i in 1:nrow(data)){
    if(nchar(data$Term_code[i]) < (nchar(data$Term_code1[i]))){
      data$Term_code[i] <- data$Term_code1[i]
    }
  } # Broke after hours due to memory constraint

How should I have written it?

While I can't provide the actual data for reproducibility, if the description of these 2 vectors is insufficient perhaps this can approximate it close enough for testing purposes:

a                  <- data.frame(matrix(nrow = 999999, ncol = 2))
a[, 1]             <- runif(min = 201210, max = 201560, n = 999999)
a[,1]              <- round(a[,1])
b                  <- sample(a[,1], 1000)
a[a[,1] %in% b, 1] <- NA
b                  <- sample(a[,1], 250)
a[a[,1] %in% b, 1] <- substr(b, 5, 6)
a[,2]              <- runif(min = 201210, max = 201560, n = 999999)
b                  <- sample(a[,2], 150)
a[a[,2] %in% b, 2] <- NA


texts: Given N, generate sequence of random numbers from 0 to N - 1 with no repetitions

texts:
Problem statement:
Given an integer n, write a function to return an array of size n, containing each of the numbers from 0 to n-1 in a random order. The numbers may not repeat and each number must show up exactly once.

Solution # 1:
Generate an ordered array then shuffle it

private static int[] Shuffle(int n)
{
    var a = Enumerable.Range(0, n).ToArray();
    var random = new Random();
    for (int i = 0; i < a.Length; i++) {
        var j = random.Next(0, i);
        Swap(a, i, j);
    }
    return a;
}

private static void Swap(int[] a, int i, int j)
{
    var temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

Solution # 2:
Generate empty array and add items in random order

private static int[] Shuffle(int n) {
    var a = new int[n];
    var random = new Random();
    for (int i = 0; i < a.Length; i++) {
        var j = random.Next(0, i);
        Swap(a, i, j);
    }
    return a;
}

private static void Swap(int[] a, int i, int j) {
    var temp = i;
    a[i] = a[j];
    a[j] = temp;
}

I'm not fully persuaded about the randomness of solution # 2. Are there better ways of achieving the solution? I'm assuming that whatever approach is taken the solution can only be produced in linear time. Is this conclusion correct?


texts:
We have an action merge for two projects. In the projects we have different modules like Feed, Files, Post etc....

modules Convert
class Merge
    attr_accessor :source_ids, :destination_id, :sources, :destination

    def initialize(source_ids, destination_id)
        @source_ids = source_ids.class == Array ? source_ids : [source_ids]
        @destination_id = destination_id
        @sources = Modelname.where("id in (?)", @source_ids).all
        @destination = Modelname.where("id in (?)", @destination_id).first
    end

    def merge
        sources.each do |source|
          ActiveRecord::Base.transaction do
            Convert::Feed.new(source, destination).merge
            Convert::File.new(source, destination).merge
            Convert::Post.new(source, destination).merge
            ## There are many more modules - code comes here
          end
        end
    end
end

class Feed
    def initialize(source, destination)
        @source = source
        @destination = destination
    end

    def merge
        #Feed merge code here
    end

end

class File
    def initialize(source, destination)
        @source = source
        @destination = destination
    end

    def merge
        #File merge code here
    end

end

class Post
    def initialize(source, destination)
        @source = source
        @destination = destination
    end

    def merge
        #Post merge code here
    end

end
end

a = Convert::Merge.new(source_id, destionation_id)
a.merge

Is this correct way to handle this action ? How can I handle this in a better way ?


texts:
I've tried to implement integer partition algorithm as described in blogpost below (author implemented it in Python):
Generating integer partitions

I'm still trying to learn best practices in producing clean code. I would also be thankful for any performance tips.

My code:

struct NumberPartition {
    a: Vec<i32>,
    k: i32,
    y: i32,
    x: i32,
    l: i32,
}

impl NumberPartition {
    pub fn new(n: i32) -> Self {
        NumberPartition {
            a: vec![0; (n + 1) as usize],
            k: 1,
            y: n - 1,
            x: 0,
            l: 0
        }
    }

    fn partition(&mut self) -> Option<Vec<Vec<i32>>> {
        let mut buf: Vec<Vec<i32>> = Vec::new();
        while self.k != 0 {
            self.x = self.a[(self.k - 1) as usize] + 1;
            self.k -= 1;
            while 2 * self.x <= self.y {
                self.a[self.k as usize] = self.x;
                self.y -= self.x;
                self.k += 1;
            }
            self.l = self.k + 1;
            while self.x <= self.y {
                self.a[self.k as usize] = self.x;
                self.a[self.l as usize] = self.y;
                buf.push(self.a[..(self.k + 2) as usize].to_vec());
                self.x += 1;
                self.y -= 1;
            }
            self.a[self.k as usize] = self.x + self.y;
            self.y = self.x + self.y - 1;
            buf.push(self.a[..(self.k + 1) as usize].to_vec());
        }
        Some(buf)
    }
}

fn main() {
    let b = NumberPartition::new(6).partition();
    for i in b.iter() {
        println!("{:?}", i);
    }
}


texts:
$("#colors_added").html(parseFloat($("#colors_added").html()) + 1);

This JS line makes my IDE go Duplicated jQuery selector with the following explanation:

  Checks that jQuery selectors are used in an efficient way. It suggests to split descendant selectors which are prefaced with ID selector and warns about duplicated selectors which could be cached.

I've made a screenshot of it:

Is my IDE on to something here, can I write this in a better way?


texts:
I have written selection sort in Swift.

Sort([2,4,23,268,9,0]).bySelection()

I am looking for ways to further improve this programme using Swift language features.

struct Sort {

        private var elements:[Int]

        init(_ unsortedElems: [Int]) {
            self.elements = unsortedElems
        }

        func bySelection() -> [Int] {
            return selectionSortAlgo(input: elements)
        }

      }

  typealias SelectionSort = Sort
  extension SelectionSort {

    fileprivate func selectionSortAlgo(input:[Int]) ->[Int] {
        var elements = input
        let size = input.count

        for (index, item) in elements.enumerated() {
            var minimumIndex = index

            for subindex in  (index+1)..<size {
                if elements[subindex] < elements[minimumIndex] {
                    minimumIndex = subindex
                }
            }

            if minimumIndex != index {
                elements[index] = elements[minimumIndex]
                elements[minimumIndex] = item
            }
        }
        return elements
    }
}


texts:
I want to make a command-line text editor in python. Is this good code?

from termcolor import *
import os

while True:
    files = os.listdir()
    bufname = input("File name: ")
    title = cprint("Ganesha Editor v1.0", "green")
    controls = cprint("Type $exit to exit text editor. It autosaves.", "blue")

    def write():
        print("Compose Something Below:\n\n")
        text = input()
        if text == "$exit":
            exit()

        else:
            if bufname in files:
                os.remove(bufname)
                create = open(bufname, "w")
                create.close()

                autosave = open(bufname, "a")
                autosave.write(text)
                autosave.write("\n")
                autosave.close()

            else:
                autosave = open(bufname, "a")
                autosave.write(text)
                autosave.write("\n")
                autosave.close()

    while True:
        write()

I prettified the code with 8 spaces for the indents.

Does anyone like this code? It's very minimal, and no one will like it, but, I'm trying to make a secondary text-editor.


texts: jQuery and cross browser input fields focus handling

texts:
I have a form and need to be able to highlight/decorate fields as they gain focus (change their background color, border). I'm also decorating their corresponding 'labels'.

All works fine where it needs to: FF, Safari, IE 7, 8 and 9

Problem 1 cropped up with IE7 and changing background color of drop down box. There I had to resort to plain old JS to access the element and use 'onfocusin' and 'onfocusout' events otherwise it'd take 2 clicks to use the field.

Problem 2 was with Safari and how it handles 'focus' event with radio buttons. For that I'm using 'mouseenter' and 'mouseleave' events to change the color of their 'labels'.

Is there a cleaner way of doing this? The caveats are I have no control of the HTML whatsoever and I can't use anything other than jQuery 1.4.3 That's all dictated by content management system I must work with.

Here's a complete 99.9% 'production' code example: http://jsfiddle.net/HenriPablo/YvDPa/3/

Script in question:

$(document).ready( function(){

    /* PROFILE PAGE ONLY -> get rid of separator border on shipping addres block when editing any of the shipping addresses */
    if( $('#formShippingAddress').length > 0 ){
        $( 'table#block\\.crmshipping tbody tr td.block\\.crmshipping\\.text' ).css('border','none');
    }

    /* highlight input field labels when input field has focus */
    /* see if event bubble - this is critical for handling decoration of select drop down boxes in IE7 */
    if( $.support.changeBubbles){

        var partialID = 'table[id^="page"]'
        var focusable = $( partialID + ' input[type="text"], ' + partialID + ' input[type="password"], ' + partialID + ' select, ' + partialID + ' input[type="checkbox"]' );
        var clickable = $( partialID + ' input[type="radio"]' );

        focusable.focus( function( ){   decorate( $(this) ); })
        focusable.blur( function( ){ decorate( $(this) ); })

        clickable.mouseenter( function(){ decorate( $(this) ); })
        clickable.mouseleave( function(){ decorate( $(this) ); })

    } else { // bubbling support check

        var i, d = document.getElementsByTagName('select')

        for( i in d ){
            d[i].onfocusin = function() {
                this.style.backgroundColor = '#b4d5ec'
                $(this).closest("td").prev().addClass('highlightLabel');
            }
            d[i].onfocusout= function() {
                this.style.backgroundColor='#ffffff'
                $(this).closest("td").prev().removeClass('highlightLabel');
            }
        } // for

        $('table[id^="page"] input' ).focus( function( ){
            decorate( $(this) )
        })

        $('table[id^="page"] input').blur( function( ){
            decorate( $(this) );
        })
    } // handle  IE7

    function decorate( elm ){
        elm.toggleClass('highlightField');
        elm.closest("td").prev().toggleClass('highlightLabel');
    } // decorator function
});

Many thanks in advance :-)


texts: Set up of pandas dataframe with mixed datatypes including arrays from .mat file in a pythonic/numpy way

texts:
Coming from a heavy MATLAB background so excuse my un-pythonic ways. I'd like to get an idea of how a python coder would approach this simple set-up of a dataframe.

I'm importing a .mat file from experimental data, it is made such that each row pertains to a single trial for a set of conditions (subjectID,group etc...).

My goal is to create a pandas dataframe such that a single row contains an entire session (all trials for a given set of conditions)- this will hopefully be clearer in my code. This code works well, but I'd like to implement this elegantly given the capabilities of python/pandas/numpy.

import scipy.io
import pandas as pd
import numpy as np

raw_dat = scipy.io.loadmat('big_data_file.mat')
big_data = raw_dat['big_data']

#Define Constants
SUB = 0
GROUP = 1
SESS = 5
MEDS = 6
GAME = 8
EOB = 9
DIR = 12
COL = 13
REW = 14
RT = 15
c_set = [SUB, GROUP, SESS, MEDS, EOB]

#Filter for strategic version of task
st_data = big_data[big_data[:,GAME] == 2,:]

#Get unique conditional sets (subject,group,meds,eob,session)
unique_sets = np.unique(st_data[:,c_set],axis=0).astype(int)
valid_ind= (st_data[:,DIR] == 0) | (st_data[:,DIR] == 1)

#Set up string identities for groups/EoB
str_EOB = ('eye','button')
str_groups = ('young','elderly','parkinsons','BPD','adult_male','adult_female')

#Set up dictionary for creating DataFrame

dict_data = []
for line in unique_sets:

 #Select of data matching conditions
    set_ind = np.all(st_data[:,c_set].astype(int) == line,axis=1)
    select_data = st_data[np.logical_and(set_ind,valid_ind),:]

    #From this, create a dictionary of values to append into dataframe
    dict_data.append(
        {'subject_id' : line[0],'group' : str_groups[line[1]],'session' : line[2],'meds' : line[3],
         'eob' : str_EOB[line[4]],'dir_choice' : select_data[:,DIR],'col_choice' : select_data[:,COL],
         'outcomes' : select_data[:,REW],'RT' : select_data[:,RT]}
    )

df = pd.DataFrame.from_dict(dict_data)
df = df[['subject_id','group','meds','session','eob','dir_choice','col_choice','outcomes','RT']]

Where dir_choice, col_choice, outcomes, RT contain column vectors as its datatype.

Not sure if this will affect the methodology but the .mat file is approximately 200,000 rows


texts: Discord bot file requirement and object instantiation d20pfsrd follow-up

texts:
I have written a series of parsers for a discord bot that each reside in classes in their own files. Each parser class has 3 functions, 2 of them are for generating the response to the discord message based on the data received from an axios get call, (1 is an embedded link the other is a text fallback) and the 3rd function is a matching function that checks if a passed url will be handled by the parser. My current solution is to individually require the files and create instances of the objects in an array, and then use find to select the proper parser. My problem is as follows: This doesn't feel scaleable and I would like to find a way to require an arbitrary number of files and instantiate their respective objects in order to add more page types to parse. My main code is as follows:
require('dotenv').config()
const Discord = require('discord.js')
const axios = require('axios')
const Feats = require('./feats')
const Magic = require('./magic')

const client = new Discord.Client()
client.login(process.env.DISCORD_TOKEN)
const responders = [new Magic(), new Feats()]

client.on('message', getPage)
async function getPage (msg) {
  if (!msg.content.startsWith(process.env.d20URL)) return
  const url = encodeURI(msg.content)
  const responder = responders.find(responder => responder.match(url))
  if (responder) {
    try {
      const response = await axios.get(url)
      const message = responder.embedFormat(response)
      await msg.channel.send(message)
    } catch (e) {
      console.error(e)
      if (e.code === 50013) {
        const response = await axios.get(url)
        const message = responder.format(response)
        await msg.channel.send(message)
      }
    }
  }
}

My primary focus is on finding a way to condense the sections where I require the local files and create their respective objects, as potentially writing out a large list of files and objects feels smelly.
Any other advice is appreciated, especially in regards to the pyramid forming in the bottom for the error handling, as repeating the axios call feels strange.


texts: Array-search algorithm for identical sequences and character distances

texts:
Here is Python code written to perform the following operations:

Find each occurrence of a three-letter sequence in a character array (e.g. a sequence such as ('a','b','c')), including overlapping sequences of up to 2 shared characters.
Count the characters between the start of each sequence and the start of all identical sequences following it.
Every time the same number of characters results from #2, increment a counter for that specific number of characters (regardless of which character sequence caused it).
Return a dictionary containing all accumulated counters for character distances.

counts = {}
# repeating groups of three identical chars in a row
for i in range(len(array)-2):
    for j in range(i+1,len(array)-2):
        if ((array[i] == array[j]) & (array[i+1] == array[j+1]) & (array[i+2] == array[j+2])):
            if counts.has_key(j-i) == False:
                counts[j-i] = 1
            else:
                counts[j-i] += 1

This code was originally written in another programming language, but I would like to apply any optimizations or improvements available in Python.


texts: Multiple column sorting and arraging algorithm

texts:
Problem

The goal is to perform the following transformation:

Additionally, if two rows can be merged, they are combined into one:

Code

I wrote the following algorithm to solve this problem:

#include <vector>
#include <iostream>
#include <algorithm>

using Matrix = std::vector<std::vector<int>>;
using Column = std::vector<int>;

Column max_col(const Matrix &v) {
    return *std::max_element(v.begin(), v.end(),
                             [](auto& lhs, auto& rhs)
                             {
                                 return lhs.size() < rhs.size();
                             });
}

bool is_element_in_next_rows(const Matrix &v, int element,int row) {
    for (auto& col : v) {
        if (row >= static_cast<int>(col.size())) continue; // out of range
        if (std::lower_bound(col.begin()+row+1,col.end(),element) !=
            std::upper_bound(col.begin()+row+1,col.end(),element)) {
            return true;
        }
    }
    return false;
}

int min_element_in_row(const Matrix &v, int row) {
    int min_element = max_col(v)[row];
    for (auto& col : v) {
        if (row >= static_cast<int>(col.size())) continue; // out of range
        if (col[row] != 0) min_element = std::min(min_element, col[row]);
    }
    return min_element;
}

void print_elements(const Matrix &v) {
    for (auto& i : v) {
        for (auto& j : i) {
            std::cout << j << " ";
        }
        std::cout << std::endl;
    }
}

void organize_elements(Matrix &v) {
    for (auto& col : v) {
        std::sort(col.begin(),col.end());
    }
    auto current_max_col = max_col(v);
    for (int row{0}; current_max_col.begin()+row!=current_max_col.end(); ++row) {
        int min_element = min_element_in_row(v,row);
        for(auto& col : v) {
            if (row >= static_cast<int>(col.size())) continue; // out of range
            int candidate = col[row];
            if (candidate > min_element) {
                if (is_element_in_next_rows(v,candidate,row)) {
                    col.push_back(0);
                    std::rotate(col.begin()+row,col.end()-1,col.end());
                }
            }
        }
        current_max_col = max_col(v);
    }
}

int main() {

    Column c1 = {5,6,8,11};
    Column c2 = {2,5,3,1,4,6};
    Column c3 = {8,7,2,4,5,3,1};

    Matrix v;
    v.push_back(c1);
    v.push_back(c2);
    v.push_back(c3);

    std::cout << "original: \n";
    print_elements(v);
    organize_elements(v);
    std::cout << "organized: \n";
    print_elements(v);
    return 0;
}

Which produces the following output:

original:
5 6 8 11
2 5 3 1 4 6
8 7 2 4 5 3 1
organized:
0 0 0 0 5 6 8 11
1 2 3 4 5 6
1 2 3 4 5 7 8

Questions

I particularly don't like this part of my code:

auto current_max_col = max_col(v);
for (int row{0}; current_max_col.begin()+row!=current_max_col.end(); ++row) {
    // ....
    current_max_col = max_col(v);
}

I also don't like that I have to do this cast:

if (row >= static_cast<int>(col.size())) continue; // out of range

Is there a way to do this check better?

The fact that I need to declare current_max_col out of the for, and then update it inside the loop. Any idea how to avoid this?

Any other ideas about how to solve this problem? Any other tips? Thank you!


texts:
Is there any better way how to mix items in list? In my example: I want to sort list items as male, female, male, ... My solution is probably very time and resource demanding. Can I do it somehow with LINQ?

private List<Child> MixGender(List<Child> children)
    {
        List<Child> male = new List<Child>() { };
        List<Child> female = new List<Child>() { };

        male = children.Where(c => c.Sex == "male").ToList();
        female = children.Where(c => c.Sex == "female").ToList();

        int childrenCount = children.Count;
        int indexMale = 0;
        int indexFemale = 0;

        children.Clear();

        for (int i = 0; i < childrenCount; i++)
        {
            if (i % 2 == 1)
            {
                if (indexMale < male.Count)
                {
                    children.Add(male[indexMale]);
                    indexMale++;
                }
                else
                {
                    children.Add(female[indexFemale]);
                    indexFemale++;
                }
            }
            else
            {
                if (indexFemale < female.Count)
                {
                    children.Add(female[indexFemale]);
                    indexFemale++;
                }
                else
                {
                    children.Add(male[indexMale]);
                    indexMale++;
                }
            }
        }

        return children;
    }