texts: Rearrange data without using Cut and Insert

texts:
I'm fairly new to VBA, and this was basically a brute-force solution to a problem I was encountering. I wanted to take data that appeared in two columns, and pull it together into one.

The current code works, but is very slow with large datasets. I've been told to avoid using the clipboard if possible, but I'm not quite sure where to begin with this. I've made a few attempts to use an array, but I'm not quite sure where to start. Any other suggestions would be very welcome.

Private Sub Arra()

    Dim Library As Worksheet
    Set Library = Sheets("Library")
    Dim Rng As Range
    Dim i As Long
    Dim lastRow As Long
    i = 1
    lastRow = Library.Range("A1").SpecialCells(xlCellTypeLastCell).row

    While i <= lastRow
    Set Rng = Library.Range("A" & i)
         If Application.WorksheetFunction.CountA(Rng.Offset(0, 1)) = 1 Then
             Rng.Offset(0, 1).Cut
             Rng.Offset(1, 0).Insert Shift:=xlDown
             Rng.Offset(0, 1).Insert Shift:=xlDown
        ElseIf Application.WorksheetFunction.CountA(Rng.Offset(0, 1)) = 0 Then
            i = i + 1
        End If
    Wend

End Sub


texts: Regex to match several slightly different strings

texts:
I work with a charity that does a number of jobs, more than 100, less than 1000 a year. Jobs are identified with a year, and an up to 3 digit serial number, so 2021#123 for instance.
I'm writing a Python report program to pull jobs out of our database, and I'd like be be able to specify ranges of jobs rather like a print dialogue can specify ranges of pages, so a dash separated range 2021#123-45, or a comma separated list 2021#003,5,07,89,131 as well. I want to be able to parse all of these representations out of text strings.
I'm only interested in the syntax at the moment, the semantics of whether a range is valid is handled later. Even though I have very limited experience of regexes, I felt a one-liner would beat a whole bunch of python ifs.
The valid strings I want to match are therefore of the form

20y#n          OR
20y#n,q,p,r    OR
20y#n-m

where y is any two digits, and m,n,p,q,r are 1 to 3 digits.
This is a question about the regex. The only python consideration is the use of r'…' for a raw string.
I struggled and failed to write a regex that captures any of these forms by trying to match the year#ddd, and then OR the different endings. I think I fell foul of the single job form not having an ending at all. I've therefore ended up with this rather agricultural effort, that works, but looks ugly. I didn't put the comments in just for this post; I put them in knowing that if I needed to change things next month, I'd need them.
job_patt = r'((?:20\d\d#\d{1,3}-\d{1,3})|(?:20\d\d#\d{1,3}(?:,\d{1,3})+)|(?:20\d\d#\d{1,3}))'
# cap group  (                                                                             )
# non-caps    (?:                      ) (?:                           ) (?:              )
# OR the non-caps, in this L->R order   |                               |
# get year#      20\d\d#                    20\d\d#                         20\d\d#
# get 1 to 3 digits     \d{1,3}                    \d{1,3}                         \d{1,3}
# get one instance of range    -\d{1,3}
# get one or more repeats of list         ',ddd'          (?:,\d{1,3})+

What could be done to shorten or tidy up this regex?


texts:
The following two functions are used to compress arbitrary Python objects and send them safely via socket or email, using only printable chars. In my specific message protocol, '=' signs are also not allowed; I could have replaced them or truncate them - I chose to truncate them.

I think they work quite well speed-wise and have no unpredicted errors. I post it here for your judgement.

## Framework
import cPickle as pickle
import zlib as zl
import base64 as b64

def compress(o):
    ## First pickle
    p = pickle.dumps(o, pickle.HIGHEST_PROTOCOL)

    ## Then zip
    z = zl.compress(p, zl.Z_BEST_COMPRESSION)

    ## Then encode
    e = b64.b64encode(z)

    ## Then truncate
    t = e.rstrip("=")

    ## Then return
    return t

def decompress(s):
    ## First pad
    e = s + "=" * (-len(s) % 4)

    ## Then decode
    z = b64.b64decode(e)

    ## Then unzip
    p = zl.decompress(z)

    ## Then unpickle
    o = pickle.loads(p)

    ## Then return
    return o


texts:
This class sends "tweet" data to the client in the form of a custom markup language.  How can it be improved?

It is used in Ajax call and in previous post people have suggested not to echo the result..but this is my primary means of communicating with the server via Ajax responseText.

Also <tw_p> is used to denote a pass and is read by the client.  The markup looks like this.

field 1 | field 2 | field 3 | field 4 || field 1 | field 2 | field 3 | field 4 ||

It is called like this -

new tweet();

The client knows how render this into xhtml once it receives it.

/*tweet*/

class tweet extends post
  {
  function __construct()
    {
    parent::__construct();
    $email=$_SESSION['email'];
    $flname=$_SESSION['name'];
    $message=$this->_protected_arr['f4b'];
    $time=time();
    database::query("INSERT INTO tw VALUES ('$time','$flname','$message','$email')");
    $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");
    $b=0;
    $c='<tw_p>';
    while($a=mysqli_fetch_assoc($query_return))
      {
      if($b==0)
        {
        $c = $c . $a['email'] . "|" .  $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message'];
        }
      else
        {
        $c = $c . "||" . $a['email'] . "|" .  $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message'];
        }
      $b++;
      }
    echo $c;
    }
  }


texts:
I've got a method that parses a file.  I take all the words and add them to a SortedSet.  Every word contains a list of Lines that contain said word.  Words are not strings but a class I created:

class Word : IComparable<Word>
{
    public Word()
    {
        Lines = new List<Line>();
    }
    public string WordStr { get; set; }
    public List<Line> Lines { get; set; }

    public int CompareTo(Word other)
    {
        return string.Compare(this.WordStr, other.WordStr, StringComparison.OrdinalIgnoreCase);
    }
}

And the method that parses the file (I suspect I am not doing something properly here):

private void AddFile(string path)
    {
        Regex regex = new Regex("[^A-Za-z0-9\\s\\']");
        FileInfo fi = new FileInfo(path);
        if (!fi.Exists || Files.Contains(path.ToLower())) //File does not exist or file already indexed
        {
            return;
        }
        Files.Add(path.ToLower());
        StreamReader sr = new StreamReader(path);
        string file = sr.ReadToEnd();
        string saniFile = regex.Replace(file, "");
        string[] saniLines = saniFile.Split(new char[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
        int lineNo = 1;
        foreach (var l in saniLines)
        {
            Line line = new Line(l, path, lineNo);
            string[] words = l.Split(' ');
            foreach (var word in words)
            {
                Word w = new Word();
                w.WordStr = word;

                if (Words.Contains(w, new WordComparer())) //Set already contains the word
                {
                    Word wordToAdd = (from wors in Words where wors.WordStr.ToLower() == w.WordStr.ToLower() select wors).First();
                    if (!wordToAdd.Lines.Contains(line))
                        wordToAdd.Lines.Add(line);
                }
                else
                {
                    w.Lines.Add(line);
                    Words.Add(w);
                }
            }
            lineNo++;
        }
    }

I have the exact same functionality working in C++ and it's orders of magnitudes faster.  So is there something I am doing incorrectly?  What if I used a SortedDictionary instead of a SortedSet for the words?  Then the key could be the string that is the word and the value would be the list of lines that contain that word.

For reference, a 618KB text file takes a few seconds to parse and index in C++.  It's taking me minutes to do it in C#.


texts:
I've written a simple accordion using zepto js lib.

Looking for advice on how to improve this better.

HTML

   Learn more

     blah

     blah

     blah

     close

   Learn more

     blah

     blah

     blah

     close

Javascript

$('.more').addClass('hide');
var learnMore = $('.learn-more'),
    close = $('.close');
learnMore.click(function() {
    $(this).hide().next('div').toggleClass('hide');
});
close.click(function() {
    $(this).parent().toggleClass('hide');
    $(this).parent().prev().show();
});

Working demo

http://jsfiddle.net/s5x9A/

How can I prevent the page from jumping when I click on the empty anchor tags?


texts: Which syntax is preferred to create a Hash in Ruby on Rails?

texts:
I am writing some code in Ruby on Rails to Create an object.

I am using Ruby 2.0 and Rails 4.0.3 in my Application.

I have a Model called:

class GroupUsers < ActiveRecord::Base
  belongs_to :users
  belongs_to :group

This is basically a ManyToMany mapping between Users and Groups.
So, today I was creating an object for this Model.

But I found out I could follow two syntax for this, as follows

GroupUsers.create( :user => user, :group => group )

Or

GroupUsers.create( user: user, group: group )

Basically since this is related to creating a Hash so it must be a question of the best practice in Ruby.

Which syntax should be preferred ?


texts: Debugging based on a debug level without performance impact?

texts:
In a web application I am writing, I have used the following:

def dbgmsg(lvl, fmt, ...):
    if dbglvl >= lvl:
        # ... format and write the message
        pass # just here for correctness

Which is then used inside the code as:

dbgmsg(3, "Something happened")

Since there is no thing such as a the #ifdef in Python to my knowledge, I need to include the code at runtime. Will the above code cause a performance impact due to the call being made even when the globally set dbglvl is 0? Which alternatives exist?


texts: Golang nanny process starting child process

texts:
The idea here is that my executable can be started normally (in which case it runs my business logic), or it can be wrapped in a nanny process (which starts a child process to run the business logic, and if the child process dies restarts it indefinitely).  Here are some more specific requirements:

As invisible to the caller as possible
STDOUT/STDERR of the child should appear to be coming from the parent (so that if I run it in a terminal, it's invisible what's happening)
A dead child is restarted
A dead parent kills the child (so that ctrl-C in a terminal is sane)

Here is what I have (working).  Is there a cleaner way, or am I wasting resources somehow?

package main

import (
    "fmt"
    "os"
    "os/exec"
    "flag"
    "time"
)

var nanny string
var myparent int

func init() {
    flag.StringVar(&nanny, "nanny", "", "execute 'run -nanny run' to run in nanny mode.")
    flag.IntVar(&myparent, "myparent", 0, "never run 'run -myparent xxx'; it is used by nanny mode.")
}

func main() {
    flag.Parse()
    if nanny != "" {
        nannymain()
    } else {
        realmain()
    }
}

func realmain() {
    if myparent != 0 {
        go nannywatcher()
    }

    // ... run arbitrary business logic ...
}

func nannywatcher() {
    for {
        time.Sleep(1000 * time.Millisecond)
        if os.Getppid() != myparent {
            // We've been reparented!  If our nanny was killed someone is
            // trying to kill us, and the nanny will take care of the logging.
            // Just die.
            os.Exit(1)
        }
    }
}

func nannymain() {
    pid := os.Getpid()
    for {
        cmd := exec.Command(nanny, fmt.Sprintf("-myparent=%d", pid))
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        cmd.Run()
        // The child died.  We will restart him.
    }
}


texts:
In my Spring MVC app I have User and Role entities.

User:

public class User {
    private Long id;
    private Set<Role> roles;

    // other fields, getters and setters
}

Role:

public class Role {
    private Long id;

    // other fields, getters and setters
}

I have a service method with the following signature:

@Transactional
void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId)

The key of the Map is a User ID and the corresponding value is a Set of Role IDs that needs to be assigned to the user.

My implementation:

public void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId) {
    // 1.
    Map<Long, Role> roles = roleRepository.findAll()
        .stream().collect(Collectors.toMap(Role::getId, Function.identity()));

    // 2.
    userRepository.findAllById(rolesByUserId.keySet())
            // 3.
            .forEach(user -> user.setRoles(rolesByUserId.get(user.getId())
                    .stream().map(roles::get).collect(Collectors.toSet())));
}

