texts: List of students with their classname in current year

texts:
I have 3 tables: students and classes and years. In a fourth table called StudentsInClass, I'm saving students classes in each year. Now I want to show a list of students with their className in Current Year.

This is the query I use but I'm not feeling good with it:

   @StartRow int,
   @EndRow int
As
SET NOCOUNT ON;
  begin
    declare @YearID int;
    set @YearID= (select top 1 ID from Years where IsCurrent =1 );
         select * from(
    select top 10000
              S.*,T2.Title as ClassName,Row_Number() over (order by S.ID)  as
        ResultSetRowNumber from Students S
         left outer join (
    select SC.StudentCode,T1.Title from
             (select * from StudentsInClass where YearID=@YearID) SC
        left outer join Classes T1 on SC.ClassID = T1.ID
    ) T2 on S.Code= T2.StudentCode order by S.Family asc
     ) as PagedResults where ResultSetRowNumber > @StartRow and ResultSetRowNumber <=
     @EndRow;
  end


texts:
Here's an implementation of selection sort, that sorts an array in ascending order.

Please let me know of any improvements/optimisations that can be done.

import java.util.List;

public class SelectionSort {

    public static void start(List<Integer> arrayToSort){
        for(int i = 0; i < arrayToSort.size(); i++) {   // i = leftmost index of unsorted part of the array
            int minimumValue = i;
            for(int j = i; j < arrayToSort.size(); j++){
                if(arrayToSort.get(j) < arrayToSort.get(minimumValue)){
                    minimumValue = j;
                }
            }
            swap(i, minimumValue, arrayToSort);
        }
    }

    private static void swap(int a, int b, List<Integer> arrayToSort){
        int temp = arrayToSort.get(a);
        arrayToSort.set(a, arrayToSort.get(b));
        arrayToSort.set(b, temp);
    }
}


texts:
This program is a random password generator. It asks the user how many chars they want their password to be and how many passwords it should generate.
I used the rand() and srand() methods to generate random letters.

I used dynamic allocation to create a char array based on user input. The comment line is where I tried to dynamically allocate an array of pointers, where each pointer would point to a char array, but I couldn't figure out how to do it so I used a counter and a do while loop and a for loop to create passwords based on user input.

Please give me advice on how I can improve or what I can do differently!

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

const int MAX = 90;
const int MIN = 65;

char * createPassword();

int main()
{
    char * p = createPassword();

    return 0;
}

char * createPassword()
{
    unsigned seed = time(0);

    srand(seed);

    char x = ' ';
    int passwordLength = 0;
    int numOfPasswords = 0;

    std::cout << "How many chars in password: ";
    std::cin >> passwordLength;
    char * pwptr = new char[passwordLength];

    std::cout << "How many passwords should be generated?";
    std::cin >> numOfPasswords;
    //char * passwords = new char *pwptr[numOfPasswords];

    int passwordcount = 0;

    do{
        for(int cnt = 0; cnt < passwordLength; cnt++)
        {
            x = (rand() % (MAX - MIN + 1)) + MIN;
            pwptr[cnt] = x;
            std::cout << pwptr[cnt];
        }
        std::cout << std::endl;
        passwordcount++;
        } while(passwordcount != numOfPasswords);

        return pwptr;
}


texts: Calculate average of array of objects per key value using reduce

texts:
I want to find average of an array of objects based on their key values using the new functional programming style. I found my way around array reduce and solved my problem, but not sure if this is the best way to do it.

Please take a look at my code and see if this is the way to use reduce for my purpose.

Let's say I have an array of objects as follows:

private data = [
    {tv: 1, radio:5,fridge:4},
    {tv: 2, radio:2,fridge:null},
    {tv: 3, radio:6,fridge:5}
];

I want to create another array containing the averages of each of the items in my data array. What I have, and is working, is below:

function summary(){
    var keys= Object.keys(data[0]);
    var sums = {};
    var averages = Object.keys(this.data.reduce((previous, element) => {
        keys.forEach(el => {
            if(element[el] !== null){
                if (previous.hasOwnProperty(el)) {
                    previous[el].value += element[el];
                    previous[el].count += 1;
                } else {
                    previous[el] = {
                        value: element[el],
                        count: 1
                    };
                }
            }
        });
        return previous;
    }, sums)).map(name => {
        return {
            name: name,
            average: sums[name].value / sums[name].count
        };
    });
    console.log(averages);
}

Running the code will give me my expected results:

average = [
    { "name": "tv", "average": 2 },
    { "name": "radio", "average": 4.333333333333333 },
    { "name": "fridge", "average": 4.5 }
]

But is this the best way to solve my problem using new reduce functions?


texts:
I'm getting throw exception and need your review
The main function bellow trying to allocate memory several times and then throw the exception on the upper level.
#include <iostream>
#include <memory>

struct MiserlinessClass{
    char  *   pMemory;
    int       memory_len;
    const int max_size = 10;
    MiserlinessClass(int len){
        if (len>max_size){
            std::cout<<"What a lavish lifestyle! Get out of my face! \n";
            std::bad_alloc exception;
            throw exception;
        }
        pMemory = (char *)malloc(len*sizeof(char));
        memory_len = len;
    }
};

int main(int argc, char** argv){
    int len = (argc==2)? strtol(argv[1],NULL,10): 5;

    std::unique_ptr<MiserlinessClass> objPtr;

    bool allocated = false;
    const int max_cnt = 5;
    int cnt = 0;
    while (!allocated){
        try{
            std::cout<<"Trying to allocate "<<len<<" chars...\n";
            objPtr.reset(new MiserlinessClass(len));
            allocated = true;
        } catch (std::bad_alloc &e){
            len = len >> 1;
            cnt++;
            if (cnt==max_cnt){
                std::cout<<"I give up \n";
                throw  e;
            }
        }
    }
    std::cout<< "Allocated " << objPtr->memory_len << " chars \n";
    return 0;
}

And here are the results of 3 different runs
1 -  allocates memory from the very first attempt,
2 -  tries few times and allocates available and T
3 -  failed after N attempts and throw an exception to the upper level
---------------------------------------
$ make; ./01_exception_pointer 3
make: Nothing to be done for 'all'.
Trying to allocate 3 chars...
Allocated 3 chars
---------------------------------------
$ make; ./01_exception_pointer 64
make: Nothing to be done for 'all'.
Trying to allocate 64 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 32 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 16 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 8 chars...
Allocated 8 chars
---------------------------------------
$ make; ./01_exception_pointer 1023
make: Nothing to be done for 'all'.
Trying to allocate 1023 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 511 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 255 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 127 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 63 chars...
What a lavish lifestyle! Get out of my face!
I give up
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

My questions are

I know the formal difference between returning value and throwing the exception, but still can not feel whether it's time to panic and throw an exception or the program should keep calm and just return the error code.

Is is a proper way to handle bad_alloc exception?

Any extra comments and suggestions :)


texts: Find element that has been removed from a shuffled array

texts:
For a function to determine which element has been removed from a shuffled array, I came up with:

def finder(arr1, arr2):
  l = len(arr1) - 1
  result = list(arr1)
  for i in range(l):
    current = arr1[i]
    if current in arr2:
      result.remove(current)
      arr2.remove(current)
  return result[0]

In the solution for my course it says:

  The naive solution is go through every element in the second array and
  check whether it appears in the first array. Note that there may be
  duplicate elements in the arrays so we should pay special attention to
  it. The complexity of this approach is \$O(N^2)\$, since we would need
  two for loops.

However doing the other way round, i.e. as I've done above seems to avoid a nested for loop, and is therefore linear as far as I can tell. Am I missing something? Have I made an error in my code or my analysis of its efficiency?


texts:
Since std::latch is not in many standard C++ libraries, I tried implementing my own, is it OK from memory ordering perspective or yielding?

class Latch {
    std::atomic<unsigned> count;

public:
    explicit Latch(unsigned cnt)
        : count(cnt)
    {
    }