So basically the flow is the following:

fetch all the Role entities from the DB into a Map<Long, Role> (where the key is the Role ID and the value is the Role entity itself)
fetch the User entities from the DB that needs to be modified
for each User, iterate through the Role IDs to be assigned, fetch the corresponding Role entities from the Map, collect them into a Set and assign it to the User

Can this method be optimized?


texts: Unity C# - Radar works but performance is horrible (Update & LateUpdate)

texts:
Hello I need help to optimize this code. I have a radar and it gets the enemies from a list and adds an image to their location to track them. I use Update to remove the images and LateUpdate to add the images. Is there any way I can do this without costing performance. I have a list of all the Enemies. I have a pool of over 40 images to use as tracking for the radar. Enemy is always moving. Any ideas?
private void Update()
{
    if (statsView_Panel.activeInHierarchy)
    {
        if (showIndicators_Enemies)
        {
            if (!enemyListHolder.activeInHierarchy)
            {
                enemyListHolder.SetActive(true);
            }

            Remove_PositionIndicatorOnEnemies();
        }
    }
}

private void LateUpdate()
{
    if (showIndicators_Enemies)
    {
        if (!enemyListHolder.activeInHierarchy)
        {
            enemyListHolder.SetActive(true);
        }

        Add_PositionIndicatorOnEnemies();
    }
}

private void Add_PositionIndicatorOnEnemies()
{
    //  Do if ListHolder is Active
    if (enemyListHolder.activeInHierarchy)
    {
        //  Run if 1 or more Enemies
        if (EnemiesManager.Count > 0)
        {
            //  Check All Enemies
            for (int i = 0; i < EnemiesManager.Count; i++)
            {
                //  Check All Indicators
                for (int s = 0; s < enemyIndicList.Count; s++)
                {
                    //  Choose Indicator that is not active *****BUG: Will Add All Deactivated Indicators to Active Enemies*****
                    if (enemyIndicList[s].gameObject.activeInHierarchy == false)
                    {
                        //  Activate Indicator and Reposition
                        enemyIndicList[s].gameObject.SetActive(true);
                        Vector3 aLocatorPos;
                        aLocatorPos = theCam.WorldToScreenPoint(satManager.GetByIndex(i).transform.position);
                        aLocatorPos.z = 0;
                        enemyIndicList[s].transform.position = aLocatorPos;

                        //  Break from Loop
                        break;
                    }
                }
            }
        }
    }
}

private void Remove_PositionIndicatorOnEnemies()
{
    //  Do if ListHolder is Active
    if (enemyListHolder.activeInHierarchy)
    {
        //  Run if 1 or more Enemies
        if (EnemiesManager.Count > 0)
        {
            //  Check All Indicators
            for (int s = 0; s < enemyIndicList.Count; s++)
            {
                //  Choose Indicator that is active
                if (enemyIndicList[s].gameObject.activeInHierarchy == true)
                {
                    //  Deactivate Indicator
                    enemyIndicList[s].gameObject.SetActive(false);
                }
            }
        }
    }
}


texts: find longest common substring in space O(n)

texts:
I am working on the class question find the longest common substring from 2 strings but I would like to return the longest common substring instead of just size of longest common substring.like

s1 = 'abcdex', s2 = 'xbcdey' => 'bcde'
s1 = 'abcxyx', s2 = 'xbcydey' => 'bc'

The way I do it is using dynamic programming to create a memo table and update each cell that required space \$O(n * m)\$. How can I implement the code so I can only using space as \$O(n)\$?

    def longestCommonSubstring(self, s1, s2):
        """
        :type s: str
        :rtype: str
        """
        m, n = len(s1), len(s2)
        dp = [[''] * (n + 1) for _ in range(m + 1)]
        max_len = ''
        for i, ic in enumerate(s1):
            for j, jc in enumerate(s2):
                dp[i][j] = dp[i - 1][j - 1] + ic if ic == jc else ''
                max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len
        return max_len


texts:
I have to create a Hotel database according to these requirements:

information about guests should be found, information about rooms divided into categories, reservations (ordered by a type of a room and assigned for a specific type of a room).
the following functionality should be provided: make a reservation by assigning a free room with the guests expectations - if you cannot meet guest's expectations, you have to save booking order to be settled by authorized employees
check how many times given person was a guest in last 2 years
which guests came to the hotel, accordingly to the reservation
free the room and write the bill

My code:

CREATE TABLE client_reservation (
    client_id        INTEGER NOT NULL,
    reservation_id   INTEGER NOT NULL
);

ALTER TABLE client_reservation ADD CONSTRAINT client_reservation_pk PRIMARY KEY ( client_id,
reservation_id );

CREATE TABLE clients (
    client_id      INTEGER NOT NULL,
    first_name     VARCHAR2(50) NOT NULL,
    last_name      VARCHAR2(100) NOT NULL,
    street         VARCHAR2(50),
    house_number   VARCHAR2(6),
    town           VARCHAR2(100),
    postal_code    VARCHAR2(6),
    telephone      VARCHAR2(15) NOT NULL
);

ALTER TABLE clients ADD CONSTRAINT clients_pk PRIMARY KEY ( client_id );

CREATE TABLE reservations (
    reservation_id        INTEGER NOT NULL,
    date_of_purchase      DATE,
    beggining             DATE,
    ending                DATE,
    status                VARCHAR2(10) NOT NULL,
    date_of_reservation   DATE NOT NULL
);

ALTER TABLE reservations ADD CONSTRAINT reservation_pk PRIMARY KEY ( reservation_id );

CREATE TABLE resevation_rooms (
    reservation_id   INTEGER NOT NULL,
    room_id          INTEGER NOT NULL
);

ALTER TABLE resevation_rooms ADD CONSTRAINT resevation_rooms_pk PRIMARY KEY ( reservation_id,
room_id );

CREATE TABLE room_category (
    category_id   INTEGER NOT NULL,
    name          VARCHAR2(50) NOT NULL,
    description   VARCHAR2(200)
);

ALTER TABLE room_category ADD CONSTRAINT room_category_pk PRIMARY KEY ( category_id );

CREATE TABLE rooms (
    room_id         INTEGER NOT NULL,
    capacity        INTEGER NOT NULL,
    price_per_day   NUMBER(10) NOT NULL,
    room_category   INTEGER NOT NULL
);

ALTER TABLE rooms ADD CONSTRAINT room_pk PRIMARY KEY ( room_id );

ALTER TABLE client_reservation
    ADD CONSTRAINT client_fk FOREIGN KEY ( client_id )
        REFERENCES clients ( client_id );

ALTER TABLE client_reservation
    ADD CONSTRAINT reservation_fk FOREIGN KEY ( reservation_id )
        REFERENCES reservations ( reservation_id );

ALTER TABLE resevation_rooms
    ADD CONSTRAINT reservation_rooms_fk FOREIGN KEY ( reservation_id )
        REFERENCES reservations ( reservation_id );

ALTER TABLE rooms
    ADD CONSTRAINT room_category_fk FOREIGN KEY ( room_category )
        REFERENCES room_category ( category_id );

ALTER TABLE resevation_rooms
    ADD CONSTRAINT room_reservation_fk FOREIGN KEY ( room_id )
        REFERENCES rooms ( room_id );

Model:

Thanks for every suggestions, cause I'm not so sure if I meet requirements and put right relations (identifying or nonidentifying)


texts:
I want to return a set of items with an attached score to the user so that the user can easily iterate from highest to lowest and get the n-th highest items.

Problems

The JavaDoc of SortedSet.first() says "Returns the first (lowest) element currently in this set.". However in this case it is actually the highest score. If I compare the other way around, however, the user needs to reverse the SortedSet in order to do this common use case.
If I only compare by score, the SortedSet can only have one item with the same score. However comparing by c strikes me as somehow arbitrary (not sure what I can do against that).
Two Items with the same URI should not exist, however that is not prevented when they have different scores.

import java.util.SortedSet;
import java.util.TreeSet;

public class Main
{
    static class Item<T extends Comparable<T>> implements Comparable<Item<T>>
    {
        double score;
        T c;

        public Item(double score, T c)
        {
            this.score=score;
            this.c=c;
        }

        @Override public int compareTo(Item<T> i)
        {
            int x = -Double.compare(score, i.score);
            if(x==0) {x=c.<T>compareTo(i.c);}
            return x;
        }
    }

    public static SortedSet<Item<String>> findItems()
    {
        SortedSet<Item<String>> items = new TreeSet<>();
        items.add(new Item<String>(0.3,"honey"));
        items.add(new Item<String>(0.7,"wolf"));
        items.add(new Item<String>(0.5,"monitor"));
        return items;
    }

    public static void main(String[] args)
    {
        // iterate from best to lowest score
        for(Item item: findItems()) {}
        // get item with best score
        findItems().first();
    }
}


texts: Optimizing Project Euler 36 - double-base palindromes

texts:
This one was quick and simple. Any optimizations?

from timeit import default_timer as timer

def sum_double_base_palindromes_under(limit):
    def is_palindrome(n):
        if str(n) == str(n)[::-1]:
            return True
        return False
    sum = 0
    for n in range(limit):
        if is_palindrome(n) and is_palindrome(int(bin(n)[2:])):
            sum += n
    return sum

start = timer()
ans = sum_double_base_palindromes_under(1000000)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Moderate return-low risk vs high returns-high risk investments

texts:
To quantify Buffet's #1 rule of investing, "Don't lose money", I take the assumption that % returns of an investment follow a Normal distribution.

Now a high return high risk investment might follow N(mu=50%, sigma=70%) while low return low risk investment follow N(mu=20%, sigma=10%).

from operator import mul
from functools import reduce
from random import gauss
from statistics import median
from typing import List

def avg_cagr(percents: List[int]) -> float:
        '''Given (successive) % annual growth rates, returns average Compound Annual Growth Rate'''
        amount = reduce(mul, [1+p/100 for p in percents])
        amount = amount if amount > 0 else 0 # at worst, complete amount can be lost but can't go negative
        return (amount**(1/len(percents)) - 1)*100

def normal_returns(mu: float, sigma: float, years: int = 20, simulations: int = 1000) -> float:
    '''Returns net CAGR assuming annual percentage returns follow a Normal distribution'''
    return median(avg_cagr([gauss(mu=mu, sigma=sigma) for _ in range(years)]) for _ in range(simulations))

I have simulated normal_returns for various values of mu & sigma (for 20 consecutive years) and plotted a contour plot. We can see here that N(25, 20) handily beats N(60, 80). Plotting code

My query is does this formulation of problem (beyond just the code) seem alright? Could I model/design it better? What are other approaches?


texts:
This is my solution for a problem in my workbook. It says to create a program that accepts input from a user to compare the areas of two rectangles. Is it good or bad practice to call functions in a constructor as soon as it is initialized?

Such as this:

public Rectangle() {
System.out.println("New rectangle dimensions \n" + "---------------
---------------------------");
userInputDimensions();
calculateArea();
}

Or is it better to just call the functions from the main class and keep the constructor empty? Everything works, I'm just trying to get some general advice on how to improve this code.

Main Class

public class Main {

public static void main(String[] args) {

Rectangle rectangle1 = new Rectangle();
Rectangle rectangle2 = new Rectangle();
Rectangle.CompareAreasOfRectangles test = rectangle1.new
CompareAreasOfRectangles(rectangle1, rectangle2);

}
}

Rectangle Class

import java.util.*;

public class Rectangle {
private double rectangleWidth;
private double rectangleLength;
private double areaOfRectangle;

public Rectangle() {
    System.out.println("New rectangle dimensions \n" + "---------------
---------------------------");
    userInputDimensions();
    calculateArea();
}

//Get Dimensions of Rectangle

private void userInputDimensions() {
    this.rectangleWidth = this.getPositiveInput("Please enter the width
of the rectangle");
    this.rectangleLength = this.getPositiveInput("Please enter the
length of the rectangle");
}

private double getPositiveInput(String prompt) {
    Scanner reader = new Scanner(System.in);
    double result;
    do {
        System.out.println(prompt);
        result = reader.nextDouble();
        if (result <= 0) {
            System.out.println("Enter a number greater than zero.");
        }
    } while (result <= 0);
    return result;
}

private void calculateArea() {
    this.areaOfRectangle = rectangleWidth * rectangleLength;
}

private double getAreaOfRectangle() {
    return areaOfRectangle;
}

// Compare areas of Rectangles

public class CompareAreasOfRectangles {
private Rectangle rectangle1;
private Rectangle rectangle2;

public CompareAreasOfRectangles(Rectangle rectangle1, Rectangle
rectangle2) {
    this.rectangle1 = rectangle1;
    this.rectangle2 = rectangle2;

    if (rectangle1.getAreaOfRectangle() >
rectangle2.getAreaOfRectangle()) {
        System.out.println("The area of Rectangle 1 is greater than the
area of Rectangle 2");
    } else if (rectangle1.getAreaOfRectangle() <
rectangle2.getAreaOfRectangle()) {
        System.out.println("The area of Rectangle 2 is greater than the
area of Rectangle 1");
    } else {
        System.out.println("The areas are equal");
    }
}
}
}


texts: Correct way to extend Bootstrap Modal - lock, unlock

texts:
I'm trying to extend bootstrap 3 modal window with ability to disable closing it.

I've built this code:

(function ($, window, document, undefined) {
    var oldHide = $.fn.modal.Constructor.prototype.hide;

    $.fn.modal.Constructor.prototype.hide = function (_relatedTarget) {
        if (this.isLocked) return;
        return oldHide.call(this, _relatedTarget);
    };

    $.fn.modal.Constructor.prototype.lock = function (_relatedTarget) {
        this.isLocked = true;
        e = $.Event('lock.bs.modal', {
            relatedTarget: _relatedTarget
        });
        this.$element.trigger(e);
    };

    $.fn.modal.Constructor.prototype.unlock = function (_relatedTarget) {
        this.isLocked = false;
        e = $.Event('unlock.bs.modal', {
            relatedTarget: _relatedTarget
        });
        this.$element.trigger(e);
    };

})(jQuery, window, document);

Working demo

After clicking "lock," you won't be able to close modal until you click "unlock."

It this way of extending bootstrap modal correct? What are potential dangers of doing this?

And how can I make this better?

EDIT:

This is my final version based on suggestions.


texts:
Ahead of the General Data Protection Regulation (GDPR) I begin to crypt more than ever before, in fact, all I can crypt become crypt.

However, I wonder if anybody can tell me if this code is secure enough or can make it even better, optimize or just have some tips about the code. and not sure about the OpenSSL are secure anymore so if any could give me some feedback about it I will love you forever.

The $keyis defined in the config.php and are a base64 encrypt and look like this e.g bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU

class myCrypt {

    public function my_encrypt($data, $key) {
        // Remove the base64 encoding from our key
        $encryption_key = base64_decode($key);
        // Generate an initialization vector
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
        $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
        // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
        return base64_encode($encrypted . '::' . $iv);
    }

    public function my_decrypt($data, $key) {
        // Remove the base64 encoding from our key
        $encryption_key = base64_decode($key);
        // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
        list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
        return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
    }
}

I like the fact that the same encrypt is never the same, but if a hacker hacks the code will he/she just use the decrypt method to decrypt the data??

  PS: This is not for passwords


texts:
This is a simple utility, intended to sit on the desktop for when needed, that does the simple ROT13 encoding and decoding.

I am used to coding in VBA, and I am interested in more .Net idiomatic coding styles.

Public Class Rot13Decoder

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles txtRotEntry.TextChanged
        lblResult.Text = Rot13(txtRotEntry.Text)
    End Sub

    Function Rot13(Source As String) As String
        Dim i As Long
        Dim result As String = ""

        For i = 0 To Source.Length - 1
            Dim myChar As Char
            myChar = Source.Substring(i, 1)

            Select Case myChar ' originally used Asc(Source(i)), hence the integers below
                Case "a" To "m", "A" To "M" '65 To 77, 97 To 109
                    result &= Chr(Asc(myChar) + 13) 'Chr(Asc(Source(i)) + 13)
                Case "n" To "z", "N" To "Z" '78 To 90, 110 To 122
                    result &= Chr(Asc(myChar) - 13) 'Chr(Asc(Source(i)) - 13)
                Case Else
                    result &= myChar
            End Select
        Next

        Return result
    End Function

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
End Class

(The title of the form says decoder, and I am using it in the example to encode!)

Double clicking on the form result label copies the text to the clipboard for use.


texts: Series of repetitive content-loading functions

texts:
A friend helped me put the following code together, which is made up of a series of repetitive loadContent() functions. I've just shown the first two functions but they're all the same.

The code works fine but I'm wondering if anyone could give me a tip as to how I could reduce the bloat in this code and condense the functions somehow. I read somewhere that repetitive code usually means that the code can be simplified or shortened somehow. I'm no expert at jQuery or coding so I'm not sure where to start. I'm assuming that the code could be written a lot better but I might be wrong.

function loadContent1()
    {
            $('#content1').empty();
            if(typeof(counterArray[1]) != 'undefined' && counterArray[1] !=     null)clearTimeout(counterArray[1]);
            jQuery.ajax({
            type: "GET",
            url: "//cgi-bin/mggsn_ssr21.cgi",
            beforeSend:function(){
                    jQuery('#content1').append('');
                    jQuery('#refresh1text').html("
Loading...
");
            }
            })
            .done(function(data){
                    if(typeof(counterArray[1]) != 'undefined' && counterArray[1] != null)clearTimeout(counterArray[1]);
                    $('#content1').empty();
                    $('#content1').html(data);
                    //alert(data.slice(0.100));

                    countDownTimeArray[1]=countDownIntervalArray[1];
                    countDown(1);
            })
                    .fail(function(){
                    $('#content1').empty();
                    jQuery('#content1').html('
failed to load content
' + this.url);
            });
    }

    function loadContent2()
    {
            $('#content2').empty();
            if(typeof(counterArray[2]) != 'undefined' && counterArray[2] != null)clearTimeout(counterArray[2]);
            jQuery.ajax({
            type: "GET",
            url: "/cgi-bin/mtest2.cgi",
            beforeSend:function(){
                    jQuery('#content2').append('');
                    jQuery('#refresh2text').html("
Loading...
");
            }
            })
            .done(function(data){
                    if(typeof(counterArray[2]) != 'undefined' && counterArray[2] != null)clearTimeout(counterArray[2]);
                    $('#content2').empty();
                    $('#content2').html(data);
                    //alert(data.slice(0.100));

                    countDownTimeArray[1]=countDownIntervalArray[1];
                    countDown(2);
            })
                    .fail(function(){
                    $('#content2').empty();
                    jQuery('#content2').html('
failed to load content
' + this.url);
            });
    }


texts: Query with multiple foreign keys to the same table

texts:
I have a primary table, REP_ASSIST.ES_LOG with multiple columns that are foreign keys to another table, REP_ASSIST.ES_DOCUMENT_STATUSES. Here is an example of what my main table looks like:

+-------------------------+-----------+-------------------------+-----------------------+
|       created_at        | filing_id | prior_dd_rcvd_status_id | new_dd_rcvd_status_id |
+-------------------------+-----------+-------------------------+-----------------------+
| 2019-09-04 10:58:48.000 |       988 | 2                       |                     2 |
| 2019-09-04 10:47:03.000 |       988 | 1                       |                     2 |
| 2019-08-28 23:56:47.000 |       988 | null                    |                     1 |
+-------------------------+-----------+-------------------------+-----------------------+

Both the prior_dd_rcvd_status_id and new_dd_rcvd_status_id are foreign keys to the other table, a sample of which is here:

+------------------+--------------------+
| dd_doc_status_id | dd_doc_status_name |
+------------------+--------------------+
|                1 | RECEIVED           |
|                2 | MISSING            |
|                3 | NOT_NEEDED         |
|                4 | UNKNOWN            |
+------------------+--------------------+

I need to pull in the values from the lookup table for a printable report; right now I'm using a subquery to get the dd_doc_status_name as a user-friendly name instead of the dd_doc_status_id.

SELECT created_at,
       filing_id,
       (
           SELECT dd_doc_status_name
           FROM REP_ASSIST.ES_DOCUMENT_STATUSES
           WHERE ES_DOCUMENT_STATUSES.dd_doc_status_id = prior_dd_rcvd_status_id
       ) AS 'prior_dd_status',
       (
           SELECT dd_doc_status_name
           FROM REP_ASSIST.ES_DOCUMENT_STATUSES
           WHERE ES_DOCUMENT_STATUSES.dd_doc_status_id = new_dd_rcvd_status_id
       ) AS 'new_dd_status'
FROM REP_ASSIST.ES_LOG
WHERE filing_id = 988;

However, I'm concerned that using subqueries like this may be a bit of a hack and affect performance (especially if I end up adding additional columns that need this information).

I'm getting the correct results (see below), but I'd like to know if there is a more efficient and more standard way.

+-------------------------+-----------+----------------------+--------------------+
|       created_at        | filing_id | prior_dd_rcvd_status | new_dd_rcvd_status |
+-------------------------+-----------+----------------------+--------------------+
| 2019-09-04 10:58:48.000 |       988 | MISSING              | MISSING            |
| 2019-09-04 10:47:03.000 |       988 | RECEIVED             | MISSING            |
| 2019-08-28 23:56:47.000 |       988 | null                 | RECEIVED           |
+-------------------------+-----------+----------------------+--------------------+


texts:
I have written this program for Maximim Priority Queue after studying from Introduction to Algorithm . I want to improve my code. Is there any other method to implement Priority Queue instead of Heap?

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

template<typename T>
void max_heapify(std::vector<T>& array, size_t index)
{
  size_t largest;
  size_t left  = (2*index) + 1;
  size_t right = left + 1;

  if(left < array.size() && array[left] > array[index])
    largest = left;
  else
    largest = index;

  if(right < array.size() && array[right] > array[largest])
    largest = right;

  if(largest != index)
  {
    int tmp = array[index];
    array[index] = array[largest];
    array[largest] = tmp;
    max_heapify(array, largest);
  }
}

template<typename T>
void build_max_heap(std::vector<T>& array)
{
  for(int64_t i = (int64_t(array.size())/2) - 1; i >= 0; i--)
  max_heapify(array, i);
}

template<typename T>
T heap_maximum(std::vector<T>& array)
{
  return array[0];
}

template<typename T>
T heap_extract_max(std::vector<T>& array)
{
  if(array.size() < 0)
  {
    std::cerr << "Heap Underflow \n";
    return -1;
  }
  else
  {
    T max = array[0];
    array[0] = array[array.size() - 1];
    array.erase(std::remove(array.begin(), array.end(), array[0]),
                  array.end());
    array.shrink_to_fit();
    max_heapify(array, 0);
    return max;
  }
}

template<typename T>
void heap_increase_key(std::vector<T>& array, size_t index, T value)
{
  if(value < array[index])
  {
    std::cerr <<"New value is smaller than the current value\n";
    return;
  }
  else
  {
    array[index] = value;
    while(index > 0 && array[(index/2) - 1] < array[index])
    {
      std::swap(array[index], array[(index/2) - 1]);
      index = (index/2) - 1;
    }
  }
}

template<typename T>
void max_heap_insert(std::vector<T>& array, T value)
{
  array.resize(array.size() + 1);
  array[array.size() - 1] = -1;
  heap_increase_key(array, array.size() - 1, value);
  build_max_heap(array);
}

int main()
{
std::vector<int> v({1, 2, 6, 3, 7});
build_max_heap(v);
std::cout << "Max-Heap: ";
for(size_t i = 0; i < v.size(); i++)
{
  std::cout << v[i] << " ";
}
std::cout << "\n";
std::cout << "Extract-Maximum: " << heap_extract_max(v) << "\n";
std::cout << "New Heap: ";
for(size_t i = 0; i < v.size(); i++)
{
  std::cout << v[i] << " ";
}
max_heap_insert(v, 10);
std::cout << "\nNew Heap after inserting 10: ";
for(size_t i = 0; i < v.size(); i++)
{
  std::cout << v[i] << " ";
}
std::cout << '\n';
}


texts: A Sub-string Extractor with Specific Keywords Parameter Implementation in C#

texts:
I am trying to implement a sub-string extractor with "start keyword" and "end keyword" and the extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. For example:

Input String
Start Keyword
End Keyword
Output

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
""(empty string)
""(empty string)
"C# was developed around 2000 by Microsoft as part of its .NET initiative"

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
""(empty string)
".NET"
"C# was developed around 2000 by Microsoft as part of its"

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
"C#"
""(empty string)
"was developed around 2000 by Microsoft as part of its .NET initiative"

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
"C#"
".NET"
"was developed around 2000 by Microsoft as part of its"

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
".NET"
""(empty string)
"initiative"

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
""(empty string)
"C#"
""(empty string)

"C# was developed around 2000 by Microsoft as part of its .NET initiative"
".NET"
"C#"
""(empty string)

The experimental implementation
The experimental implementation is as below.
private static string GetTargetString(string stringInput, string startKeywordInput, string endKeywordInput)
{
    int startIndex;
    if (String.IsNullOrEmpty(startKeywordInput))
    {
        startIndex = 0;
    }
    else
    {
        if (stringInput.IndexOf(startKeywordInput) >= 0)
        {
            startIndex = stringInput.IndexOf(startKeywordInput) + startKeywordInput.Length;
        }
        else
        {
            return "";
        }

    }

    int endIndex;
    if (String.IsNullOrEmpty(endKeywordInput))
    {
        endIndex = stringInput.Length;
    }
    else
    {
        if (stringInput.IndexOf(endKeywordInput) > startIndex)
        {
            endIndex = stringInput.IndexOf(endKeywordInput);
        }
        else
        {
            return "";
        }
    }

    //    Check startIndex and endIndex
    if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex)
    {
        return "";
    }

    if (endIndex.Equals(0).Equals(true))
    {
        endIndex = stringInput.Length;
    }
    int TargetStringLength = endIndex - startIndex;
    return stringInput.Substring(startIndex, TargetStringLength).Trim();
}

Test cases
string test_string1 = "C# was developed around 2000 by Microsoft as part of its .NET initiative";

Console.WriteLine(GetTargetString(test_string1, "", ""));
Console.WriteLine(GetTargetString(test_string1, "", ".NET"));
Console.WriteLine(GetTargetString(test_string1, "C#", ""));
Console.WriteLine(GetTargetString(test_string1, "C#", ".NET"));
Console.WriteLine(GetTargetString(test_string1, ".NET", ""));
Console.WriteLine(GetTargetString(test_string1, "", "C#"));
Console.WriteLine(GetTargetString(test_string1, ".NET", "C#"));

The output of the above test cases.
C# was developed around 2000 by Microsoft as part of its .NET initiative
C# was developed around 2000 by Microsoft as part of its
was developed around 2000 by Microsoft as part of its .NET initiative
was developed around 2000 by Microsoft as part of its
initiative

If there is any possible improvement, please let me know.


texts:
I am writing a simple event handling class in C++, to avoid having delegate registration and calls cluttering the rest of the code. I have a design that seems to do the job, but it has a couple of drawbacks.

So far it looks like this:

template<typename T>
struct IDelegate { virtual void operator ()(const T & args) const = 0; };

template<typename T>
class EventHandler
{
public:
    void Trigger(const T & args) const;
    void AddListener(const IDelegate<T> & delegate);
    void RemoveListener(const IDelegate<T> & delegate);
};

Which in practice would look like this (some code elided for clarity):

class Foo
{
public:
    struct CustomEventArgs { int i; };
    EventHandler<CustomEventArgs> * SomeHandler() const { return m_handler; }

    void SomeMethod()
    {
        // Some code
        CustomEventArgs someArgs = { 42 };
        SomeHandler()->Trigger(someArgs);
    }

private:
    EventHandler<CustomEventArgs> * m_handler;
};

class Bar : public IDelegate<Foo::CustomEventArgs>
{
public:
    void operator ()(const Foo::CustomEventArgs & args) const
    {
        std::cout << args.i << " bottles of beer" << std::endl;
    }

    void StartListening(const Foo & foo)
    {
        foo.SomeHandler()->AddListener(*this);
    }
};

This code would basically do what I want, but there are still several things I don't quite like.

EventHandler::Trigger() is public

Anyone can call it, which is a serious flaw. Only the owner should be able to call that method. I can see two ways of ensuring this, but I am not happy with any of them:

Making the EventHandler(s) hidden from outside Foo. This defeats the purpose though, since it would then require to add as many AddListener/RemoveListener methods.
Making Trigger() protected, deriving from EventHandler, then declaring Foo as a friend. This would require to declare a specific class for every single pair of event-handler/class-using-that-event-handler, which is less than ideal.

SomeHandler() returns a pointer

If possible, I think it'd be better to make m_handler an actual member instead of having it somewhere (else) on the heap, and return a reference to it. But I don;t see how to do that without getting plagued with non-const-ness: I want StartListening() to take a const reference.

The question[s]

What would you recommend regarding these two issues?
Do you see other flaws in this design?


texts: Euler Problem 7 (finding the 10001st prime) in Powershell

texts:
I am having issue making this code more efficient. The problem to be solved is as follows:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10,001st prime number?

I'm looking to complete this in powershell. My code runs well up until about 4.8k primes.

$incNum1 = 1
$incNum2 = 2
$divisNum = 2 * $incNum2 - 1
$highestNum = 0
$k = 1
$nextNum = 2 * $incNum1 + 1

while($k -lt 6000){

    $upTo = [int][Math]::Ceiling(($nextNum / 2))

    $break = $false

    while($divisNum -lt $upTo){
        $modRes = $nextNum % $divisNum

        if($modRes -eq 0){

            $break = $true

            break
        }

        $incNum2++
        $divisNum = 2 * $incNum2 - 1
    }

    if(!$break){

        $highestNum = $nextNum

        echo $nextNum

        $k++
    }

    $incNum2 = 2
    $divisNum = 2 * $incNum2 - 1

    $incNum1++

    $nextNum = 2 * $incNum1 + 1
}

echo $highestNum


texts:
I have fully working code, however I'd like to make it nice. I've got these three models:

  User (can have both or either one)
  user can have one trucker
  user can have one owner_trucker
  Trucker
  belongs to user
  OwnerTrucker
  belongs to user

I'm not the only one working in the app, but it starts to annoy me how everyone is solving the issue locally.

The problem is how to determine what the user is (a trucker or a owner_trucker or both). i.e if user.trucker is not nil, its a trucker etc.

So here are few examples from the application (various controllers), basically checking for the same thing but in a different way:

helper_method :profile_type_from_user
  def profile_type_from_user(user)
    return profile = user.trucker ? :trucker : :owner_trucker
  end

And then used in another controller like:

if profile_type_from_user(profile) == :trucker
else
end

Another example would be:

@profile = current_user.trucker ? current_user.trucker : current_user.owner_trucker

Checking if one or another:

current_user.trucker? && current_user.owner_trucker.nil?

It this refactorable?


texts: SICP exercise 2.28 - counting leaves in a tree (recursive process)

texts:
From SICP

  Exercise 2.28: Write a procedure fringe that takes as argument a tree
  (represented as a list) and returns a list whose elements are all the
  leaves of the tree arranged in left-to-right order. For example,

(define x (list (list 1 2) (list 3 4)))

(fringe x)
(1 2 3 4)

(fringe (list x x))
(1 2 3 4 1 2 3 4)

After writing this code, I found out that implementing this in an iterative way is easier and more straight forward. But I ended up implementing this in a more complicated way. I'd like to think this is a recursive process. The argument "remaining" is not an accumulator. It stores all remaining items that are not yet consed into the new list.

Please review my code.

(define (fringe tree)
    (define (aux lst remaining)
        (cond
            ((null? lst)
                (if (null? remaining)
                    '()
                    (aux remaining '())))
            ((pair? (car lst)) (aux (car lst) (aux (cdr lst) remaining)))
        (else (cons (car lst) (aux (cdr lst) remaining)))))
    (aux tree '()))

How does it compare to the iterative version I linked to above?
What is the order of growth of my function? Is it O(N)?
How can it be faster?
If I used append rather than cons, would it slow my function a lot?
How can I improve this code?


texts:
I am using the Android library Retrofit for networking in my app. The library calls for creating a RestAdapter for making service calls. I want to use this same instance of the RestAdapter for all of my service calls. How is my setup for this scenario?

Extending Application:

public class CustomApplication extends Application {
    private RestClient restClient = null;

    public RestClient getRestClient() {
        return restClient;
    }

    public void initRestClient() {
        if (restClient == null) {
            restClient = new RestAdapter.Builder().setEndpoint(BASE_URL).build().create(RestClient.class);
        }
    }
}

Initializing instance and making sure I have access to the instance in all my Activities, without explicitly having to get it for each Activity:

public class BaseActivity extends Activity {
    protected RestClient restClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((CustomApplication) this.getApplication()).initRestClient();
        restClient = ((CustomApplication) this.getApplication()).getRestClient();
    }
}

Then all my Activities will extend BaseActivity.


texts: Using a base class but defining a property

texts:
I have designed a Python TreeNodeBase class, so all tree nodes I implement can inherit from this. However, due to the laziness inherent in a lot of trees, I would like some fields to be properties (using the @property decorator) instead.

But doing so, the base class will raise AttributeError whenever it tries to set a field, when I call super().__init__(). The way I'm resolving this now is to ignore the AttributeError. Is this a good idea, and is there a standard approach to this problem?

from contextlib import suppress

class TreeNodeBase:
    def __init__(self, value, edge_value=None, children=None, parent=None, tree=None):
        with suppress(AttributeError):
            self.value = value
        with suppress(AttributeError):
            self.edge_value = edge_value
        with suppress(AttributeError):
            self.children = children
        with suppress(AttributeError):
            self.parent = parent
        self.tree = tree

    def get_child(self, edge_value):
        raise NotImplementedError


texts:
This is my first time building an Android app or even using Java in the first place. All of this code does work, but I'm hoping to optimize it or find out if things could be done more easily than how I've done them.

radio.java

package com.example.jacob.wutk;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

public class radio extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private boolean isMediaPlayerStarted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio);
        setMediaPlayer();
    }

    public void setMediaPlayer() {
        try {
            mediaPlayer = new MediaPlayer();
            String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here

            final ImageButton imb = (ImageButton) findViewById(R.id.playPause);

            imb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isMediaPlayerStarted) {
                        mediaPlayer.prepareAsync();
                        isMediaPlayerStarted = true;
                    } else {
                        if (mediaPlayer.isPlaying()) {
                            imb.setImageResource(R.drawable.play1);
                            mediaPlayer.pause();
                        } else {
                            imb.setImageResource(R.drawable.pause1);
                            mediaPlayer.start();
                        }
                    }
                }
            });

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mediaPlayer){
                    mediaPlayer.start();
                }
            });

            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(url);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }}

activity_radio.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    tools:context="com.example.jacob.wutk.radio">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left|center_vertical"
        android:scaleType="centerCrop"
        android:src="@drawable/background_mic1"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="1.0dip"
        android:paddingLeft="4.0dip"
        android:paddingRight="4.0dip"
        android:paddingTop="5.0dip">
       <ImageButton
           android:id="@+id/playPause"
           android:layout_width="0.0dip"
           android:layout_height="wrap_content"
           android:layout_weight="1.0"
           android:background="?android:selectableItemBackground"
           android:clickable="true"
           android:scaleType="fitCenter"
           android:onClick="playPauseMusic"
           android:src="@drawable/play1"/>
       <ImageView
           android:layout_width="0.0dip"
           android:layout_height="fill_parent"
           android:layout_marginRight="5dp"
           android:layout_weight="1.0"
           android:background="?android:selectableItemBackground"
           android:scaleType="fitCenter"
           android:src="@drawable/logo"/>

    </LinearLayout>

</FrameLayout>

Debug version of app


texts: Converting from polar coordinates to rectangular coordinates

texts:
This is performance critical. I measured and determined that using the sqrt is faster then using the cos method.

I am aware that this code only works for some points, so that is not an issue.

Point is System.Drawing.Point. _offset is also of type Point.

I assumed, and the profiler seemed to confirm, that the try/catch will not slow down the code unless an exception occurs. Please correct me if that is wrong.

/// <summary>
/// Convert from polar coordinates to rectangular coordinates.
/// Only works for points to the left of the origin.
/// </summary>
/// <param name="radius">The radius of the point in pixels.</param>
/// <param name="theta">The angle of the point in radians.</param>
/// <returns>The point in rectangular coordinates.</returns>
internal Point PolarToRectangular(
        double radius,
        double theta)
{
    try
    {
        double sin = Math.Sin(theta);

        // This is faster then:
        // double cos = Math.Cos(theta);
        double cos = -Math.Sqrt(1 - (sin * sin));

        Int32 x = _offset.X + (Int32)Math.Round(radius * cos);
        Int32 y = _offset.Y + (Int32)Math.Round(radius * sin);

        return new Point(x, y);
    }
    catch (OverflowException ex)
    {
        ex.Data.Add("Screen polar Radius", radius);
        ex.Data.Add("Screen polar Theta", theta);
        throw;
    }
}


texts: find in which sublist of a list are any value of a list in python

texts:
I want to return a NumPy array of Element IDs with at least one Node being in the interesting Nodes list.
I have:

A list of interesting Nodes, Interesting_Nodes.
The size is ~300,000 items.

A list of sublists which represent Node forming an Element, Nodes.
The size is ~1,000,000 lists of ~20 values.
Nodes[i] contain the 20 Nodes creating Elements[i]. Which is an integer ID.

A list of Elements, Elements.
The size is ~1,000,000 items.

Here is an example of these lists.
import numpy as np
Interesting_Nodes=[1,2,10,40,400,1000]
Elements=[1,2,3]
Nodes=[[1,20,25],[30,400,35],[500,501,502]]

In this case the function will return [1,2] because Elements[0] have the Node 1 in the Interesting_Nodes list and Elements[1] contains the Node 400 which is also in the Interesting_Nodes list
I wrote this it seems to work but is very slow. Is there a way to perform this faster?
def recuperation_liste_element_dans_domaine_interet(Interesting_Nodes,Elements,Nodes):
    Liste_elements=list([])
    for n in Interesting_Nodes:
        id=np.where(Nodes==n)
        Liste_elements=Liste_elements+list(Elements[id[0]])
    nbrListe = list(set(Liste_elements)) # remove all the element duplication
    return np.array(nbrListe)

Another way to perform that I think could be: (be still too slow)
def recuperation_liste_element_dans_domaine_interet(Interesting_Nodes,Elements,Nodes):
    Liste_elements=[0]*len(Elements)
    compteur=0
    j=0
    for n in Nodes:
        if any(i in Interesting_Nodes for i in n):
            Liste_elements[compteur]=Elements[j]
            compteur=compteur+1
        j=j+1
    Liste_elements=Liste_elements[:compteur]
    return np.array(Liste_elements)


texts:
This should implement a stack that has a \$O(1)\$ getMin method. I used an auxiliary stack. Please provide comments on my solution.

import org.junit.Test;

public class Solution {

  @Test
  public void testEmptyStack(){
    StackMin<Integer> s = new StackMin<Integer>();
    System.out.println("----------------------");
    System.out.println("Empty stack");
    System.out.println(s.getMin());
  }

  @Test
  public void testRandomStack(){
    System.out.println("----------------------");
    StackMin<Integer> s = new StackMin<Integer>();
    s.push(2);
    s.push(-1);
    s.push(0);
    s.push(7);
    s.push(22);
    System.out.println("Random stack");
    s.printStack();
    System.out.println("Min element");
    System.out.println(s.getMin());
  }

  @Test
  public void testEqualities(){
    System.out.println("----------------------");
    StackMin<Integer> s = new StackMin<Integer>();
    s.push(2);
    s.push(-1);
    s.push(0);
    s.push(0);
    s.push(0);
    s.push(7);
    s.push(22);
    s.push(-1);
    s.push(-1);
    s.push(33);
    System.out.println("Stack with equalities");
    s.printStack();
    System.out.println("Min element");
    System.out.println(s.getMin());
  }

  public static void main(String[] args) {
    Solution e = new Solution();
    e.testEmptyStack();
    e.testRandomStack();
    e.testEqualities();
  }
}

class NodeV2<T> {
  private final T data;

  private final NodeV2<T> next;

  public NodeV2(T d, NodeV2<T> n) {
    data = d;
    next = n;
  }

  public NodeV2(T d) {
    this(d, null);
  }

  public T getData() {
    return data;
  }

  public NodeV2<T> getNext() {
    return next;
  }

}

class StackMin<T extends Comparable<T>> extends StackV2<T> {
  StackV2<T> auxiliaryStack = new StackV2<T>();

  void push(T element) {
    if (auxiliaryStack.isEmpty() || element.compareTo(auxiliaryStack.top.getData()) <= 0) {
      auxiliaryStack.push(element);
    }

    super.push(element);
  }

  T pop() {
    if (this.peek().compareTo(auxiliaryStack.peek()) <= 0) {
      auxiliaryStack.pop();
    }

    return super.pop();
  }

  public T getMin() {
    return auxiliaryStack.peek();
  }

}

class StackV2<T extends Comparable<T>> {
  NodeV2<T> top;

  void push(T element) {
    NodeV2<T> t = new NodeV2<T>(element, top);
    top = t;
  }

  T pop() {
    if (top != null) {
      T item = top.getData();
      top = top.getNext();
      return item;
    }
    return null;
  }

  T peek() {
    return top == null ? null : top.getData();
  }

  boolean isEmpty() {
    return top == null ? true : false;
  }

  public void printStack() {
    NodeV2<T> current = top;
    while (current != null) {
      System.out.println(current.getData());
      current = current.getNext();
    }
  }
}


texts: Is this String concatenation creating extra String?

texts:
Using the eclipse formatting on a class with some @NamedQueries created concatenations.

While I have been doing this for years without paying attention I just realised that may be it
is  not a good usage.

So basically Which one of these Strings inside the queryis better ? Is the second one creating too many Strings? Should I be bothered at all?

My answer would be yes second one is creating extra Strings but I am not sure I should be concerned.

First Query

 @NamedQuery(
      name = SomeConstant,
      query="SELECT person FROM Person person Where person.name = :name ")

Second Query

 @NamedQuery(
      name = SomeConstant,
      query="SELECT person FROM Person person"+" "+
               "Where person.name = :name ")


texts: C++ Stack implementation with linked-list

texts:
It's proving difficult to find implementations of a Stack with linked list and Im trying to figure out if my implementation is correct/not missing anything obvious.

template <class T>
class Stack {
private:
  struct node {
    T data;
    node* next = nullptr;
    node(T data, node* next) : data(data), next(next) {};
  };
  node* top_ = nullptr;
public:
  Stack() {}
  Stack(T seed[], size_t len) {
    for(size_t i = 0; i < len; ++i) {
      Push(seed[i]);
    }
  }
  void Push(T value) {
    node* ele = new node { value, top_ };
    top_ = ele;
  }
  bool IsEmpty() {
    return top_ == nullptr;
  }
  T Peek() {
    if (IsEmpty())
      throw std::runtime_error("Stack is empty");
    return top_->data;
  }
  T Pop() {
    if (IsEmpty())
      throw std::runtime_error("Stack is empty");
    node* popped = top_;
    T result = popped->data;
    top_ = popped->next;
    delete popped;
    return result;
  }
};

My tests (sample basic ones below) do show working functionality as well, so its really just my code structure/procedures I'm worried about

int seed[3] { 5,4,3 };
Stack<int> stack { seed, 3 };
REQUIRE( stack.Pop() == 3 );
REQUIRE( stack.Pop() == 4 );
REQUIRE( stack.Pop() == 5 );
REQUIRE_THROWS_WITH( stack.Pop(), "Stack is empty" );
REQUIRE_NOTHROW( stack.Push(9) );
REQUIRE_NOTHROW( stack.Push(3) );
REQUIRE( stack.Peek() == 3 );
REQUIRE( stack.Pop() == 3 );


texts: Difference between dates in Months and Days

texts:
I've written a function that returns how many Months and Days are between two dates. I want to respect calendar month boundaries, but I'm ignoring time as it's not relevant for my needs.

I've got the following, but I feel like I'm missing thing I can do to optimize it/refactor it. So I'm looking for additional eyes to help me review this.

//As opposed to TimeSpan ^_^
public readonly struct CalendarSpan
{
    public CalendarSpan(int months, int days)
    {
        Months = months;
        Days = days;
    }
    public readonly int Months;
    public readonly int Days;
}

public static CalendarSpan DifferenceInMonthsAndDays(DateTime startDate, DateTime endDate)
{
    //Ensuring that the larger of two dates is the latter argument
    if (startDate > endDate)
        return DifferenceInMonthsAndDays(endDate, startDate);

    //Start with getting the difference in months
    var months = 12 * (endDate.Year - startDate.Year) + endDate.Month - startDate.Month;

    int days;
    //Add the difference in months to the smaller of the two dates
    var addedMonths = startDate.AddMonths(months);
    if (addedMonths <= endDate)
        //So long as we can avoid negative numbers, just do the simple math
        days = endDate.Day - addedMonths.Day;
    else
    {
        //Otherwise, backoff by 1 months, and use the built in Subtract logic to get the number of days between the two dates
        months--;
        addedMonths = startDate.AddMonths(months);
        days = endDate.Subtract(addedMonths).Days;
    }

    return new CalendarSpan(months, days);
}

UPDATE
I have been trying to get unit tests for this, and I honestly don't know why I ever attempted this. It is NOT an easy or straight forward thing to do at all.
Insert obligatory meme of Homer disappearing into the hedges


texts:
Pretty standard. Generates the first n primes, input via a scanner.

package main;

import java.util.Scanner;

public class Prime_Generator {
   public static void main(String args[]) {
      int n;
      int status = 1;
      int num = 3;

      Scanner scanner = new Scanner(System.in);
      System.out.print("First n primes: ");

      n = scanner.nextInt();
      if (n >= 1) {
         System.out.print("First "+n+" prime numbers are: \n");
         System.out.println(2);
      }

      for (int i = 2; i <=n;) {
         for (int j = 2; j <= Math.sqrt(num); j++) {
            if (num%j == 0) {
               status = 0;
               break;
            }
         }
         if (status != 0) {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }
   }
}

My question:

How can I improve the efficiency of this code?


texts: Create an Array of Objects for Patch Notes in React

texts:
I was looking to get some reviews of my code, so I can improve my writing. Functionally it works the exact way I want it to based on my patch notes .md file. I'm open to all suggestions for improving the code, especially in making it more performant.

 state = {
  open: false,
  notes: null
 }

 componentDidMount() {
  this.getData();
 }

 getData = () => {
  axios.get(patchnotes_md_urlpath)
   .then((response) => {
    const updates = response.data.replace(/(\r\n|\n|\r)/g, '').split('### ');
    let i;
    let j;
    let notes = [];
    for ( i = 1; i < updates.length; i++ ) {
     let update = updates[i].split('* ');
     const newObj = Object.assign({});
     newObj.version = update[0];
     let list = [];
     for ( j = 1; j < update.length; j++ ) {
      list.push(update[j]);
     }
     newObj.notes = list;
     notes.push(newObj);
    }
    this.setState({
     notes
    });
   }).catch((error) => {
    console.error(error);
   });
 }

### 0.1.2

* Patch notes now implemented when the modal starts.
* Added top lists for organizations

### 0.0.1

* Patch Notes Added
* Modal to include Patch Notes


texts:
I have implemented a QuadTree of my own, and I'm afraid I didn't use yield properly when I query my tree, my fear is that I create O(HN) iterators.

Could you direct me how to better improve the performance of the following code?

QuadTree

public IEnumerable<T> Query(string leafId, Circle shape)
    {
        // Gets the relevant parent by a leafId Query (this is O(lg H))
        var startNode = GetParentIntersecting(leafId, shape);

        return startNode.Query(shape);
    }

QuadTreeNode

 public IEnumerable<T> Query(IShape shape)
    {
        var results = new HashSet<T>();

        foreach (var content in _contents)
        {
            if (shape.Contains(content.GetPosition()))
            {
                //Debug.Log(content.GetPosition());
                yield return content;
                //results.Add(content);
            }
        }

        if (IsLeaf)
            yield break;

        foreach (var node in Nodes)
        {
            if (node.IsEmpty && node.IsLeaf)
                continue;

            foreach (var result in node.Query(shape))
            {
                results.Add(result);
            };
        }
    }


texts:
I'm running into page performace issues and I believe this block is causing the biggest slowdown:

  // Section menu on mouseover, hide menu on mouseout
  // Can be more concise using .toggleClass?
  $('section').live('mouseenter', function() {
    if ($(window).width() > 1278) {
      $(this).find('menu').removeClass('hidden')
      $(this).find('div.section-wrapper').addClass('active')
    }
  }).live('mouseleave', function() {
    if ($(window).width() > 1278) {
      $(this).find('menu').addClass('hidden')
      $(this).find('div.section-wrapper').removeClass('active')
    }
  })

For the record, I'm aware .live() is deprecated and will eventually switch to .on(). I'm under the impression this only runs when mouseenter and mouseleave occur, but with it, the page performance is poor - especially for mobile.

I'm trying to convert this to a css media query so it runs faster but the following block of SASS isn't cutting it:

@media(min-width: 1279px) {
  section:hover {
    menu.hidden {
      display:block;
    }
    section .section-wrapper {
      border: 1px #ddd solid;
      padding: 14px;
    }
  }
}

.active just adds a border and changes the padding to accommodate. section:hover appears to do nothing. I added section {background-color: #E1C2E2;} within the media query for troubleshooting and it's working fine. Ideas? Could it be nested SASS with media queries causing the slowdown?


texts: Speeding up VBA Code that Sets Pivot Table Filters

texts:
I've written out some VBA code that sets various filters onto pivottables. The problem I am experiencing is that it is extremely slow and bogs down my system heavily.

I've tried implementing various things to speed up the code, but nothing really has that much of an effect.

The reason I am doing it this way is the filters need to be dynamic and I am using multiple data sources, so just using a single slicer doesn't work in my case.

Here is my code:

 Private Sub Worksheet_Calculate()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.DisplayStatusBar = False
    ActiveSheet.DisplayPageBreaks = False

    Dim DivRef, RegRef, DistRef, ZoneRef As String
    DivRef = Sheet5.Range("AH6").Value
    RegRef = Sheet5.Range("AH7").Value
    DistRef = Sheet5.Range("AH8").Value
    ZoneRef = Sheet5.Range("AN4").Value

With Sheet5.PivotTables("PivotTable21")
    .ManualUpdate = True
    .PivotFields("Division2").CurrentPage = DivRef
    .PivotFields("Region2").CurrentPage = RegRef
    .PivotFields("District2").CurrentPage = DistRef
    .ManualUpdate = False
End With

With Sheet5.PivotTables("PivotTable9")
    .ManualUpdate = True
    .PivotFields("Division2").CurrentPage = DivRef
    .PivotFields("Region2").CurrentPage = RegRef
    .PivotFields("District2").CurrentPage = DistRef
    .ManualUpdate = False
  End With

     Application.EnableEvents = True
     Application.ScreenUpdating = True
     Application.Calculation = xlCalculationAutomatic

    End Sub

In reality, there are a number of pivottables that are being filtered, but for the sake of this post, I am only posting PivotTable21 and PivotTable9's filters, though it is all more or less the same code.

I've been told that part of the problem might be that I am using calculated fields in my pivottables, and that may bog down some of the code as well.

Does anyone have any tips for speeding this code up?


texts: Converting date format in range of cells

texts:
This code works, but I was wondering if there's a way to get excel to identify the date data more easily. This comes from an imported file where the date field(s) come in as text and in a European format.

Company specific information has been changed.  the function FndLast gets the last row of the data.

Sub FormatTheDates()

Dim rng As Range
Dim lstRow As Long
Dim StartRow As Long

Set rng = sheets("MySheet").Cells.Find("Keyfield")

If Not rng Is Nothing Then
    With sheets("MySheet")
    ****Data starts one row below key field***
        StartRow = rng.Row + 1
        lstRow = FndLast(1, .Cells)
        Set rng = .Range(.Cells(StartRow, 5).Address, .Cells(lstRow, 5).Address)
        rng.NumberFormat = "m/d/yyyy"
        rng.value = rng.value
    End With
End If

Set rng = sheets("MySheet2").Cells.Find("Keyfield")

If Not rng Is Nothing Then
    With sheets("MySheet2")
        StartRow = rng.Row + 1
        lstRow = FndLast(1, .Cells)
        Set rng = .Range(.Cells(StartRow, 7).Address, .Cells(lstRow, 7).Address)
        rng.NumberFormat = "m/d/yyyy"
        rng.value = rng.value
    End With
End If

End Sub

The fndlast function takes a 1,2, or 3 as a parameter and finds the last row, column or cell on a sheet. I use this as opposed to usedrange as it returns the last one with data.

Function FndLast(choice As Long, rng As Range)

' 1 = last row
' 2 = last column
' 3 = last cell

Dim lrw As Long
Dim lCol As Long

Select Case choice

Case 1:
    On Error Resume Next
    FndLast = rng.Find(What:="*", _
                    After:=rng.Cells(1), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
    On Error GoTo 0

Case 2:
    On Error Resume Next
    FndLast = rng.Find(What:="*", _
                    After:=rng.Cells(1), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column
    On Error GoTo 0

Case 3:
    On Error Resume Next
    lrw = rng.Find(What:="*", _
                   After:=rng.Cells(1), _
                   LookAt:=xlPart, _
                   LookIn:=xlFormulas, _
                   SearchOrder:=xlByRows, _
                   SearchDirection:=xlPrevious, _
                   MatchCase:=False).Row
    On Error GoTo 0

    On Error Resume Next
    lCol = rng.Find(What:="*", _
                    After:=rng.Cells(1), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column
    On Error GoTo 0

    On Error Resume Next
    FndLast = rng.Parent.Cells(lrw, lCol).Address(False, False)
    If Err.Number > 0 Then
        Last = rng.Cells(1).Address(False, False)
        Err.Clear
    End If
    On Error GoTo 0

End Select
End Function

As I said, all of this works, and fairly quickly, but it feels like the Range.value = range.value seems unnecessary. Is it, or is this just an Excel quirk that I need to work around in order for my code to work?


texts: Throwing exceptions when validation fails

texts:
When I want to check the validity of an attendance being entered into the system, I perform following action.

AttendancePresenter Class

    void _View_OnCheckValidity(object sender, EventArgs e)
    {
        //ExecuteAction performs exception handling in Base Class
        this.ExecutAction(() =>
        {
            ValidateAttendance();
        });
    }

    private void ValidateAttendance()
    {
        //DataService method returns true if the attendance is valid.
        var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
        //Set the validity of the attendance in a View property.
        //So that View can stop execution if validity is false.
        _View.AttendanceValidity = validity;
        //If validation fails, throw an exception
        if (!validity)
        { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
    }

View

private void txtOutTime_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter & !string .IsNullOrWhiteSpace(txtEmployeeID.Text) &  txtOutTime.Text != DefaultText)
    {
        OnCheckValidity(sender, e);
        if (this.AttendanceValidity)
        { OnEnterAttendance(sender, e); } //This line of code enters attendance into the DB
    }
}

Appreciate if you could review this code and give your feedback. Specially what I want to know is about the exception thrown in presenter if the validation fails. Is it acceptable? Is this is a standard use of throw?


texts:
Another C exercise:

  Write a function that takes an array of 'ints' as its input and finds the smallest and largest elements. It should also compute the median and mean. Use a struct holding the result as the return value

I found it quite awkward that there is no function to copy an array into another array, so I wrote one intdup to use it in the median calculation.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <limits.h>

struct Result {
    int smallest;
    int largest;
    double median;
    double mean;
};

int cmp(void const *lhs, void const *rhs) {
    const int *left = (const int *)lhs;
    const int *right = (const int *)rhs;
    return *left - *right;
}

int * intdup(const int * source, const size_t len)
{
    assert(source);

    int * p = malloc(len * sizeof(int));

    if (p == NULL)
        exit(1);

    memcpy(p, source, len * sizeof(int));
    return p;
}

int find_smallest(const int* array, const size_t len)
{
    assert(array);

    size_t i = 0;
    int smallest = INT_MAX;

    for (i = 0; i < len; ++i) {
        if (array[i] < smallest)
            smallest = array[i];
    }

    return smallest;
}

int find_largest(const int* array, const size_t len)
{
    assert(array);

    size_t i = 0;
    int largest = INT_MIN;

    for (i = 0; i < len; ++i) {
        if (array[i] > largest)
            largest = array[i];
    }

    return largest;
}

double calculate_median(const int* array, const size_t len)
{
    assert(array);

    int* calc_array = intdup(array, len);
    int tmp = 0;

    qsort(array, len, sizeof(int), cmp);

    if (len % 2 == 0) { // is even
        // return the arithmetic middle of the two middle values
        return  (array[(len - 1) / 2] + array[len / 2] ) /2.0;
    }
    else {  // is odd
        // return the middle
        return array[len / 2];
    }
}

double calculate_mean(const int* array, const size_t len)
{
    assert(array);

    double mean = 0;
    size_t i = 0;

    for (i = 0; i < len; ++i)
        mean += array[i];

    return mean / len;
}

struct Result calculate_values(const int* array, const size_t len)
{
    assert(array);

    struct Result result = { 0 };

    result.smallest = find_smallest(array, len);
    result.largest = find_largest(array, len);
    result.median = calculate_median(array, len);
    result.mean = calculate_mean(array, len);

    return result;
}

void print_result(const struct Result* result)
{
    assert(result);

    printf("smallest: %i\n", result->smallest);
    printf("largest: %i\n", result->largest);
    printf("median: %f\n", result->median);
    printf("mean: %f\n\n", result->mean);
}

int main()
{
    int numbers[] = { 1,7,3,4,5,6,7,8,9 };      // 9 elements
//  int numbers[] = { 1,7,3,4,5,6,7,8 };        // 8 elements

    int len = sizeof(numbers) / sizeof(numbers[0]);
    struct Result result = calculate_values(&numbers, len);

    print_result(&result);
    getchar();
    return 0;
}

See the the revised code her: Calculate min, max, mean and median out of array Version 2


texts:
I was reading Joshua Blochs "Effective Java 2nd edition" item 29, which describes how to create Heterogeneous containers, in the end of chapter he wrote:

  A Class object used in this fashion is called a type token. You can
  also use a custom key type. For example, you could have a DatabaseRow
  type representing a database row (the container), and a generic type
  Column as its key.

It wondered me and I wrote this implementation which he has mentioned. Is there something I could have done better ? I'm mostly interested in Column class which serves as Type Token

class Column<T> {

    @SuppressWarnings("unchecked")
    public T cast(Object obj) {
        return (T) obj;
    }
}

public class DatabaseRow {

    private Map<Column<?>, Object> row = new HashMap<>();

    public <T> void putColumn(Column<T> type, T instance) {
        row.put(type, type.cast(instance));
    }

    public <T> T getColumn(Column<T> type) {
        return type.cast(row.get(type));
    }

    public static void main(String[] args) {
        DatabaseRow db = new DatabaseRow();

        Column<Integer> colInt = new Column<>();
        Column<Double> colDouble = new Column<>();

        db.putColumn(colInt, 1);
        db.putColumn(colDouble, 10.0);

        System.out.println(colInt.getClass() + " " + colDouble.getClass());
        System.out.println(db.getColumn(colInt) + " " + db.getColumn(colDouble));
    }

}


texts: Moving and organizing files in download folder

texts:
This is a Python script that I use on my Android tablet.  It moves the files in the Download folder to a folder on the external SD card.  The files are sorted based on their extensions and are moved to folders (for each different type of extension).  If it encounters a new file type, it will create a new folder.  If the file name already exists, the new file will be renamed by appending the first five hash digits to the end of the file name.  The original file is deleted.

How can I improve my program?  What changes should I make?

import os
import hashlib

download_dir = "/sdcard/Download/"
save_dir = "/mnt/external_sd/Download/"

FileList = os.listdir(download_dir)
for File in FileList:
    #print File
    extension = ''.join(os.path.splitext(File)[1])
    name = ''.join(os.path.splitext(File)[0])
    ext = extension.strip('.')

    if os.path.isdir(download_dir + File):
        pass
    else:
        if os.path.exists(save_dir + ext + "/" + File):
            Data = open(download_dir + File, "r").read()
            m = hashlib.sha1()
            m.update(Data)
            h = (m.hexdigest())[0:5]
            file(save_dir + ext + "/" +name+"-"+h+"."+ext, "w").write(Data)
            print File, " ","-->"," ",name+"-"+h+"."+ext
            os.remove(download_dir + File)

        elif os.path.exists(save_dir + ext):
            Data = open(download_dir + File, "r").read()
            file(save_dir + ext + "/" + File, "w").write(Data)
            print File #, " ","-->"," ",name+"."+ext
            os.remove(download_dir + File)

        if os.path.exists(save_dir + ext) != True:
            os.makedirs(save_dir + ext)
            Data = open(download_dir + File, "r").read()
            file(save_dir + ext + "/" + File, "w").write(Data)
            print File , " ","-->"," ","/"+ext+"/"+name+"."+ext
            os.remove(download_dir + File)


texts:
How can I optimize this algorithm to reverse strings inside parentheses?

String reverseParentheses(String s) {
    String tmpCh = new String("");
    String tmpChRe = new String("");
    String tmp = new String("");
    int l = s.length();
    int n = 0;
    int j =0;
    for(int i = 0;i<l;i++){
            if(s.charAt(i)=='(')
                    n++;
    }
    int T[] = new int[n];
    for(int i=0;i<l;i++){
            if(s.charAt(i)=='('){
                    T[j]=i;
                    j++;
            }
    }
    j=0;
    while(n>0){
            j = T[n-1] + 1;
            while(s.charAt(j)!=')'){
                    tmpCh = tmpCh + s.charAt(j);
                    j++;
            }
            for(int q=tmpCh.length()-1;q>=0;q--)
                    tmpChRe = tmpChRe + tmpCh.charAt(q);
            tmp = s.substring(0,T[n-1]) + tmpChRe + s.substring(T[n-1]+tmpChRe.length()+2);
            s = tmp;
            n--;
            tmp = "";
            tmpCh = "";
            tmpChRe = "";
    }
    return s ;
}


texts: Simulate Tic Tac Toe game using C language


texts: Renaming all files/folders in first children folders but not sub-children

texts:
Let's say I have this folder tree:

├──FolderParent
  ├── FolderA
      ├── FolderAA_IMG             -- should be renamed
          ├── file_IMG_AA1.txt     -- should NOT be renamed
          ├── file_VID_AA1.txt     -- should NOT be renamed
      ├── file_IMG_A1.txt          -- should be renamed
      ├── file_PANO_A1.txt         -- should be renamed
  ├── FolderB
      ├── file_IMG_B1.txt          -- should be renamed
      ├── file_PANO_B1.txt         -- should be renamed

As you can see, only the files/folders in the first children folder should be renamed, not the other ones. I follow this base code and then I added a second loop above but I wonder if the double for loop is the right way to go.

import os

# custom var
path= r"C:\Users\user\FolderParent"

# other cvar
number_modified_files= 0

# get all path of subfolder
all_subfolders = [f.path for f in os.scandir(path) if f.is_dir() ]
print(all_subfolders)

for folder in all_subfolders:
    # set the path to the folder: otherwise the rename file won't work
    os.chdir(folder)
    #won't rename files in subfolder but will rename folder in the path
    for filename in os.listdir(folder):
        print("new file:", filename)
        if "IMG_" in filename:
            os.rename(filename, filename.replace('IMG_', ''))
            number_modified_files +=1
        elif "PANO_" in filename:
            os.rename(filename, filename.replace('PANO_', ''))
            number_modified_files +=1
        elif "VID_" in filename:
            os.rename(filename, filename.replace('VID_', ''))
            number_modified_files +=1

print(f"End : {number_modified_file} files renamed")


texts: Python and redis. Make queries more efficient

texts:
My Python code (part of a Django site) queries data from a redis database and loads it into a Pandas dataframe. I'm new to redis, and I think I'm not using the redis library as efficiently as I could.
The database keys are timestamps in epocho format. The values are all json strings. Here's a sample:
Keys:
['1622235486.006474000', '1622235486.006760000', '1622235486.114156000']
Values:
['{"timestampx": "1622235486.006474000", "length": "1416", "dscp": "0", "srcip": "172.17.4.2", "destip": "172.16.1.2"}', '{"timestampx": "1622235486.006760000", "length": "108", "dscp": "0", "srcip": "172.16.1.2", "destip": "172.17.4.2"}', '{"timestampx": "1622235486.114156000", "length": "112", "dscp": "0", "srcip": "172.17.4.2", "destip": "172.16.1.2"}']

Four questions about my code:

First I get all keys with .keys(). Then I filter the list of keys. Then I use .mget(keys). Making two connections to redis (once to get keys, again to get values) seems inefficient. Is there a better method?
Some of the keys aren't epoch timestamps. They start with "1_", and they contain None values. I have to filter those out. I use a separate line of code to do that. Can I do that as part of the keys() function?
I also have a line to sort the keys. Can I ask redis to return them sorted?
Finally, is there an argument for .mget() that filters out None values?

import redis
from datetime import datetime
from datetime import timedelta
import pandas as pd
import json

INTERVAL = 5

r = redis.StrictRedis(**redis_config)
filter = datetime.now() - timedelta(seconds=INTERVAL)

recentkeys = []
allkeys = r.keys(pattern="*")  #Question 1. Is the best query keys() passed to mget()?
allkeys = [x for x in allkeys if not x.startswith('1_')] #Question 2. Can I pass a filter to redis and have it filter the response?

    for k in allkeys:
        if float(k) > float(filter.timestamp()):
            recentkeys.append(k)
    recentkeys.sort()          #Question 3. Can redis return a sorted set?

    values = r.mget(recentkeys)
    values = [x for x in values if x != None]    #Question 4. Can redis filter out None values?

    recent_values = pd.DataFrame(map(json.loads, values))


texts: Am I being too redundant in this Django view (or can I reduce the repetition in my code)?

texts:
I'm new to Django and learning my ways around it. I'm writing a fake basic CRUD app to get me started. In the following code I pretty much copy and paste the same code four times with minor adjustments between each. I only pasted it here twice for the Bands and Album models.

Am I doing this right?

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from models import Band, Album, Song, Instrument

from forms import BandForm, AlbumForm

# Bands Functions:

def bands_index(request):
    latest_band_list = Band.objects.all().order_by('-added_on')[:5]
    return render(request,
                  "bands/index.html", {
                  'latest_band_list': latest_band_list
                  })

def band_detail(request, band_id):
    b = get_object_or_404(Band, pk=band_id)
    return render(request, 'bands/detail.html', {'band': b})

@login_required
def band_add(request):
    form = BandForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        instance = form.save(commit=False)
        instance.added_by = request.user
        instance.save()

        return redirect('/bands/')
    else:
        return render(request, 'bands/add.html',
            {'form': form},
            context_instance=RequestContext(request))

@login_required
def band_remove(request, band_id):
    b = get_object_or_404(Band, pk=band_id)
    b.delete()

    return redirect('/bands/')

@login_required
def band_edit(request, band_id):
    b = get_object_or_404(Band, pk=band_id)

    form = BandForm(request.POST or None, instance=b)

    if request.method == 'POST' and form.is_valid():
        instance = form.save(commit=False)
        instance.save()

        return(redirect('/bands/'))
    else:
        return render(request, 'bands/edit.html',
            {'form': form, 'band_id': band_id},
            context_instance=RequestContext(request))

# Album Functions

def albums_index(request):
    latest_album_list = Album.objects.all().order_by('-added_on')[:5]
    return render(request, "albums/index.html", {
        'latest_album_list': latest_album_list
        })

def albums_detail(request, album_id):
    a = get_object_or_404(Album, pk=album_id)
    return render(request, 'albums/detail.html', {'album': a})

@login_required
def album_add(request):
    form = AlbumForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        instance = form.save(commit=False)
        instance.added_by = request.user
        instance.save()

        return redirect('/albums/')
    else:
        return render(request, 'albums/add.html',
            {'form': form},
            context_instance=RequestContext(request))

@login_required
def album_remove(request, album_id):
    a = get_object_or_404(Album, pk=album_id)
    a.delete()
    return redirect('/albums/')

@login_required
def album_edit(request, album_id):
    a = get_object_or_404(Album, pk=album_id)

    form = AlbumForm(request.POST or None, instance=a)

    if request.method == 'POST' and form.is_valid():
        instance = form.save(commit=False)
        instance.save()

        return(redirect('/albums/'))
    else:
        return render(request, 'albums/edit.html',
            {'form': form, 'album_id': album_id},
            context_instance=RequestContext(request))


texts:
This is a kind of follow up to my previous sort implementation review with specific questions to merge sort, and Modern C++ idioms.

template<typename InputIt1,
         typename InputIt2,
         typename OutputIt,
         typename Comparator = std::less<typename std::iterator_traits<InputIt1>::value_type >>
void merge(InputIt1 first1,
           InputIt1 last1,
           InputIt2 first2,
           InputIt2 last2,
           OutputIt out,
           Comparator cmp = Comparator())
{
    while (first1 != last1 || first2 != last2)
    {
        if (first2 == last2 || first1 != last1 && cmp(*first1, *first2))
        {
            *out = *first1++;
        }
        else
        {
            *out = *first2++;
        }
        ++out;
    }
}

template<typename BidirIt,
         typename Comparator = std::less<typename std::iterator_traits<BidirIt>::value_type >>
void sort_merge(BidirIt first,
                BidirIt last,
                Comparator cmp = Comparator())
{
    typedef std::iterator_traits<BidirIt>::difference_type dt;
    typedef std::iterator_traits<BidirIt>::value_type vt;

    dt size = std::distance(first, last);
    if (size > dt(1))
    {
        auto middle = first + size / dt(2);

        std::vector<vt> left(first, middle);
        std::vector<vt> right(middle, last);

        auto left_begin = left.begin(), left_end = left.end();
        auto right_begin = right.begin(), right_end = right.end();

        sort_merge(left_begin, left_end);
        sort_merge(right_begin, right_end);

        ::merge(left_begin, left_end, right_begin, right_end, first);
    }
}

I am looking for any performance optimizations I may have missed in the algorithm itself, as well as Modern C++ constructs I may not be abiding by for this example.

I looked into in-place merging, however, all of the solutions I have found for in-place merging perform worse. Namely, substituting a sort_insertion for the merge operation. However, if I were to make an in-place sort_merge, I would start a separate topic as it's considered a completely separate algorithm.


texts:
I am creating a simple BMI Calculator to check if the user is overweight or not. I am not sure how much improvement I need but I do appreciate any comments as to whether the coding is inconsistent.

def introduction_page():
  print("Welcome to the BMI Calculator")
  to_start = str(input("Y to start. N to exit"))
  if to_start in ("Y","y"):
    print("We will calculate now")
    return main_page()
  else:
    print("exiting")

def main_page():
  found = False

  while not found:
    weight_store = float()
    height_store = float()
    user_weight = float(input("Please enter your weight(kg): "))
    weight_confirm =  str(input("Y to confirm. N to re-enter"))
    if weight_confirm in("y","Y"):
      weight_store = weight_store + user_weight
      while not found:
        user_height = float(input("Please enter your height(m): "))
        height_confirm = str(input("Y to confirm. N to re-enter"))
        if height_confirm in ("Y","y"):
          height_store = height_store + user_height
          total_height = (height_store * height_store)
          total_weight = (weight_store)
          BMI = (total_weight / total_height)
          print (int(BMI))
          if (BMI < 18.5 or BMI <25) :
            print("Normal Weight")
            found = True
          elif (BMI < 25 or BMI < 30):
            print("Over-weight")
            found = True
          elif (BMI < 30 or BMI < 40):
            print("Obesity")
            found = True
          else:
            print("Morbid Obesity")
            found = True
        else:
          print("Please re-enter")
    else:
      print("Please re-enter!")

introduction_page()


texts: Factory for classes unknown at compile time

texts:
I have a class called Machine. It contains a list of parts and a list of actions. The list of parts will contain instances of the Part class subclasses and the list of actions will contain instances of my Action class subclasses. Each Part subclass will have its corresponding Action subclass. None of the subclasses are available at compile time. When a Machine instance starts all its parts should perform their action.

An action will perform the same manipulation for each Part subclass so I am trying to create a factory class that will create a single instance for each Action subclass. My first thought was to use an interface for Action, but then I would have to create an Action instance for each Part instance I create, or make each class that implemented Action responsible for making itself a singleton. I am not sure if a factory is the best solution and if I am implementing the pattern correctly.

Neither Action nor Part subclasses are available to me so I am using generics. I am new to Java so I am not sure if I am using them correctly - Eclipse gives me several Raw type warnings (I indicated where). Here is my code:

import java.util.ArrayList;

public class GenericsTest
{
    public static void main(String[] args) throws InstantiationException,
            IllegalAccessException
    {

        ArrayList<Part> parts = new ArrayList<Part>();

        Rotate rotate = ActionFactory.getAction(Rotate.class);
        Move move = ActionFactory.getAction(Move.class);

        int i;
        for (i = 0; i < 1000; i++)
        {
            Gear gear = new Gear();
            gear.value1 = i;
            gear.actions.add(rotate);
            parts.add(gear);

            Lever lever = new Lever();
            lever.value2 = i + 2000;
            lever.actions.add(move);
            parts.add(lever);
        }

        Machine machine = new Machine();
        machine.parts.addAll(parts);
        machine.start();
    }

}

class Machine
{
    public void start()
    {
        for (Part part : parts)
        {
            // Raw type warning
            for (Action action : part.actions)
            {
                // Raw type warning
                action.execute(part);
            }
        }
    }

    public ArrayList<Part> parts = new ArrayList<Part>();
}

abstract class Part
{
    // Raw type warning
    public ArrayList<Action> actions = new ArrayList<Action>();
}

abstract class Action<T extends Part>
{
    abstract public void execute(T part);
}

class ActionFactory<T extends Action>
{

    public static <T> T getAction(Class<T> c) throws InstantiationException,
            IllegalAccessException
    {
        T returnAction = null;

        for (Action action : actions)
        {
            if (action.getClass() == c)
            {
                // Unchecked cast warning
                returnAction = (T) action;
            }
        }

        if (returnAction == null)
        {
            returnAction = c.newInstance();
            actions.add((Action) returnAction);
        }

        return returnAction;
    }

    private static ArrayList<Action> actions = new ArrayList<Action>();
}

/*
 * Subject1, Subject2, Action1 and Action2, somewhere else:
 */

class Gear extends Part
{
    public int value1;
}

class Lever extends Part
{
    public int value2;
}

class Rotate extends Action<Gear>
{

    @Override
    public void execute(Gear part)
    {
        System.out.println("rotate action executed, value 1: " + part.value1);
    }
}

class Move extends Action<Lever>
{

    @Override
    public void execute(Lever part)
    {
        System.out.println("move action executed, value 2: " + part.value2);
    }
}