    void arrive_and_wait()
    {
        assert(count > 0);

        count.fetch_sub(1, std::memory_order_release);
        while (count.load(std::memory_order_acquire) > 0) {
            std::this_thread::yield();
        }
    }
};
```


texts:
I need to write a function which will do the following functionalities

I would get a string and a array as input parameters

The string would be like one of the following for example

catalog
level1Cats
level2Cats

The String array would be containing the data for the strings mentioned above for example

catalog:("12605")

level1Cats:("12605_For the Home") OR level1Cats:("12605_Clothing")

level2Cats:("12605_For the Home_Appliances")

Now if the String is catalog and the array is the one mentioned above then the output should be 12605.

If its is level1Cats then the output should be an array of the following strings

12605_For the Home
12605_Clothing

I wrote the following code to implement the above mentioned logic It's doing the functionality without a flaw, Can i implement the same in a different and a more efficient way?

public static String[] parseFQ(String fqField, String fqs[]) {

    List<String> prefixes = new ArrayList<String>();

    if(fqField != null && fqField.length() > 0
            && fqs != null && fqs.length > 0) {

        //Get the fq which starts with given field name.
        for(String fq : fqs) {
            if(fq.startsWith(fqField)) {
                fqField = fq;
                break;
            }
        }

        boolean parsed = false;
        while(!parsed) {
            int quoteStart = fqField.indexOf("\"");
            int quoteEnd = (quoteStart >= 0) ? fqField.indexOf("\"", quoteStart+1) : -1;
            if(quoteEnd > 0) {
                prefixes.add(fqField.substring(quoteStart+1, quoteEnd));
                fqField = fqField.substring(quoteEnd+1, fqField.length());
            } else {
                parsed = true;
            }
        }
    }
    //Return the prefixes array
    return prefixes.toArray(new String[]{});
}


texts: HTML5: Section in Article is Untitled Section in the Outliner

texts:
Assume I have an article list, each with the following format:

Article

In the header I'm placing: the article's title, the author and the image,
the paragraph belongs to the section, in the footer all the bottom elements (share, read more).

This is my html5 article code:

HTML5 Website

        Title of the Article 1

        Name of the Author

Paragraph content

Title of the Article 2

Name of the Author

Paragraph content

This is the generated outline:
http://gsnedders.html5.org/outliner/

My Questions:
For example1:
Is it benefit to the outliner to mix Title and Author in the same element?
Considering that the outliner reads both as one.

For example2:
The problem I find is that when using section it generates an untitled section in the outliner. So the only solution is to use a div instead of a section. Is that semantic?

General Question:
I want to know if my whole code is properly semantic, respecting both html5 specification and the outliner.


texts: Return a new array where each element is the number of smaller elements to the right of that element in the original input

texts:
The task:

  Given an array of integers, return a new array where each element in
  the new array is the number of smaller elements to the right of that
  element in the original input array.

  For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0],
  since:

  There is 1 smaller element to the right of 3
  There is 1 smaller element to the right of 4
  There are 2 smaller elements to the right of 9
  There is 1 smaller element to the right of 6
  There are no smaller elements to the right of 1

const lst = [3, 4, 9, 6, 1];

My solutions:

const numberOfSmallerElem = lst => lst.map((x,i) => lst.slice(i + 1).reduce((acc,y) => y < x ? ++acc : acc, 0));
console.log(numberOfSmallerElem(lst));

function numberOfSmallerElem2(lst) {
  for (let i in lst) {
    lst[i] = lst.slice(i).reduce((acc,y) => y < lst[i] ? ++acc : acc, 0);
  }
  return lst;
}
console.log(numberOfSmallerElem2(lst));

function numberOfSmallerElem3(lst) {
  const ret = [];
  for (let i = 0, len = lst.length; i < len - 1; i++) {
    const reference = lst[i];
    let counter = 0;
    for (let j = i + 1; j < len; j++) {
      if(lst[j] < reference) { counter++; }
    }
    ret.push(counter);
  }
  ret.push(0);

  return ret;
}
console.log(numberOfSmallerElem3(lst));


texts: Printing a singly linked list with time complexity O(n) and space complexity O(sqrt(n))

texts:
My aim is to write a method which prints contents of a singly linked list in reverse order with time complexity \$O(n)\$ and space complexity \$O(\sqrt{n})\$. The best I could come up with is to store the pointers to nodes in an array and print it in reverse order.

void display_reverse(List *l)
{
    int list_size = size(l);
    Node** pointer_array = malloc(list_size*sizeof(Node*));
    Node* temp = l->head;
    int i;
    for(i = 0; i<list_size; ++i, temp=temp->next)
        pointer_array[i] = temp;
    for(i = list_size - 1; i>=0; --i)
        printf("%d\n", pointer_array[i]->data);
    free(pointer_array);
}

int size(List* l)
{
    int count = 0;
    Node* temp = l->head;
    while(temp!= NULL)
    {
        ++count;
        temp = temp->next;
    }

    return count;
}

Is there a better way of doing it, without modifying the list in any way?  There is another option where time complexity is \$O(n \log n)\$ and space complexity is \$O(\log n)\$. How can I go about solving this?


texts: Query your MySQL server for table size by row count and physical size by database

texts:
After writing a similar SQL procedure to check my table sizes several times, I wrote this stored procedure to check my MySQL database's table size. It will show you the table sizes and row count across all tables in a particular database. I use this to identify any scaling issues with my database and review storage.

Stored procedure

DELIMITER //
CREATE PROCEDURE checkTableSize
(IN tableName VARCHAR(255))
BEGIN
    SELECT
        table_name AS `Table`,
        round(avg(((data_length + index_length) / 1024 / 1024)), 2) as `Size in MB`,
        sum(table_rows) as rowCount
    FROM information_schema.TABLES  where table_schema = tableName
    GROUP by table_name
    ORDER by rowCount desc;
END //
DELIMITER ;

How to call results

call checkTableSize('EnterDBNameHere');

I'd like to know if there are out-of-the-box solutions from MySQL, or more elegant solutions to my stored procedure. I also thought I'd share in case this helps anyone.


texts:
I wrote a silly Rust program inspired by a WolframAlpha query. I know, that's nothing serious, but if there's anything that could be made more, well, proper Rust-like, I'd love to know! Of course, general feedback is welcomed too.
For starters, here's my Cargo.toml:
[package]
name = "rusted-days"
version = "0.1.0"
authors = ["baduker"]
edition = "2018"

[dependencies]
chrono = "0.4.19"

And the code:
use std::io;
use std::io::Write;
use chrono::{NaiveDateTime, DateTime, Utc, Datelike};

fn main() {
    let prompt = "What's your date (DD/MM/YYYY)?: ";
    let date = input(prompt).expect("Something went wrong! o.O");
    show_interpretation(parse_date(date));
}

fn input(user_input: &str) -> io::Result<String> {
    print!("{}", user_input);
    io::stdout().flush()?;

    let mut buffer: String = String::new();
    io::stdin().read_line(&mut buffer)?;

    Ok(buffer.trim_end().to_owned())
}

fn parse_date(date: String) -> DateTime<Utc> {
    let naive_date = chrono::NaiveDate::parse_from_str(
        date.as_str(), "%d/%m/%Y"
    ).unwrap();

    let naive_datetime: NaiveDateTime = naive_date
        .and_hms(0, 0, 0);

    DateTime::<Utc>::from_utc(naive_datetime, Utc)
}

fn show_interpretation(date: DateTime<Utc>) {
    println!("Input interpretation: days since {}", date.format("%A, %B %d, %Y"));

    let total_days = Utc::now() - date;
    println!("Result:\n{} days have rusted away ¯\\_(ツ)_/¯", total_days.num_days());

    let years = Utc::now().year() - date.year();
    let months = Utc::now().month() - date.month();
    let days = Utc::now().day() - date.day();

    println!("Timespan:\n{} year(s), {} month(s), {} day(s)", years, months, days);
    println!("{} weeks", total_days.num_weeks());
    println!("{:.2} years", total_days.num_days() as f32 / 365_f32);
}

A sample output (you should get):
What's your date (DD/MM/YYYY): 01/01/1970
Input interpretation: days since Thursday, January 01, 1970
Result:
18567 days have rusted away ¯\_(ツ)_/¯
Timespan:
50 years, 10 month(s), 0 days
2652 weeks
50.87 years


texts:
I assigned the following contrived problem in a comparative programming languages course to give students practice with "streaming":

Write function that returns the top ten players by points-per-game among the players that have been in 15 games or more. The input to your function will be an object, keyed by team, with a list of player stats. Each player stat is an array with the player name, the number of games played, and the total number of points.

A sample data set is as follows:
stats = {
    'ATL': [
        ['Betnijah Laney', 16, 263],
        ['Courtney Williams', 14, 193],
    ],
    'CHI': [
        ['Kahleah Copper', 17, 267],
        ['Allie Quigley', 17, 260],
        ['Courtney Vandersloot', 17, 225],
    ],
    'CONN': [
        ['DeWanna Bonner', 16, 285],
        ['Alyssa Thomas', 16, 241],
    ],
    'DAL': [
        ['Arike Ogunbowale', 16, 352],
        ['Satou Sabally', 12, 153],
    ],
    'IND': [
        ['Kelsey Mitchell', 16, 280],
        ['Tiffany Mitchell', 13, 172],
        ['Candice Dupree', 16, 202],
    ],
    'LA': [
        ['Nneka Ogwumike', 14, 172],
        ['Chelsea Gray', 16, 224],
        ['Candace Parker', 16, 211],
    ],
    'LV': [
        ['A’ja Wilson', 15, 304],
        ['Dearica Hamby', 15, 188],
        ['Angel McCoughtry', 15, 220],
    ],
    'MIN': [
        ['Napheesa Collier', 16, 262],
        ['Crystal Dangerfield', 16, 254],
    ],
    'NY': [
        ['Layshia Clarendon', 15, 188]
    ],
    'PHX': [
        ['Diana Taurasi', 13, 236],
        ['Brittney Griner', 12, 212],
        ['Skylar Diggins-Smith', 16, 261],
        ['Bria Hartley', 13, 190],
    ],
    'SEA': [
        ['Breanna Stewart', 16, 317],
        ['Jewell Loyd', 16, 223],
    ],
    'WSH': [
        ['Emma Meesseman', 13, 158],
        ['Ariel Atkins', 15, 212],
        ['Myisha Hines-Allen', 15, 236],
    ],
}

Now in JavaScript, there is a "fluent" or method-chaining style readily apparent:
function topTenScorers(stats) {
  return Object.entries(stats)
    .flatMap(([team, players]) => players.map(player => [...player, team]))
    .filter(([, games, ,]) => games >= 15)
    .map(([name, games, points, team]) => ({ name, ppg: points / games, team }))
    .sort((p1, p2) => p2.ppg - p1.ppg)
    .slice(0, 10)
}

However, my Python solution (below) just doesn't satisfy the same way (I'm more of a JavaScript programmer). I've heard that Python list comprehensions are preferred to map and filter; I think that Python doesn't have a built-in flat_map, and, well, although you can do fancy things with itertools, Pythonic programs tend to, I think, be more favorable to computing intermediate expressions than to chaining. So I came up with the following:
def top_ten_scorers(stats):
    with_teams = [[*player, team]
                for (team, players) in stats.items()
                for player in players]
    with_ppg = [{'name': name, 'ppg': points/games, 'team': team}
                for [name, games, points, team] in with_teams
                if games >= 15]
    return sorted(with_ppg, key=lambda k: k['ppg'], reverse=True)[:10]

I'd love to know whether the code is in the style of current Python best practices. I know Python is well-loved by data scientists, and this problem, although very contrived, feels data-sciencey to me, so I figured a set of best practices would have arisen that my code might not meet. Also, I'm having trouble with names for the intermediate expressions, and am not sure whether the breakdown of steps is too coarse or too fine. I'm not sure which approach to take to clean it up.
Of course, it is not imperative that a streaming solution be found; what is most important is a solution that best fits the Zen of Python rule(s) "There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch."


texts:
HtmlAgilityPack is being really slow pulling back results. I have seen similar tools that get results a lot faster, but it's taking over a minute just to get the viewcounts on YouTube, and that's just with the first page of results.

Ideally I want to loop through multiple elements, but a nested loop wouldn't work for this code.

private void button1_Click(object sender, EventArgs e)
{
    //webBrowser1.Navigate("www.youtube.com/results?search_query=grindtime");
    StringBuilder output = new StringBuilder();
    string raw = "http://www.youtube.com/results?search_query=grindtime";
    HtmlWeb webGet = new HtmlWeb();
    webGet.UserAgent = "Mozilla/5.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4";
    var document = webGet.Load(raw);
    var viewcount = document.DocumentNode.SelectNodes("//*[@class='viewcount']");
    //var videotitle = document.DocumentNode.SelectNodes("//a[@class='yt-uix-tile-link']");
    //var browser = document.DocumentNode.SelectNodes("//*[@class='viewcount']");

    if (viewcount != null)
    {
        foreach (var v in viewcount)
        {
             output.AppendLine(v.InnerHtml);

             ListViewItem lvi = new ListViewItem("#1");
             lvi.SubItems.Add("video title here");
             lvi.SubItems.Add(b.InnerHtml);
             //views
             //desc..
             //lid = link in desc yes/no
             listView1.Items.Add(lvi);
         }
     }


texts: Improving time complexity of finding the longest palindrome in Python

texts:
The Longest Palindromic Substring challenge from InterviewBit:

Given a string S, find the longest palindromic substring in S.

where a "substring" must be contiguous, and in case of ties the first such substring should be returned.

Example:
Input : "aaaabaaa"
Output : "aaabaaa"

My code:
class Solution:
    # @param A : string
    # @return a strings
    def clean_string(self, string):
        result = []
        str_list = string.split()
        for word in str_list:
            result.append(''.join(ch for ch in word if ch.isalnum()))
        return "".join(result).lower()

    def is_palindrome(self, string):
        if len(string)==1:
            return True
        if string[::-1]==string:
            return True
        return False

    def longestPalindrome(self, A):
        if len(A)==1:
            return A
        cleaned = self.clean_string(A)
        start_index = 0
        max = -1
        longest = None
        while (start_index < len(cleaned)-1):
            end_index = start_index
            while (end_index < len(cleaned)):
                end_index +=1
                if self.is_palindrome(cleaned[start_index:end_index]):
                    if len(cleaned[start_index:end_index]) > max:
                        longest = cleaned[start_index:end_index]
                        max = end_index-start_index

            start_index +=1
        return longest

s = Solution()
print(s.longestPalindrome("abbcccaaadaaakl"))

My code passes all the tests except for the time limit:

Please provide some insight as to how to modify the code to pass the time limit.


texts: No getter/setter on model with many instance vars

texts:
While reading Object calisthenics and Getters/Setters. Evil. Period. I got confused. Let me explain it by example.

I have this organization class, representing the information about organization, the classic entity:

class Organization
{
    private $name;

    private $city;

    private $street;

    private $phone;

    private $email;

    public function __construct($name, $city, $street, $phone, $email)
    {
        $this->name = $name;
        $this->city = $city;
        $this->street = $street;
        $this->phone = $phone;
        $this->email = $email;
    }

    public function getName()
    {
        ....
    }

    public function getCity()
    {
        ....
    }

    public function setCity($newCity)
    {
        ....
    }

    public function getStreet()
    {
        ....
    }

    public function setStreet($newStreet)
    {
        ....
    }

    public function getPhone()
    {
        ....
    }

    public function getEmail()
    {
        ....
    }

    public function setPhone($newPhoneNumber)
    {
        ....
    }
}

The organization name, city, street, phone and email may change, so the setters looks kind a logical. Getters are used to to display the properties of organization in table. How can I remove the boilerplate code and break trough from this anemic model? Maybe this is the case where the getter/setter is unavoidable?

Also object initialization using __construct. Is it a good practice to pass so many instance variables to constructor?

I gave it a try, according to what I read. Created some ValueObject to store information and do validation (don't know if the ValueObject should do a validation on its data):

class Phone
{
    private $phone;

    public function __construct($phone)
    {
        if (!$this->validate($phone)) {
            throw new InvalidPhoneNumberException();
        }

        $this->phone = $phone;
    }

    public function getPhone()
    {
        return $this->phone;
    }

    private function validate($phone)
    {
        // validate the phone number
    }
}

class Email
{
    private $email;

    public function __construct($email)
    {
        if (!$this->validate($email)) {
            throw new InvalidEmailAddressException();
        }

        $this->email = $email;
    }

    public function getEmail()
    {
        return $this->email;
    }

    private function validate($email)
    {
        // validate email
    }
}

class Address
{
    private $city;

    private $street;

    public function __construct($city, $street)
    {
        $this->city= $city;
        $this->street = $street;
    }

    public function getCity()
    {
        return $this->city;
    }

    public function getStreet()
    {
        return $this->street;
    }
}

Then passed these objects instead of string representations of data to my Organization and did some renaming on methods:

class Organization
{
    private $name;

    private $address;

    private $phone;

    private $email;

    public function __construct($name, Address $address, Phone $phone, Email $email)
    {
        $this->name = $name;
        $this->address = $address;
        $this->phone = $phone;
        $this->email = $email;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function getPhone()
    {
        return $this->phone;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function changeAddress(Address $newAddress)
    {
        $this->address = $newAddress;
    }

    public function changePhoneNumber(Phone $newPhoneNumber)
    {
        $this->phone = $newPhoneNumber;
    }
}

Does this code smells less and looks more mature from the perspective of OOP?


texts:
So, I code sometimes but I'm always bored with my code and I felt I have a lack of python skills and I see some piece of code when I finished it. This below is a piece that I did today and I want to share with you to take some advice in how I can improve this and so my Python proficiency.
The idea below is to do a regression over a column and create three new columns with the prediction to the next 30, 60 and 90 days. The code works fine and do what I expect but I'm not happy with it.
The dataset is something like this:

f0
f1
f2
f3
f4
f5
f6
f7
f8
f9
f10
f11

AA
1648
0
0
89440
40760
0
2021-01-21
0
0
40760
0

...
...
...
...
...
...
...
...
...
...
...
...

AA
1802
36196
8980
89440
90380
45176
2021-03-16
2522
527
0
3049

BB
1868
0
0
335153
87760
0
2021-01-21
0
0
87760
0

...
...
...
...
...
...
...
...
...
...
...
...

BB
1872
112758
42762
335153
260860
155520
2021-03-16
0
0
0
0

CC
1868
0
0
420774
282320
0
2021-01-21
0
0
282320
0

...
...
...
...
...
...
...
...
...
...
...
...

CC
1872
360787
106921
420774
762104
467708
2021-03-16
18766
3902
0
22668

DD
1868
0
0
86173
31000
0
2021-01-21
0
0
31000
0

...
...
...
...
...
...
...
...
...
...
...
...

DD
1872
28163
3628
86173
66600
31791
2021-03-16
0
0
0
0

 df['prev30'] = np.int(0)
    df['prev60'] = np.int(0)
    df['prev90'] = np.int(0)

    for f0 in df['f0'].unique():

        dataset = df[df['f0'] == f0]
        y = dataset.iloc[:, 2:3].values
        X = dataset.iloc[:, 0:1].values

        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/4, random_state = 0)
        regressor = LinearRegression()
        regressor.fit(X_train, y_train)

        max_data = dataset['f1'].max()
        array = [30,60,90]

        for i in array:
            if i == 30:
                prev = "prev30"
            elif i == 60:
                prev = "prev60"
            else:
                prev = "prev90"

            new_X = np.array([[max_data + i]])
            predic = int(regressor.predict(new_X))
            dataset[prev] = predic

        print(dataset[dataset["f0"] == f0])


texts: A wounded Zombie finder, or: how to find the almost dead undead?

texts:
The Zombies are on their way to eat our statistics. Fortunately, we have a way to get rid of them: our votes. However, we need to find them first. The /unanswered section is too large and contains many strong enemies where we have to write a review first. But the StackExchange Data Explorer can sniff almost dead Zombies from a mile.

For this, we need a fitting query. This is what I've tried:

SELECT
  q.Id AS [Post Link],
  MAX(a.Score) AS [Best answer score]
FROM
  Posts q
JOIN
  Posts a ON a.ParentId = q.Id
WHERE
      q.PostTypeId = 1
  AND q.AnswerCount > 0
  AND q.AcceptedAnswerId IS NULL
  AND a.PostTypeId = 2
GROUP BY
  q.Id
HAVING
 MAX(a.Score) = 0

You can run and find the query on SEDE.

It searches for questions (q.PostTypeId = 1) that have at least one answer, no accepted answer, and the maximum score of all its answers is 0. The resulting list can then be checked for fast Zombie removal.

Is there something that is utterly wrong? Or can this weapon help us in our fight against the undead?


texts: JOIN and sprintf rather than two queries and echo

texts:
It works fine, however it's a little messy. I understand it would be better for performance to use JOIN and have been advised before to use sprintf. However, it's pretty confusing and I cannot understand the PHP tutorials on it.

<?php
$exerciseID = get_the_ID();
$blogUrl = get_site_url();

global $wpdb;

$getImageIdQuery = "
SELECT image_map
FROM wp_posts
WHERE ID = '".$exerciseID."'";

$imageID = $wpdb->get_results($getImageIdQuery);

foreach($imageID as $row2) {
 }

$mappedImage = $row2->image_map;

$query = "
SELECT id
FROM imagemap
WHERE exercise = '".$mappedImage."'";

$result = $wpdb->get_results($query);

foreach($result as $row) {
 }
echo '
';
echo '
' .the_title(). '
';
echo '
';
echo "id. ".jpg />";

?>


texts:
I have created a program that calculates pi using a Monte Carlo method. It also animates the process and displays the value as it is updated to show how it gets closer and closer to the actual value as more time passes. It is made with HTML canvas. I would like some feedback on my program.

"use strict";

function hypot(a, b) {
  return Math.sqrt(a * a + b * b);
}

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min
}

class Circle {
  constructor(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
  }

  draw() {
    ctx.strokeStyle = "#000";
    ctx.lineWidth = "5px";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    ctx.stroke();
  }

  collidePoint(pt) {
    var dx = this.x - pt.x;
    var dy = this.y - pt.y;
    return hypot(dx, dy) <= this.r;
  }
}

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  draw() {
    ctx.fillStyle = "rgba(0, 0, 0, 16)";
    ctx.fillRect(this.x, this.y, 1, 1);
  }
}

const canvas = document.getElementById("disp");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var width = parseInt(canvas.width);
var height = parseInt(canvas.height);
var trys = 0;
var lands = 0;
var area = width * height;
var points = [];
var ball = new Circle(width / 2, height / 2, Math.min(width, height) / 2);
setInterval(step, 10);

function drawAll() {
  ctx.clearRect(0, 0, width, height);
  ball.draw();
  points.forEach((point) => {
    point.draw();
  });
}

function step() {
  drawAll();
  var pnt = new Point(randInt(0, width), randInt(0, height));
  trys++;
  if (ball.collidePoint(pnt)) {
    lands++;
  }
  var prob = lands / trys;
  var pi = (prob * area) / Math.pow(ball.r, 2);
  document.getElementById("out").innerText = pi.toString();
  points.push(pnt);
}
html, body {
  height: 100%;
  overflow: hidden;
}

#disp {
  width: 100vw;
  height: 100vh;
  margin: 0;
}

#box {
  position: absolute;
  z-index: 1;
  width: 200px;
  height: 20px;
  left: 5%;
  top: 5%;
  background-color: whitesmoke;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Monte Carlo Pi</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <canvas id="disp"></canvas>
    Pi &#x2248;


texts: Map, which contains biomes, which contain landforms, which contain tiles

texts:
I am trying to model this:

a Map can have multiple child of type Biomes and no parent
a Biome can have multiple child of type Landforms and a Map as its parent
a Landform can have multiple child of type Tiles and a Biome as its parent
a Tile has no child and a Landform as its parent

I want it to be generic so I can easily add new links to the chain (like adding a new kind of section between Biome and Landform for example). Here is the less ugly solution I have for now :

public class RootSection<T, TChild> : Section<T>
    where T : Section<T>
    where TChild : Section<TChild>
{
    public List<TChild> ChildSection { get; } // duplicate
}

public class MiddleSection<T, TChild, TParent> : Section<T>
    where T : Section<T>
    where TChild : Section<TChild>
    where TParent : Section<TParent>
{
    public List<TChild> ChildSection { get; } // duplicate
    public TParent Parent { get; } // duplicate
}

public class BottomSection<T, TParent> : Section<T>
    where T : Section<T>
    where TParent : Section<TParent>
{
    public TParent Parent { get; } // duplicate
}

public class Section<T>
    where T : Section<T>
{
    List<T> AdjacentSections { get; }
}

public class Map : RootSection<Map, Biome> { } // (T, TChild)
public class Biome : MiddleSection<Biome, Landform, Map> { } // (T, TChild, TParent)
public class Landform : MiddleSection<Landform, Tile, Biome> { } // (T, TChild, TParent)
public class Tile : BottomSection<Tile, Landform> { } // (T, TParent)

As you can see, there is already duplicate code and I can't think of a solution to get rid of this issue. I feel like I am either missing something obvious or over-complexifying the problem. I also feel like this is close to a classic data structure which I ignore the name preventing me from searching for inspiration on the net.

How can I rewrite this code to look cleaner ? Am I right to think it's close to a well known data structure ?


texts: Date formatters, lazily instantiated once

texts:
I would like to create two date formatters only on first call. In Objective-C I would use dispatch_once() but now working in Swift. Am I doing it correctly? My code is based on example that was using class instead of static but it looks like it's Swift 2.0 doesn't support it yet.

class HomeContentItem : NSObject {
    var hideDescription:Bool = false
    var expanded:Bool = true

    var imageURL:String?
    var titleShort:String?
    var textBody:String?
    var sectionName:String?
    var dateString: String?
    var watermarkImage:UIImage?

    var moreTappedAction: ((AnyObject) -> (Void))?
    var sectionNameTappedAction: ((AnyObject) -> (Void))?
    var selectedItemAction: ((AnyObject) -> (Void))?

    static let sameDayFormatter = { (Void) -> NSDateFormatter in
        let formatter = NSDateFormatter()
        formatter.dateFormat = "hh:mm"
        return formatter
        }()

    static let differentDayFormatter = { (Void) -> NSDateFormatter in
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        return formatter
        }()

    func setDate(date:NSDate) {
        if date.isSameDateAs(NSDate()) {
            self.dateString = HomeContentItem.sameDayFormatter.stringFromDate(date)
        } else {
            self.dateString = HomeContentItem.differentDayFormatter.stringFromDate(date)
        }
    }
}

And extention to date:

extension NSDate {
    func isSameDateAs(date : NSDate) -> Bool {
        let firstCalendar = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
        let secondCalendar = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
        return (firstCalendar.day == secondCalendar.day &&
            firstCalendar.month == secondCalendar.month &&
            firstCalendar.year == secondCalendar.year)
    }
}


texts:
I guess I made the mistake of creating UIImage *image1 to UIImage *image11. Can an one advise me on how to improve it?

+(NSArray *)stampImages{
        UIImage *image1 = [UIImage imageNamed:@"abcd.png"];
        UIImage *image2 = [UIImage imageNamed:@"fron.png"];
        UIImage *image3 = [UIImage imageNamed:@"amule.png"];
        UIImage *image4 = [UIImage imageNamed:@"dog2_trans.png"];
        UIImage *image5 = [UIImage imageNamed:@"dolphin.png"];
        UIImage *image6 = [UIImage imageNamed:@"hit.png"];
        UIImage *image7 = [UIImage imageNamed:@"abcd.png"];
        UIImage *image8 = [UIImage imageNamed:@"qw.png"];
        UIImage *image9 = [UIImage imageNamed:@"rewq.png"];
        UIImage *image10 = [UIImage imageNamed:@"rac.png"];
        UIImage *image11 = [UIImage imageNamed:@"gs.png"];
        UIImage *image12= [UIImage imageNamed:@"acb3.png"];
        NSMutableArray *stampList = [NSMutableArray arrayWithObjects:image1,image2,image3,image4,image5,image6,image7,image8,image9,image10,image11,image12,nil];
        return stampList;
    }


texts:
This is a plugin I wrote a while ago and I'm trying to improve it. Is this the best practice for jQuery plugins? Should I use options for flexibility?

The initial aim was to replicate the syntax for .fadeIn() in jQuery.

Any pointers would be appreciated.

/* AnimateCSS - CSS transitions instead of js */
(function ($, window, document, undefined) {

    // Function-level strict mode syntax
  'use strict';

    $.fn.animateCSS = function (effect, delay, callback) {

        // Return this to maintain chainability
        return this.each(function () {

            // Cache $(this) for speed and compression
            var $this = $(this),
                transitionEnd = "webkitAnimationEnd mozAnimationEnd msAnimationEnd oAnimationEnd animationEnd",
                animated = "animated",
                visibility = "visibility",
                visible = "visible",
                hidden = "hidden";

            // Create a function we can call later
            function run() {
                // Add the animation effect with classes
                $this.addClass( animated + " " + effect);

                // Check if the elemenr has been hidden to start with
                if ($this.css( visibility ) === hidden) {
                    // If it has, show it (after the class has been added)
                    $this.css( visibility, visible);
                }

                // If the element is hidden
                if ($this.is(":" + hidden)) {
                    // Show it
                    $this.show();
                }

                // Event triggered when the animation has finished
                $this.bind( transitionEnd, function () {
                    // Remove the classes so they can be added again later
                    $this.removeClass(animated + " " + effect);

                    // Add a callback event
                    if (typeof callback === "function") {
                        // Execute the callback
                        callback.call(this);

                        // Unbind the event handlers
                        $this.unbind( transitionEnd );
                    }
                });
            }
            // Check if delay exists or if it"s a callback

            if (!delay || typeof delay === "function") {
                // If it"s a callback, move it to callback so we can call it later
                callback = delay;

                // Run the animation (without delay)
                run();
            } else {
                // Start a counter so we can delay the animation if required
                setTimeout( run, delay );
            }
        });
    };
})(jQuery, window, document);


texts: Run length encoding of vectors in MATLAB: looped version and vectorized version

texts:
A project I'm working on requires something akin to run length encoding on a vector in matlab. The data is in the form of a numeric vector, and the output is in the form of two vectors, elems and lens that hold the elements and their respective run lengths. For example data = [20 13 12 12 12 18 17 16 16 11] would give elems = [20 13 12 18 17 16 11] and lens = [1 1 3 1 1 2 1]. There is no minimum run length.

My first attempt uses loops:

clear all

data = [2 1 2 3 3 1 2 2 3 3 1 1 1 1 1 2 2 1 1 3 3 3 3 2 1 3 3 2 2 1 1 1 2 2 2 2 3 1 1 1];
n = length(data);
elems = zeros(n, 1);
lens = zeros(n, 1);

len = 1;
elem = data(1);
c = 1;
for k = 2:n
    if data(k) == elem
        len = len + 1;
    else
        elems(c) = elem;
        lens(c) = len;
        c = c + 1;
        elem = data(k);
        len = 1;
    end
end

elems(c) = elem;
lens(c) = len;
lens = lens(lens ~= 0);
elems = elems(lens ~= 0);

It's pretty basic although I couldn't think of a way to efficiently preallocate the elems and lens vectors to something smaller than n. I figured I could always start them small, e.g. n/2 or something, keep track of their size, then reallocate them to something larger, maybe 1.5 times the previous size, if they were running out of room, or something like that.

My second attempt is completely vectorized:

clear all

data = [2 1 2 3 3 1 2 2 3 3 1 1 1 1 1 2 2 1 1 3 3 3 3 2 1 3 3 2 2 1 1 1 2 2 2 2 3 1 1 1];
breaks = [true data(2:end) ~= data(1:end-1)];
run_starts = find([breaks true]);
elems_vec = data(breaks);
lens_vec = diff(run_starts);

Can either of these methods be improved? The algorithms are pretty simple, and Im really just looking for general feedback that can help me learn matlab a bit more.


texts:
I want to improve the performance of this program.

count = 0
store = []
n = 9238899039
for i in range(1,n):
    if i*i*i <= n:
        count += 1
        store.append(i)
print count

At the moment it is very slow. I need to find all cubic numbers up to n.


texts:
I need to extend the default TextWriterTraceListener class to include timestamps with each message on same line and file rotation. I can't seem to find any way of doing it with TraceListener configuration.

Can you please review it and let me know any flaws to be used in a multi-threaded application?

using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Text;
namespace ConsoleApplication1
{
    public class MyTextWriterTraceListener : TextWriterTraceListener
    {
        public MyTextWriterTraceListener(System.IO.Stream stream) : base(stream) { }
        public MyTextWriterTraceListener(System.IO.Stream stream, string name) : base(stream, name) { }
        public MyTextWriterTraceListener(string FileName, string name) : base(FileName, name) { RotateLogFiles(FileName); }
        public MyTextWriterTraceListener(string FileName) : base(FileName) { RotateLogFiles(FileName); }
        public MyTextWriterTraceListener(System.IO.TextWriter writer, string name) : base(writer, name) { }
        public MyTextWriterTraceListener(System.IO.TextWriter writer) : base(writer) { }
        public override void Write(string Msg)
        {
            base.Write(Msg);
            base.Flush();
        }
        public override void WriteLine(string Msg)
        {
            base.WriteLine(LinePrefix() + Msg);
            base.Flush();
        }

        private void RotateLogFiles(string FileName)
        {
            FileInfo TheFileInfo = new FileInfo(FileName);
            if (TheFileInfo.Exists == false)
                return;
            if (TheFileInfo.LastWriteTime.Date < DateTime.Today)
            {
                TheFileInfo.MoveTo(string.Format(@"{0}\{1}_{2}{}", TheFileInfo.DirectoryName, TheFileInfo.Name, TheFileInfo.LastWriteTime.ToString(), TheFileInfo.Extension));
            }
        }

        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
        private string LinePrefix()
        {
            DateTime Now = DateTime.Now;
            return string.Format("{0} : ", Now.ToString("dd-MMM-yyyy HH:mm:ss"));
        }
    }
}


texts:
I have made a bit array implementation that can be seen below:

unsigned int uint_size();

class Bitarray1D {
private:
    unsigned int * array_;
    int elements_;
    int bits_;

public:
    Bitarray1D(int bits);

    ~Bitarray1D();

    void size(int& bits) const;

    unsigned int count() const;

    void setAll(int value);

    void set(int index, int value);

    int test(int index) const;

    unsigned int operator [](int index) const;

    void flip(int index);

    std::string to_string() const;

private:
    void init();

};

and some of the functions:

void Bitarray1D::init(){
        if (bits_ == 0) throw std::invalid_argument("Can't initialize zero size array");

        int number_of_elements = bits_;
        std::cout << "unsigned int size: " << uint_size() << " bytes" << std::endl;

        elements_ = std::ceil((bits_*1.0)/(uint_size()*1.0));
        array_ = new unsigned int[elements_];
}

int Bitarray1D::test(int index) const {
        if (index < 0 || index >= bits_) throw std::out_of_range("Index out of range");

        int element = index / uint_size();
        int bit = index % uint_size();

        unsigned int temp_element = array_[element];
        temp_element = temp_element >> bit;

        unsigned int mul = 1;
        temp_element = temp_element & mul;
        return temp_element;
}

unsigned int Bitarray1D::operator [] (int index) const {
        if (index < 0 || index >= bits_) throw std::out_of_range("Index out of range");

        return test(index);
}

uint_size() is a function that returns the size of an unsigned int in bytes.

While this works well, i want to implement the assignment in array-like style as well, i.e.: bitarray[i] = 1;

In the current implementation this is not possible. In order to do so, I figured that [] operator in Bitarray should return a "Bit object" with the appropriate operators like below:

class Bit{
  private:
        unsigned int& element_;
        unsigned int index_;

    int getValue() const{
        // get value of bit
    }
public:
    Bit(unsigned int& element, unsigned int index): element_(element), index_(index){}

    Bit& operator [] (int value){
        return *this;
    }

    Bit& operator = (int value){
          //assign value to the bit
    }

    friend std::ostream& operator<<(std::ostream& os, const Bit& bit){
        os << bit.getValue();
        return os;
    }
};

This implementation works, but has two major problems:

Memory leak. In order for the [] operator in Bitarray to return a reference to a Bit object I have to return the following:

Bit& Bitarray1D::operator [] (int index) const {
     return *(new Bit(..., ... ));
}

I could change the array_ of the bitarray to hold an array of class Bit, but then the whole point of the Bitarray is lost, which is smaller memory footprint.


texts:
I currently have code that looks like this

private string _stringField;

protected string StringField
{
    get
    {
        if (_stringField == null)
            _stringField = GetStringField();
        return _stringField;
    }
}

ReSharper is suggesting I change the property to:

protected string StringField
{
    get
    {
        return _stringField ?? (_stringField = GetStringField());
    }
}

This isn't an idiom I've seen before and probably would have to think about the first time I saw it; is this something I should be concerned would confuse other people too?


texts: Creating an optimized, fully functional TextureManager in SDL

texts:
After I've discussed pointer semantics with Loki Astari previously, I finally managed to code the TextureManager class using auto_pointers. But the problem is that I need to pass an SDL_Renderer object to my class' constructor as an auto_ptr. But the object I want to pass is a raw pointer.

How should I do it? Also, I'm not so sure about the aout_pointers I've written. Can you help me, please?

TextureManager.h

#pragma once //using visual C++

#include <unordered_map>
#include "Texture.h"
#include <memory>

/**
    This class helps the user to manage large
    amount of texture at the same time (disposing them, setting
    their color, their renderer, ...). The dispose method of this class
    should be called before the end of the program (there will be no issues
    if it is not called : the destrctor of the TextureManager class will call
    the destructor of the @Texture class ! But it is better to call it, since
    it will release all ressources when you want !).This class contains a dynamic
    array, so the user can add @Texture pointers threw out the programs
    evolution.
*/

typedef std::unordered_map<int, Texture*> atlasType;//cannot use auto_ptr in STL container !

class TextureManager
{
public:
    TextureManager(std::auto_ptr<SDL_Renderer> pRenderer);
    ~TextureManager();

    void setRenderer(std::auto_ptr<SDL_Renderer> pRenderer);
    bool LoadFromFile(unsigned int ID, const char* fileName);

    bool unloadTexture(unsigned int ID);
    void dispose();

    Texture& getTexture(unsigned int ID);
    Texture getTextureCopy(unsigned int ID);

private:
    std::auto_ptr<SDL_Renderer> m_pRenderer;
    atlasType m_textureAtlas;
};

TextureManager.cpp

#include "TextureManager.h"

TextureManager::TextureManager(std::auto_ptr<SDL_Renderer> pRenderer)
    : m_pRenderer(pRenderer)
{}

TextureManager::~TextureManager(){
    dispose();
}

void TextureManager::dispose(){
    for (atlasType::iterator it = m_textureAtlas.begin(); it != m_textureAtlas.end(); ++it){
        delete (it->second);
    }
    m_textureAtlas.clear();
}

bool TextureManager::unloadTexture(unsigned int ID){
    Texture *pTempTexture = m_textureAtlas[ID];

    if (!pTempTexture)
        return false;

    delete pTempTexture;//dispose texture
    pTempTexture = nullptr;
    m_textureAtlas.erase(ID);

    return true;
}

Texture& TextureManager::getTexture(unsigned int ID){
    return *(m_textureAtlas[ID]);
}

Texture TextureManager::getTextureCopy(unsigned int ID){
    return *(m_textureAtlas[ID]);
}

bool TextureManager::LoadFromFile(unsigned int ID, const char* fileName){
    Texture *pTexture = m_textureAtlas[ID];

    if (pTexture == nullptr){
        pTexture = new Texture();
        pTexture->setRenderer(m_pRenderer.get());//Texture uses raw pointer;

        m_textureAtlas[ID] = pTexture;//will be deleted in dispose;
    }
    if (!pTexture->LoadFromFile(fileName))
        return false;

    return true;
}

void TextureManager::setRenderer(std::auto_ptr<SDL_Renderer> pRenderer){
    m_pRenderer = pRenderer;
}

Here's where I can not call the constructor (raw pointer <-> auto_ptr):

/* ......Declarations........... */

SDL_Renderer * m_pRenderer = nullptr;

/* etc..........*/

m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);

/*Trying to create TextureManager*/

m_textureManager = TextureManager(m_pRenderer);//fail to compile : is not of type auto_ptr<SDL_Renderer> ! what shall I do ?


texts: Remove duplicate elements from array along with element using Java 1.7

texts:
I need to write a method where a int[] will be supplied as an input and it should return an array, but with all of the numbers that occur more than n times removed entirely.

Input:

(int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5]

Output:

(int list) [1, 4]

These are the steps i have tried:

Copy the int array to ArrayList (inputList).
Create a LinkedHashset to find unique values
Iterate LH and find the collection frequency of ArrayList with iterator.

    int[] intArray = new int[0];
ArrayList<Integer> inputList = new ArrayList<Integer>(data.length);
        //System.out.println(Arrays.toString(data));
        for (int i = 0; i < data.length; i++){
            inputList.add(Integer.valueOf(data[i]));
        }

        LinkedHashSet<Integer> lhs = new LinkedHashSet<>(inputList);

        intArray = new int[lhs.size()];
        int i=0;
        int j=0;
        Iterator<Integer> itr = lhs.iterator();
        while(itr.hasNext()){
            Integer shiftNumber = itr.next();

            if(Collections.frequency(inputList, shiftNumber)==1) {
                intArray[i++] = shiftNumber.intValue();
                j++;
            }

        }
        intArray = Arrays.copyOf(intArray, j);
        return intArray;
    }
}

return intArray;

I am able to achieve the results with the above snippet.However, I need suggestions in reducing the piece of code and improving performance by using any algorithms or other collection objects.


texts: Combinations of size k from a list in OCaml

texts:
I wanted to write a small but non-trivial function in OCaml to test my understanding. I have only a basic understanding of the libraries, and no idea at all of what is considered good style. The function computes all combinations of size k from a list, where 0 <= k <= length lst.

Would someone mind commenting on

Whether the function is generally well written (have I covered all cases, are there opportunities for tail recursion that I've missed?)
Have I made good use of libraries (e.g. I defined is_empty and tails because I couldn't find them in the List module, but maybe they are somewhere else?)
Is the style okay, particularly the use of let statements and indentation?

The code is:

let rec tails = function
  | []          -> []
  | _ :: t as l -> l :: tails t

let is_empty = function
  | [] -> true
  | _  -> false

let rec combnk k lst =
  if k = 0 then [[]]
  else let f = function
    | []      -> [] (* I think this is unnecessary, but I get a pattern match warning o/w *)
    | x :: xs -> List.map (fun z -> x :: z) (combnk (k-1) xs)
  in if is_empty lst then []
     else List.concat (List.map f (tails lst))

Based on the excellent comments by amon (see below) I have written to what I think is the most readable version of this function, which is the one that inlines the definition of tails and gets rid of is_empty completely, but doesn't go all the way to removing the use of List.concat and List.map, because I believe in using library functions to simplify the code wherever possible.

In particular, the layout guidelines make the structure of the function much clearer, and I think that in this version it is obvious what algorithm is being used, whereas it is somewhat obfuscated in the original. Thanks, amos!

let rec combnk k lst =
  if k = 0 then
    [[]]
  else
    let rec inner = function
      | []      -> []
      | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs) :: inner xs in
    List.concat (inner lst)


texts:
I'm new to ReactJs and trying to figure out the preferred style. I also have tried it enough to realize that I'm not a fan of jsx and prefer how React looks when written in coffeescript.

This is a very simple control (eventually will be a series of controls). It contains a select element and a button. When a selection is made and the button is clicked it triggers some domain activity which does work in a separate area.

flatten = (selection) -> console.log "Do domain work to the", selection

ActionsDemo = React.createClass: render ->
    FlattenRacer @props

FlattenRacer = React.createClass render: ->
    flattenSelected = =>
        selector = @refs['character']
        if selector.selected()
            flatten selector.selected()
            selector.clear()

    R.div (className: 'action'),
        CharacterSelector (racers: @props.racers, ref: 'character')
        R.button (onClick: flattenSelected), "Flatten"

CharacterSelector = React.createClass
    selected: -> @getDOMNode().value
    clear: -> @getDOMNode().value = null
    render: ->
        R.select null,
            [R.option null, "-- Select --"].concat _.map @props.racers, (r) ->
                R.option (value: r), r

React.renderComponent (ActionsDemo racers: ['racer1', 'racer2', 'racer3']),
                      (document.querySelector '#racetrack-actions')

The _ functionality is via lodash

The above works and is similar to the approach in the ReactJs tutorial but I keep hearing that React is about "data-flow" and this doesn't really seem like...that.

I've done a lot of knockoutjs and doing things in this manner seems kind of like a step backwards. For example if I wanted to disable the button unless the selector has a valid selection there's no obvious way to do this. It also seems like the CharacterSelector should be in charge of when it gets cleared. Also the entire refs mechanism feels a bit like a hack. This feels like I should be using functional reactive programming somewhere but not quite sure where.

As a side note, is there a way I can just force my CharacterSelector instance to re-render instead of having to create a clear method?

How can I improve this?


texts: Optimally splitting a text into strings from a set

texts:
I am trying to write an algorithm that starts with a corpus of texts (e.g., a Wikipedia dump). It first builds an array of individual characters (e.g., "a", "b", "7", "0", ".", " ") and frequent substrings (e.g, " the ", "ly ", " un", "er", "some"). Then it splits up the text corpus into a sequence of those substrings.

I build the array as follows (not optimal but it's probably good enough):

from collections import defaultdict

corpus = [ ] # An array of strings, each string being a text
max_len = 5 # Longest sequence of characters to look for
strings = defaultdict(int)
for text in corpus:
    for n in range(max_len):
        for i in range(len(text)):
            if i+n < len(text):
                strings[text[i:i+n+1]] += 1

dict_size = 1000000 # Rough number of sequences to keep
min_count = sorted(strings.values(), reverse=True)[dict_size]
for key, count in strings.items():
    if count < min_count and len(key) > 1: # Keep frequent sequences and all individual chars
        del strings[key]

The part that seems trickiest is doing a good (or optimal) split of the texts. I assumed that longer substrings are less frequent and shorter substrings are less likely to collide, so my idea was to take a greedy approach: I run through the text sequentially once for each possible length in decreasing order. I use a linked list to keep track of the split out text:

class Token:
    def __init__(self, text, next=None):
        self._text = text
        self._next = next
        self._done = False

    @property
    def next(self):
        return self._next
    @next.setter
    def next(self, token):
        self._next = token

    @property
    def text(self):
        return self._text
    @text.setter
    def text(self, text):
        self._text = text

    @property
    def done(self):
        return self._done
    @done.setter
    def done(self, status):
        self._done = status

for text in corpus:
    head = Token(text) # Start the list with one token of the whole text
    for n in range(max_len, 0, -1): # Run through lengths in decreasing order
        token = head # Go back to the start for each run
        i = 0
        while True:
            if token.done or i+n > len(token.text): # If token is processed or end of token is reached
                if token.next:
                    token = token.next # Continue linked list
                    i = 0
                    continue
                else:
                    break
            if token.text[i:i+n] in strings:
                if i > 0: # Split out characters before match
                    token.next = Token(token.text[i:], token.next)
                    token.text = token.text[:i]
                    token = token.next
                token.done = True
                if len(token.text) > n: # Split out characters after match
                    token.next = Token(token.text[n:], token.next)
                    token.text = token.text[:n]
                    token = token.next
                    i = 0
            else:
                i += 1 # Run through characters in the token

This seems to work but I'm not sure how optimal it actually is, and I can't think of an algorithm that wouldn't run in exponential time. Initially I thought this may be a dynamic programming question but I don't think it works either because the character space is so sparse.


texts: Comparing rows of a matrix with some row vectors

texts:
I have run this program for five hours and it has not yet completed. I wonder if we can make changes to reduce the computation time.

I use several for loop and this greatly increases the computation time. my goal is to compare the contents of the rows of a matrix (4435 × 2000) with 6 row vectors (1 × 2000). The comparison is made on parts of 64 values.

for i=1:4435
    for j=70:2000
        L = A(i,j);
        j1=0;
        j2=0;
        j3=0;
        j4=0;
        j5=0;
        j6=0;
        for i1=70:2000
            if D1(B(v,1),i1)==L
                j1=i1;
                Break
            end
        end

        for i2=1:2000
            if A(B(v-1,1),i2)==L
                j2=i2;
                Break
            end
        end

        for i3=1:2000
            if A(B(v-2,1),i3)==L
                j3=i3;
                Break
            end
        end

        for i4=1:2000
            if A(C(mm,1),i4)==L
                j4=i4;
                Break
            end
        end

        for i5=1:2000
            if A(C(mm-1,1),i5)==L
                j5=i5;
                Break
            end
        end

        for i6=1:2000
            if A(C(mm-2,1),i6)==L
                j6=i6;
                Break
            end
        end

        if j1>64
           if A(i,j-63:j)==A(B(v,1),j1-63:j1)
              m_A1(i,j)=1;
           else
              m_A1(i,j)=0;
           end
        end

        if j2>64
           if A(i,j-63:j)==A(B(v-1,1),j2-63:j2)
              m_A2(i,j)=1;
           else
              m_A2(i,j)=0;
           end
        end

        if j3>64
           if A(i,j-63:j)==A(B(v-2,1),j3-63:j3)
              m_A3(i,j)=1;
           else
              m_A3(i,j)=0;
           end
        end

        if j4>64
           if A(i,j-63:j)==A(C(mm,1),j4-63:j4)
              m_A4(i,j)=1;
           else
              m_A4(i,j)=0;
           end
        end

         if j5>64
           if A(i,j-63:j)==A(C(mm-1,1),j5-63:j5)
              m_A5(i,j)=1;
           else
              m_A5(i,j)=0;
           end
         end

         if j6>64
           if A(i,j-63:j)==A(C(mm-2,1),j6-63:j6)
              m_A6(i,j)=1;
           else
              m_A6(i,j)=0;
           end
        end

    end
end


texts:
Below is a python script that I wrote to flash neopixel leds at a very fast rate using a raspberry pi0. The main while loops runs at a semi reasonable rate, although faster would be much better. In addition, the button thread slows down the script considerably.  Any ideas on how to make this run faster? While running, it uses 96% of my CPU already.

I am especially hoping for input on how to make this faster.

import time
import csv
from pprint import pprint
from neopixel import *
import RPi.GPIO as GPIO
import threading

B1 = 23
B2 = 24
B3 = 25
GPIO.setmode(GPIO.BCM)
GPIO.setup(B1, GPIO.IN)
GPIO.setup(B2, GPIO.IN)
GPIO.setup(B3, GPIO.IN)

numpats = 4
cpat = 0
DELAY = 0
shuffle = False

def ButtonThread():
    global cpat
    global DELAY
    global shuffle

    while True:
        if GPIO.input(B1):
            cpat = cpat + 1
            if cpat >= numpats:
                cpat = 0
            print(cpat)
            time.sleep(0.5)

        if GPIO.input(B2):
            DELAY = DELAY + .0001
            time.sleep(0.1)

            if DELAY > .05:
                DELAY = 0

        if GPIO.input(B3):
            shuffle = not shuffle
            print(shuffle)
            time.sleep(0.5)

LED_COUNT      = 300      # Number of LED pixels.
NUMPIX =  100
LED_PIN        = 18      # GPIO pin connected to the pixels (18 uses PWM!).
LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA        = 5       # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 25     # Set to 0 for darkest and 255 for brightest
LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53
LED_STRIP      = ws.WS2811_STRIP_GRB   # Strip type and colour ordering

#LOAD PATTERNS
text = []
pattern = []
with open('patterns.txt')as inputfile:
    for line in inputfile:
        text.append(line.strip().split(','))
    for p in text:
    pattern.append([])
        for d in p:
            pattern[cpat].append(int(float(d)))
    cpat = cpat + 1

cpat = 0
colors = []
r,g,b = 0.0,0.0,0.0
for p in pattern:
    cnt=0
    colors.append([])
        for x in p:
            if cnt%3 == 0:
            r = x
        elif cnt %3 == 1:
            g = x
        else :
            b = x
            colors[cpat].append(Color(r,g,b))
        cnt = cnt + 1
    cpat = cpat + 1

if __name__ == '__main__':
    cpat = 0
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
    strip.begin()

    buttThread = threading.Thread(target=ButtonThread, args=())
    buttThread.daemon = True
    buttThread.start()

    cpat = 0
    print(strip.numPixels())

    while True:
        cnt=0
        for x in colors[cpat]:
            led = cnt%(NUMPIX)
            strip.setPixelColor(led, x)
            strip.setPixelColor(NUMPIX + led, x)
            strip.setPixelColor(2*NUMPIX + led, x)
            cnt = cnt +1

            if led == NUMPIX-1:
                strip.show()
                cnt=0
                time.sleep(DELAY)


texts:
From Wikipedia:

  Insertion sort iterates, consuming one input element each repetition,
  and growing a sorted output list. Each iteration, insertion sort
  removes one element from the input data, finds the location it belongs
  within the sorted list, and inserts it there. It repeats until no
  input elements remain.

  Sorting is typically done in-place, by iterating up the array, growing
  the sorted list behind it. At each array-position, it checks the value
  there against the largest value in the sorted list (which happens to
  be next to it, in the previous array-position checked). If larger, it
  leaves the element in place and moves to the next. If smaller, it
  finds the correct position within the sorted list, shifts all the
  larger values up to make a space, and inserts into that correct
  position.

Just tried out my solution in C++:

#include <vector>

std::vector<int> ins_sort(std::vector<int> series)
{
    for(int i=1; i<series.size(); i++)
    {
        int key = series[i];
        for(int j=i-1; j>-1; j--)
        {
            if (key < series[j])
            {
                series[j+1] = series[j];
                series[j] = key;
            }
            else break;
        }
    }
    return series;
}


texts:
I've created a UDF some time ago and used it pretty often till now in different ways (but mainly to compare a "history" of data like having different filters at the same time). While there is no need to change anything at this state, I'd like get some suggestions of how to improve it without the loss of any functionality.

To make it short, it is a LOOKUP-function which goes for the xth match and returns a ref.

Normally there are comments, but I deleted them to test if it is still easy to get what it does. Also i like to have it in a way i don't need them.

Public Function VLOOKUPK(lookup_value As String, lookup_vector As Range, Optional result_vector As Range, _
                                  Optional count_num As Long = 1, Optional case_sens As Boolean) As Variant
  Application.Volatile

  Dim i(0 To 1) As Long, j As Long, lookup_vector_values As Variant
  VLOOKUPK = CVErr(2023)
  If count_num - 1 <> Abs(Round(count_num - 1)) Or (i(0) * i(1)) = 1 Then Exit Function

  Set lookup_vector = Intersect(lookup_vector.Parent.UsedRange, lookup_vector)
  If lookup_vector.Areas.Count > 1 Then Set lookup_vector = lookup_vector.Areas(1)
  i(0) = lookup_vector.Rows.Count
  i(1) = lookup_vector.Columns.Count

  If i(0) > 2 And i(1) > 2 Then Exit Function

  If result_vector Is Nothing Then
    If i(0) = 1 Or i(1) = 1 Then
      Set result_vector = lookup_vector

    ElseIf i(0) > 2 And i(1) = 2 Then
      Set result_vector = lookup_vector.Columns(2)
      Set lookup_vector = lookup_vector.Columns(1)

    ElseIf i(0) = 2 And i(1) > 2 Then
      Set result_vector = lookup_vector.Rows(2)
      Set lookup_vector = lookup_vector.Rows(1)

    Else
      Exit Function

    End If
  Else
    If result_vector.Columns.Count > 1 And result_vector.Rows.Count > 1 Then Exit Function
    Set result_vector = Intersect(result_vector.Parent.UsedRange, result_vector)

  End If

  If lookup_vector.Columns.Count > 1 And lookup_vector.Rows.Count > 1 Then Exit Function

  If Not case_sens Then lookup_value = LCase(lookup_value)
  If lookup_vector.Columns.Count > 1 Then j = 1
  lookup_vector_values = lookup_vector.Value
  i(0) = 1: i(1) = 1

  For i(j) = 1 To UBound(lookup_vector_values, j + 1)
    If lookup_value Like IIf(case_sens, lookup_vector_values(i(0), i(1)), LCase(lookup_vector_values(i(0), i(1)))) Then
      If count_num = 1 Then
        Set VLOOKUPK = result_vector.Cells(i(0), i(1))
        Exit Function

      Else
        count_num = count_num - 1

      End If
    End If
  Next
End Function

How to use it:

VLOOKUPK(lookup_value,lookup_vector,[result_vector],[count_num],[case_sens])

lookup_value (required)

The value to search for.
lookup_value can be used with wildcards like *.

lookup_vector (required)

The Range to look in.
It needs to contain only one row or column if the result_vector is submitted.
If no result_vector is set and the lookup_vector contains only 1 row/column, the result_vector will be set to the lookup_vector.
If no result_vector is set, and the lookup_vector contains 2 columns while holding more then 2 rows, the first column will be set as lookup_vector while the second column will become the result_vector. (and vice versa)

Having a range of 2x2 will result in an error.

result_vector (optional)

The range where the value to output is located.
Needs to contain only one row or column.

count_num (optional)

Indicates the kth match to work with.
if not submitted, the first occurrence will be submitted.

case_sens (optional)

if set to TRUE the search will be case sensitive.


texts:
I wrote (several months ago) a program that will take an input file, with a provided std::string, and append that to each individual line in the file. Looking at the code again, I am wondering about the performance of this program, possibly if the file is very large or any of the lines/input string is long.

#include <fstream>
#include <iostream>
#include <vector>

// argv[1] is input file name
// argv[2] is output file name
// argv[3] is string to add
int main(int argc, const char * argv[])
{
    if (argc != 4) {
        std::cout << "Needs input file and string to add" << std::endl;
        return EXIT_FAILURE;
    }
    std::ifstream in_file(argv[1]);
    std::string str;
    std::vector<std::string> vec, result_vec;
    while (std::getline(in_file, str)) {
        vec.push_back(str);
    }

    std::for_each(vec.begin(), vec.end(), [&](std::string str) {
        result_vec.push_back(str + argv[3]);
    });

    std::ofstream out_file(argv[2]);
    std::copy(result_vec.begin(), result_vec.end(), std::ostream_iterator<std::string>(out_file, "\n"));
}


texts:
I created a function that truncates an incomplete UTF-8 character at the end of std::string in C++.

C++'s Standard Library does not yet support character based substr on UTF-8 characters and does substr by number of bytes only.

Because of that, in the example below, substr causes a weird broken character to appear in the end.

std::string utfstr = "옷三옷白옷옷-어<어<어<어<-";
std::cout << utfstr.substr(0, 5) << std::endl;

It seems like my function is working, but, I would like to get some feedback on possible problems and improvements.

#include <string>
#include <iostream>
using namespace std;

ssize_t TrimEndUTF8(std::string& str) {
  // Scans backward from the end of string.
  const char* cptr = &str.back();
  int num = 1;
  int numBytesToTruncate = 0;

  for (int i = 0; 6 > i; ++i) {
    numBytesToTruncate += 1;
    if ((*cptr & 0x80) == 0x80) { // If char bit starts with 1xxxxxxx
      // It's a part of unicode character!
      // Find the first byte in the unicode character!

      //if ((*cptr & 0xFC) == 0xFC) { if (num == 6) { return 0; } break; }
      //if ((*cptr & 0xF8) == 0xF8) { if (num == 5) { return 0; } break; }

      // If char binary is 11110000, it means it's a 4 bytes long unicode.
      if ((*cptr & 0xF0) == 0xF0) { if (num == 4) { return 0; } break; }
      // If char binary is 11100000, it means it's a 3 bytes long unicode.
      if ((*cptr & 0xE0) == 0xE0) { if (num == 3) { return 0; } break; }
      if ((*cptr & 0xC0) == 0xC0) { if (num == 2) { return 0; } break; }

      num += 1;
    } else {
      // If char bit does not start with 1, nothing to truncate!
      return 0;
    }

    cptr -= 1;
  }
  str.resize(str.length() - numBytesToTruncate);
  return numBytesToTruncate;
}

int main() {
  for (int i = 1; 30 > i; ++i) {
    std::string utfStr = "안-녕<하>세d요e만f나g서반갑습니다";
    std::string substred = utfStr.substr(0, i);
    size_t trimmed = TrimEndUTF8(substred);
    cout << "Trimmed " << trimmed << " bytes" << endl;
    cout << substred << endl;
  }

  for (int i = 1; 30 > i; ++i) {
    std::string utfStr = "_____------";
    std::string substred = utfStr.substr(0, i);
    size_t trimmed = TrimEndUTF8(substred);
    cout << "Trimmed " << trimmed << " bytes" << endl;
    cout << substred << endl;
  }

  return 0;
}


texts: ASP.net service that sends email whenever an entity is updated

texts:
I have an ASP.net MVC5 project which involve different domain services, and one of it are EmailService which will send email if entity is updated.

public class Project {
    string ProjectType {get; set;}
    string Name {get; set;}
}

public interface IProjectService {
    event void EventHandler<ProjectEventArgs> Updated;
}

public interface IEmailLogRepository {
    void Insert(EmailLog obj);
}

public class EmailService {

    private readonly IEmailLogRepository _repos;

    public string SmtpServer {get;set;}
    public string SmtpPort {get;set;}
    public string SmtpSender {get;set;}
    public string SmtpUsername {get;set;}
    public string SmtpPassword {get;set;}
    ......

    public string TemplateASubjectFormat {get;set;}
    public string TemplateBSubjectFormat {get;set;}
    public string TemplateAContentFormat {get;set;}
    public string TemplateBContentFormat {get;set;}

    public EmailService(IProjectService service, IEmailLogRepository repos) {
        service.Updated += OnProjectUpdated;
        _repos = repos;
    }

    private void OnProjectUpdated(object sender, ProjectEventArgs args) {
        if (args.Entity.ProjectType == "A")  SendEmailWithTemplateA(args.Entity);
        if (args.Entity.ProjectType == "B")  SendEmailWithTemplateB(args.Entity);
    }

    private void SendEmailWithTemplateA(Project obj){
        MailMessage mail = new MailMessage();
        mail.Suject = string.Format(TemplateASubjectFormat, obj.Name);
        mail.Content = string.Format(TemplateAContentFormat, obj.Name);
        ......
        SendEmail(mail);
    }

    private void SendEmailWithTemplateB(Project obj){
        MailMessage mail = new MailMessage();
        mail.Suject = string.Format(TemplateBSubjectFormat, obj.Name);
        mail.Content = string.Format(TemplateBContentFormat, obj.Name);
        ......
        SendEmail(mail);
    }

    private void SendEmail(MailMessage mail){

        EmailLog log = new EmailLog();
        log.Email = mail.ToAdress;

        try{
            SmtpClient smtp = new SmtpClient();
            ........
            smtp.Send(mail);
            log.Status = "Success";
            _repos.Insert(log);
        }catch(Exception ex){
            log.Status = string.Format("Error: {0}", ex.Message);
            _repos.Insert(log);
        }
    }
}

public class ProjectController : Controller
{
    private readonly IProjectService _service;
    private readonly EmailService _emailService;

    public ProjectController(IDbConnection connection, IProjectService service, IEmailLogRepository emailRepos){
        _service = service;
        _emailService = new EmailService(_service, emailRepos);
        Dictionary<string, string> settings = Settings.Load(connection);
        _emailService.SmtpServer = settings["SmtpServer"];
        ........
        _emailService.TemplateASubjectFormat = settings["TemplateASubjectFormat"];
        _emailService.TemplateAContentFormat = settings["TemplateAContentFormat"];
        _emailService.TemplateBSubjectFormat = settings["TemplateBSubjectFormat"];
        _emailService.TemplateBContentFormat = settings["TemplateBContentFormat"];
        ........
    }
}

In the above code, the EmailService contains lots of settings like Smtp and template info for different project types, those settings are located in database currently (one settings table but it stored all settings for different services), and the service properties are assigned in ASP.net controller constructor.

This kind of setting properties assignment caused the constructor contains a lots of lines, some controller may require more than one service to work, each services in my projects are designed like this, and I feel it's not a good design, so may I check what's the best practice for assign settings value for setting assignment?


texts: Finding Repeat and missing numbers in an array

texts:
Problem Statement:

  You are given a read-only array of n integers from 1 to n. Each
  integer appears exactly once except A which appears twice and B which
  is missing.

  Return A and B.

  Example

Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4

I wrote the following code:

def repeated_number(number_array):

   pair_A_B = []

   n = len(number_array)

   for i in number_array:
      if(number_array.count(i)==2):
        pair_A_B.append(i)
        break

   sample = range(1,n+1)

   diff = list(set(sample)-set(number_array))

   pair_A_B.append(diff[0])

   return pair_A_B

sample_input = [3,1,2,3,5]

print(repeated_number(sample_input))

The code works fine for this problem on my laptop but when I try to submit it on a coding forum it says my code is not efficient. How can I make it efficient in terms of time?


texts:
I'm hoping to get some feedback on how to improve and optimise a program I wrote which takes three values as input (via the terminal) and uses them in the quadratic formula.

I'm aware this is mostly micro-optimisation, but any advice whatsoever would be much appreciated.

public class Quadratic_Equations {
    static Scanner sc = new Scanner (System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("Please enter a, b and c or enter -1 at any time to exit");
            double a = tryParse(sc.nextLine());
            a = checkIfValidNumber(a);
            if (a == -1)
                break;
            double b = tryParse(sc.nextLine());
            b = checkIfValidNumber(b);
            if (b == -1)
                break;
            double c = tryParse(sc.nextLine());
            c = checkIfValidNumber(c);
            if (c == -1)
                break;

            System.out.println(useQuadraticFormula(a, b, c));
            System.out.println();
        }
        sc.close();
    }

    private static double checkIfValidNumber(double number) {
        while (number == -1.0) {
            System.out.println("You didn't enter a valid number for a. Please try again.");
            number = tryParse(sc.nextLine());
        }
        return number;
    }

    public static Double tryParse(String text) {
        try {
            return new Double(text);
        } catch (NumberFormatException e) {
            return -1.0;
        }
    }

    public static String useQuadraticFormula(double a, double b, double c) {
        double result1;
        double result2;
        if (Math.pow(b, 2) - (4 * a * c) <= 0)
            return "These numbers do not compute - they produce an illegal result.";
        result1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
        result2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
        return String.valueOf(result1) + ", " + String.valueOf(result2);
    }
}

Among the things I really dislike are:

The static scanner object.
The three different checks for -1 being entered.
The quadratic formula method, which seems like it could be shortened.

I'm still working on this myself, but as I said any advice (including on naming conventions, code style etc.) would be appreciated.


texts: Validating that only certain values are unset

texts:
I am checking data output in some testing code, and only some fields can be None, but I think this can be better:

for key in data[0].keys():
        self.assertIn(key, data_model)
        if data[0][key] is None:
            self.assertTrue('rate' in key or 'percentage' in key or 'ratio' in key)
            continue
        self.assertIsInstance(data[0][key], data_model[key])

Mostly I don't like the ... or ... in the assertTrue


texts:
How does the following look for doing a string replace in C? Is this approach more common than allocating memory within the function and returning a new string pointer, or is the bring-your-own-buffer more common?
#include <stdio.h>
#include <string.h>

// return size of string, -1 if error such as buffer too small
// no memory is allocated here, buffer needs to be passed in
// Example: str_replace("Replace me", "me", "ME", buffer, 64);
// Returns: 10, buffer is now "Replace ME".
ssize_t
str_replace (
        const char* input_str,
        const char* from,
        const char* to,
        char* output_buffer,
        size_t max_size
) {
    size_t input_len = strlen(input_str);
    size_t from_size = strlen(from);
    size_t to_size = strlen(to);

    // get the output string length;
    size_t output_len = input_len;
    char* str_iterator = (char*) input_str;
    while ((str_iterator=strstr(str_iterator, from))) {
        output_len += (to_size - from_size);
        str_iterator += from_size;
    }
    if (output_len > max_size) {
        fprintf(stderr, "Buffer too small for output string.\n");
        return -1;
    }

    // reset str_iterator, make sure output_buffer is clear
    str_iterator = (char*) input_str;
    output_buffer[0] = '\0';

    // copy to output buffer
    // 1. Find the first match of `from` in `input_str` (advancing pointer on input_buffer along way)
    // 2. Copy the input_str up until the first match to output_buffer
    // 3. Copy `from` into output_buffer (advance string)
    // 4. Advance input_buffer pointer by size of `from`
    // 5. Repeat 2-5 until no more matches
    // 6. Copy remainder of input_str to output_buffer
    for (char* match; (match=strstr(str_iterator, from)); str_iterator+= (match-str_iterator) + from_size) {
        strncpy(output_buffer, str_iterator, match-str_iterator);
        output_buffer += (match-str_iterator);
        strncpy(output_buffer, to, to_size);
        output_buffer += to_size;
    }
    // copy remainder
    if (strlen(str_iterator))
        strcpy(output_buffer, str_iterator);

    return output_len;
}

int main(void)
{
    char buffer[50];
    ssize_t out_size = str_replace("Replace me", "me", "ME", buffer, 50);
    if (out_size == -1)
        printf("Nope!\n");
    else
        printf("Response size: %zu.\nResponse string: %s\n", out_size, buffer);
}

$ gcc logmain.c -o log; ./log
Response size: 10.
Response string: Replace ME

And another alternative:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// same as above but now with malloc
char* str_replace2(const char* input, const char* from, const char* to)
{
    size_t input_len = strlen(input);
    size_t from_size = strlen(from);
    size_t to_size = strlen(to);
    char* str_iterator = (char*) input;

    // get the output string length;
    size_t output_len = input_len;
    while ((str_iterator=strstr(str_iterator, from))) {
        output_len += (to_size - from_size);
        str_iterator += from_size;
    }
    char *str_out = malloc(output_len);
    char * const str_out_start = str_out; // const for emphasis it doesn't change
    if (!str_out) {
        fprintf(stderr, "Cannot malloc str of size %zu", output_len);
        return NULL;
    }

    // write to output str
    str_iterator = (char*) input;
    for (char* match; (match=strstr(str_iterator, from)); str_iterator+= (match-str_iterator) + from_size) {
        strncpy(str_out, str_iterator, match-str_iterator);
        str_out += (match-str_iterator);
        strncpy(str_out, to, to_size);
        str_out += to_size;
    }
    // copy remainder
    if (strlen(str_iterator))
        strcpy(str_out, str_iterator);

    return str_out_start;
}

Additionally, where are comments usually put in C? Above the function? In the function?


texts:
I have this simple implementation for array sorting:

#include <iostream>
#include <stdlib.h>

using namespace std;

// some magic for the sorter
int compare(const void *i, const void *j) {
    int a = *(int *) i, b = *(int *) j;
    return a < b ? -1 : a > b ? 1 : 0;
}

int main() {
    int arr[100], temp = 0, count = 0;

    // reads values into the array (assumed integers as input)
    while (cin >> arr[count++]);
    count--;

    // what sorts the array
    qsort(arr, count, sizeof(int), compare);

    // prints everything but duplicate elements
    for (int i = 0; i < count; i++) {
        bool match = false;
        for (int j = 0; j < i && !match; j++)
            if (arr[i] == arr[j])
                match = true;
        if (!match)
            cout << arr[i];
    }
}

How can it be improved? I'd like to also remove duplicate elements rather than just silently ignoring them too.


texts: Python password generator based on the current month

texts:
I am relatively new to python and am trying to teach myself.

I have created a python program that will take the current month's first three letters, and add one letter to the first, two to the second and three to the third.

It does this by converting the month's characters to an ASCII number, then adding X to that.

Please see the below code, which is what I wrote, and if you can, please provide me with feedback, how you feel it can be shortened etc.

import datetime

myDate = datetime.datetime.now()
month = myDate.strftime("%b")
month_list = list(month)
#below line is for testing other months or words. To use, please comment out the above three lines (myDate, month and month_list)
#month_list = ["Z", "z", "Z", ""]

letter_one = month_list[0]
letter_one_ascii = ord(letter_one)
letter_one_ascii += 1

if letter_one_ascii == 91 or letter_one_ascii == 123:
    letter_one_ascii = 65
else:
    letter_one = chr(letter_one_ascii)

letter_two = month_list[1]
letter_two_ascii = ord(letter_two)
letter_two_ascii += 2

if letter_two_ascii == 91 or letter_two_ascii == 123:
    letter_two_ascii = 65
elif letter_two_ascii == 92 or letter_two_ascii == 124:
    letter_two_ascii = 66
else:
    letter_two = chr(letter_two_ascii)

letter_three = month_list[2]
letter_three_ascii = ord(letter_three)
letter_three_ascii += 3

if letter_three_ascii == 91 or letter_three_ascii == 123:
    letter_three_ascii = 65
elif letter_three_ascii == 92 or letter_three_ascii == 124:
    letter_three_ascii = 66
elif letter_three_ascii == 93 or letter_three_ascii == 125:
    letter_three_ascii = 67
else:
    letter_three == chr(letter_three_ascii)

letter_one = chr(letter_one_ascii)
letter_two = chr(letter_two_ascii)
letter_three = chr(letter_three_ascii)

print "Your Password is: " + letter_one.upper(), letter_two.upper(), letter_three.upper()


texts:
I have implemented my own lock-free ringbuffer for multiple producers multiple consumers using vector. Can you guys help me review to see if there are any problems and ways to improve?

Explanation:
Each producer runs on its own thread and will use Push() to enter its item into the RingBuffer.

Each consumer runs on its own thread and has its own unique number. When consumer TryRead(), it will enter its unique number.

RingBuffer will keep track of the last position each consumer read in std::vector<long> mReadIdxVec

If mReadIdxVec[consumer unique number] >= mMaxReadIdx, TryRead() will return a nullptr.

Question:
Within Push() method, will it be a problem if multiple producers on different threads call this line mVector[index] = pMsg; at the same time?

Can this code be improved further? Any comments are welcomed!

RingBuffer.h

#ifndef __RING_BUFFER_H_
#define __RING_BUFFER_H_

#include <atomic>

class RingBuffer
{
    private:
        std::vector<Foo *> mVector;
        std::atomic<long> mWriteIdx{0}; //mWriteIdx will not exceed 2,000,000,000
        std::atomic<long> mMaxReadIdx{0}; //mMaxReadIdx will not exceed 2,000,000,000
        std::vector<long> mReadIdxVec;

    public:
        RingBuffer(int pNumOfConsumers);
        void Push(Foo *);
        Foo * TryRead(const int&);
};

#endif

RingBuffer.cc

#include "RingBuffer.h"
#define MAX_SIZE 1000

RingBuffer::RingBuffer(int pNumOfConsumers)
{
    mVector.reserve(MAX_SIZE);
    mVector.assign(MAX_SIZE, nullptr);
    mReadIdxVec.assign(pNumOfConsumers, 0);
}

void RingBuffer::Push(Foo * pMsg)
{
    if(!pMsg) return;
    long writeIdx = mWriteIdx++;
    long index = writeIdx % MAX_SIZE;
    if(writeIdx >= MAX_SIZE) delete mVector[index];
    mVector[index] = pMsg;
    mMaxReadIdx++;
}

Foo * RingBuffer::TryRead(const int& pConsumer)
{
    if(mReadIdxVec[pConsumer] >= mMaxReadIdx) return nullptr;
    long index =  mReadIdxVec[pConsumer] % MAX_SIZE;
    mReadIdxVec[pConsumer]++;
    return mVector[index];
}


texts: Python Text Analysis with TextBlob -- Reading lines from The Office TV Show

texts:
I have a Jupyter notebook that allows a user to type in a phrase and the program will 'guess' which Office character it resembles.

Here is a link to the github repo

I have the following littered throughout my code:

the_office_raw_script['polarity'] = the_office_raw_script['line_text'].apply(lambda x: TextBlob(x).sentiment.polarity)

the_office_raw_script['scores'] = the_office_raw_script['line_text'].apply(lambda x: analyser.polarity_scores(x))

and the following, which is the prediction part:

from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB

X_train, X_test, y_train, y_test = train_test_split(df_upsampled['line_text'], df_upsampled['speaker'], random_state = 0)

count_vect = CountVectorizer()

X_train_counts = count_vect.fit_transform(X_train)

tfidf_transformer = TfidfTransformer()

X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

clf = MultinomialNB().fit(X_train_tfidf, y_train)

I have some examples of output, which is AWESOME! (so happy i got this far)

print(clf.predict(count_vect.transform(["hard working beet farmer"])))

the above prints dwight

print(clf.predict(count_vect.transform(["that's what she said"])))

the above prints pam which is totally wrong because michael says 'that's what she said' over 15 times throughout the series.

Two Questions

How would I go above making my script into a function, would that be worth it?

How do I somewhat ~hardcode~ some inputs? If someone types in 'that's what she said' or a variation thereof I want it to always print michael?


texts: Generic Graph using Adjacency matrix - Java

texts:
The main purpose of representing Graph using adjacency matrix method is, to check the vertex and its neighbor's existence in constant time proportional to \$\mathcal{O}(n)\$.

In the various tutorials I have seen, Graphs contain only integer vertices and it becomes straight forward to represent them in a \$v \times v\$ integer 2D array to map the vertices.

In real world, we might have to store a custom type Object as the graph vertex. For this, I have created a Graph implementation with Adjacency matrix. Can you please let me know of any feedback / improvements?

//V - type of Object stored on graph vertices
public class GraphAM<V> {

    //Maps vertex with its adjacency matrix index. O(1) to retrieve index of a vertex
    private Map<V, Integer> vertices;
    //To get vertex using index at O(1) time
    private List<V> verticesLookup;

    //adjacency matrix
    private int[][] adj;

    private int index;

    public GraphAM(int numVertices) {
        adj = new int[numVertices][numVertices];
        index = 0;
        vertices = new HashMap<>();
        verticesLookup = new ArrayList<>();
    }

    public void addEdge(V from, V to) {
        addVertex(from);
        addVertex(to);

        int fromIndex = vertices.get(from);
        int toIndex = vertices.get(to);
        adj[fromIndex][toIndex] = 1;
    }

    private void addVertex(V v) {
        if(!vertices.containsKey(v)) {
            vertices.put(v, index);
            verticesLookup.add(index, v);
            index++;
        }
    }

    public void bfs(V start) {
        Queue<V> queue = new LinkedList<>();
        boolean[] visited = new boolean[vertices.size()];

        queue.add(start);
        int index = vertices.get(start);
        visited[index] = true;

        while(!queue.isEmpty()) {
            V v = queue.poll();
            System.out.print(v + " ");

            List<V> adjacentVertices = getAdjacentVertices(v);
            for(V a : adjacentVertices) {
                int adjInd = vertices.get(a);
                if(!visited[adjInd]) {
                    queue.add(a);
                    visited[adjInd] = true;
                }
            }

        }

    }

    public void dfs(V start) {
        boolean[] visited = new boolean[vertices.size()];
        dfs(start, visited);
    }

    private void dfs(V v, boolean[] visited) {
        System.out.print(v + " ");
        int index = vertices.get(v);
        visited[index] = true;

        List<V> adjacentVertices = getAdjacentVertices(v);
        for(V a : adjacentVertices) {
            int aIndex = vertices.get(a);
            if(!visited[aIndex]) {
                dfs(a, visited);
            }
        }
    }

    private List<V> getAdjacentVertices(V v) {
        int index = vertices.get(v);
        List<V> result = new ArrayList<>();
        for(int i=0; i<adj[index].length; i++) {
            if(adj[index][i] == 1) {
                result.add(verticesLookup.get(i));
            }
        }
        return result;
    }

}

Main class

class Main {

  public static void main(String[] args) {
            GraphAM<Integer> g = new GraphAM<>(4);

            g.addEdge(0, 1);
            g.addEdge(0, 2);
            g.addEdge(1, 2);
            g.addEdge(2, 0);
            g.addEdge(2, 3);
            g.addEdge(3, 3);

            System.out.println("Following is Breadth First Traversal "+
                    "(starting from vertex 2)");

            g.bfs(2);

            System.out.println("\nFollowing is Depth First Traversal "+
                    "(starting from vertex 2)");

            g = new GraphAM<>(4);

            g.addEdge(0, 1);
            g.addEdge(0, 2);
            g.addEdge(1, 2);
            g.addEdge(2, 0);
            g.addEdge(2, 3);
            g.addEdge(3, 3);

            g.dfs(2);
    }

}