texts: Check that file is fully downloaded by FTP

texts:
I have a task in which I want to handle error occurred in FTP downloading, For which I used the wget command to download a file via FTP and once the download is complete, compare downloaded filesize with FTP file size.

For that, I have the code as follows. My question: is this the correct method?

# fetch file details from the server and extract only number from the return value

FileSizeOnServer=curl --max-time 10 -u $FTP_USER:$FTP_PASSWORD --head $FTP_Path 2>&1 | grep "Content-Length:"
echo "Present File Size Details:" $FileSizeOnServer

FTP_File_Size=${FileSizeOnServer#*: }
echo "FTP_File_Size:$FTP_File_Size"

# fetch only size of local file size

DownloadedFileSize=`stat -c %s /home/pi/Desktop/ABCD.txt`
echo "DownloadedFileSize:$DownloadedFileSize"

# compare local and ftp file size

if [ "$DownloadedFileSize" -eq "$FTP_File_Size" ]; then
    echo "Size matched"
else
    echo "File Size doesn't match Start Downloading again"
fi


texts:
I am learning C on my own. This is not an assignment. I am trying to implement a function that takes a variable numbers of strings and concatenate them in a new string. It works, but I feel it is not elegant and would like to improve it.

For instance, I don't like how I am using n nor having to decrement argc twice, and I don't like having to use both length and total_length. On a more general level, I would like to know if there is a way to parse the variable arguments only once, although it does not seem to be possible unless allocating a fixed number of character or calling malloc multiple times (which I want to avoid).

/*
 * concat_strings - concatenate a variable number of strings
 * usage:
 * const *message = concat_strings(4, "Error running", argv[0], " - ", "Action create: needs name and email");
 */
char *concat_strings(int argc, ...)
{
    va_list ap;

    /* calculate the total number of characters in all the strings */
    va_start(ap, argc);
    int n = argc;
    int l = 0;
    while(n--)
        l += strlen(va_arg(ap, char*));
    va_end(ap);

    /* allocate memory */
    const size_t sizeof_char = sizeof(char);
    char *joined = malloc(sizeof_char * (l + 1));

    /* copy strings to destination */
    va_start(ap, argc);
    size_t length = 0;
    size_t total_length = 0;
    char *s;
    while(argc--) {
        s = va_arg(ap, char*);
        memcpy(joined + total_length, s, sizeof_char * (length = strlen(s)));
        total_length += length;
    }
    *(joined + total_length) = '\0';
    va_end(ap);

    return joined;
}


texts: Implementing delegate methods in an UIView class

texts:
This is my UIView class:

class OnboardingView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var skipButton: UIButton!
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!

    @IBOutlet weak var skipButtonTopConstraint: NSLayoutConstraint!
    @IBOutlet weak var nextButtonTopConstraint: NSLayoutConstraint!
    @IBOutlet weak var pageControlBottomConstraint: NSLayoutConstraint!

    fileprivate var stepviews: [OnboardingStepViewDelegate] = []

    weak var delegate: OnboardingDelegate?

    fileprivate var visibleIndex: Int = 0 {
        willSet {
                stepviews[visibleIndex].didDisappear()
        }
        didSet {
            stepviews[visibleIndex].didAppear()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        scrollView.contentSize = CGSize(width: scrollView.frame.width * CGFloat(stepviews.count), height:scrollView.frame.height)
        scrollView.delegate = self

        let firstPage = OnboardingIntroductionStepView.instanceFromNib(title: "Some title", message: "Message", imageName: "page1")

        stepviews = [firstPage, second, third]

        scrollView.contentSize = CGSize(width: 3 * scrollView.frame.size.width, height: scrollView.frame.size.height)

        scrollView.addSubview(firstPage)
    }
}

private extension OnboardingView {

    @IBAction func nextPage(_ sender: Any) {
        if pageControl.currentPage == stepviews.endIndex{
            return
        }

        let nextPageIndex = CGFloat(pageControl.currentPage + 1)

        UIView.animate(withDuration: 0.3) {
            self.scrollView.contentOffset.x = self.scrollView.frame.width * nextPageIndex
        }

        pageControl.currentPage += 1
    }

    @IBAction func skip(_ sender: Any) {
        pageControl.currentPage = stepviews.endIndex
        nextPage(self)
    }

    func moveControlConstraintsOffScreen () {
        pageControlBottomConstraint.constant = 40
        skipButtonTopConstraint.constant = -40
        nextButtonTopConstraint.constant = -40
    }

    func moveControlConstraintsOnScreen () {
        pageControlBottomConstraint.constant = 0
        skipButtonTopConstraint.constant = 16
        nextButtonTopConstraint.constant = 16
    }
}

extension OnboardingView: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.endEditing(true)

        visibleIndex = Int(scrollView.contentOffset.x / self.frame.width)

        delegate.doSomething()
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let pageNumber = Int(targetContentOffset.pointee.x / self.frame.width)
        pageControl.currentPage = pageNumber
    }
}

As you can see my view implements the UIScrollViewDelegate. However, this delegate method only handles view related logic. After this view logic is done it will notify the delegate (My ViewController) to do something. Using this approach my ViewController will only contain lifecycle updates (ViewDidLoad, ViewWillDissapear) etc. This makes sense in my opinion - This view class contains a scrollview that implements its logic to do view related tasks, once those tasks are done it tells the VC what to do based on delegation.

My question is: Is this bad and if so, why? Normally MVC is used as the design pattern, which results in "God" ViewControllers where ViewControllers also implement Datasource and Delegate. This results in a ViewController that handles controller logic AND view logic, making the Controller AND View less reusable.


texts: Compute mean, variance and standard deviation of CSV number file

texts:
I've written my first C++ application this week and I wanted to see if there's anything that aren't up to standards or better ways to do what I'm currently doing.

For the goal of the exercise, let's assume I can't use any other mathematical function other than the square root.

The application reads a file where numbers are on separate lines and computes the mean, variance and standard deviation of all the numbers. Afterwards I print the whole numbers list and the stats that were computed.

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#import <cmath>

using namespace std;

std::vector<int> readFile(const std::string &filePath) {
    ifstream in_file;
    in_file.open(filePath);
    std::vector<int> numbers;

    std::string line;

    while(std::getline(in_file,line,'\r')){
        numbers.push_back(std::stoi(line));
    }

    return numbers;
}

float computeMean(std::vector<int> numbers)
{
    if(numbers.empty()) return 0;

    float total = 0;
    for (int number : numbers) {
        total += number;
    }

    return (total / numbers.size());
}

float computeVariance(float mean, std::vector<int> numbers)
{
    float result = 0;
    for(int number : numbers)
    {
        result += (number - mean)*(number - mean);
    }

    return result / (numbers.size() - 1);
}

int main() {
    std::cout << "Please enter the file path :" << std::endl;
    std::string filePath;
    std::cin >> filePath;
    std::vector<int> numbers = readFile(filePath);
    float mean = computeMean(numbers);
    float variance = computeVariance(mean, numbers);
    float standardDeviation = sqrt(variance);

    std::cout << std::to_string(numbers.size()) + " numbers : ";
    std::string data;
    for(int number : numbers) {
        data += std::to_string(number) + ", ";
    }
    data = data.substr(0, data.length()-2);
    std::cout << data << std::endl;

    std::cout << "Mean : " << std::to_string(mean) << std::endl;
    std::cout << "Variance : " << std::to_string(variance) << std::endl;
    std::cout << "Standard Deviation : " << std::to_string(standardDeviation) << std::endl;
    return 0;
}


texts:
I am currently learning Graph algorithms by solving questions on online judges.  The below code is for implementing Topological sort, using recursive DFS.  Also, it is my first time with C++ STL. Kindly review my working code below and provide me with feedback.  The exact question for the below code is here.

#include<cstdio>
#include<set>
#include<list>
#include<stack>
#include<algorithm>
#include<vector>
#include<utility>
#include<functional>

struct node
{
    int d, f, value;

    bool operator< (const node &rhs) const
    {
        if(f<=rhs.f && f>=rhs.f)
            return value<rhs.value;
        else
            return f<rhs.f;
    }
};

std::vector< std::pair<node, node> > Edges;
std::set<node> s;
bool *visited;
int N, myTime=0,i=0;
node node1, node2;
void dfsVisit(node);

void dfs()
{
    for(std::vector< std::pair<node, node> >::iterator it=Edges.begin(); it!=Edges.end(); it++)
        if(it->first.value<N)
            if(!visited[it->first.value])
                dfsVisit(it->first);
}

void dfsVisit(node n)
{
    myTime++;                           //increment myTime
    n.d=myTime;                         //set the discovery time for node n

    if(n.value<N)
        if(visited[n.value])
            return;

    for(std::vector< std::pair<node,node> >::iterator it=Edges.begin(); it!=Edges.end(); ++it)
    {
        if(it->first.value==n.value && !visited[it->second.value])
        {
            dfsVisit(it->second);
        }
    }

    visited[n.value]=true;
    myTime++;
    n.f=myTime;

    //printf("The discovery and finishing times of %d are: %d, %d\n",n.value+1,n.d,n.f);
    //printf("Inserting %d into the set.\n",n.value+1);
    s.insert(n);
}

int main()
{
    int M, firstOfRule, secondOfRule, data, i;
    scanf("%d""%d",&N,&M);
    visited=new bool[N];

    for(i=0;i<N;i++)
        visited[i]=false;

    while(M--)
    {
        scanf("%d",&firstOfRule);
        scanf("%d",&secondOfRule);

        while(secondOfRule--)
        {
            scanf("%d",&data);
            node1.value=firstOfRule-1;
            node2.value=data-1;
            Edges.push_back(std::make_pair(node1,node2));
            printf("Connected %d and %d\n",node1.value+1,node2.value+1);
        }
    }

    dfs();

    for(std::set<node>::const_iterator it=s.begin(); it!=s.end(); it++)
        printf("%d ",it->value+1);

    return 0;
}

Sample input would be as follows:

  5 4
  3 2 1 5
  2 2 5 3
  4 1 3
  5 1 1

And the expected output is:

  1 5 3 2 4


texts: Formatting the Lengthy Parameters in a better way

texts:
Should I have made a line break convert_to_quick_mode( and from_exported_cdf,

        convert_to_quick_mode(
          from_exported_cdf,

code:

class QuickModeConverter(object):
    def run(self,
            from_exported_cdf,
            from_exported_msword,
            to_export_quick_mode_cdf,
            to_export_quick_mode_msword
            ):

        convert_to_quick_mode(
          from_exported_cdf,
          from_exported_msword,
          to_export_quick_mode_cdf,
          to_export_quick_mode_msword
        )
        pass


texts: jQueryTools plugin custom effect for caching ctabs

texts:
This is a custom effect for jQuery tools that enable caching for ajaxed tabs.
Please advice on anything that I can improve. Note that I'm not sure where to put the loading indicator, so, at least have a look at that.

$.tools.tabs.addEffect("ajax_cache", function(tabIndex, done) {
    //check if content already loaded
    //if yes, display it, and hide the rest
    //if no, send ajax request

    var panes_cont = this.getPanes().eq(0);
    var dest_pane = panes_cont.find("#tabindex_"+tabIndex);
    if(dest_pane.length > 0){
        panes_cont.children().hide();
        dest_pane.show();
    } else {
        panes_cont.children().hide();
        panes_cont.append("<img id='tab_loading' src='/graphics/loading.gif' />");

        var new_pane = $('<div>').attr('id', 'tabindex_'+tabIndex).load(this.getTabs().eq(tabIndex).attr("href"),
        function(){
            panes_cont.find("#tab_loading").remove();
            panes_cont.append(new_pane.show());
        });

    }

    done.call();
});


texts:
I am trying to create a web crawler for student research. I have already finish it, but I would like to tell me if the way I use is the best one. (probably it isn't :p)

The crawler is for the cnn site and the only thing I want to get, is the text of the news.

Here is an example link: link

Here is my code:

def cnn_crawler(link):
    req = urllib2.Request(link, headers={'User-Agent' : "Magic Browser"})
    usock = urllib2.urlopen(req)
    encoding = usock.headers.getparam('charset')
    page = usock.read().decode(encoding)
    usock.close()

    soup = BeautifulSoup(page)
    div = soup.find('div', attrs={'class': 'cnn_strycntntlft'})
    text = div.find_all('p')
    text.remove(soup.find('p', attrs={'class': 'cnn_strycbftrtxt'}))
    final = ""
    for entry in text:
            final = final + entry.get_text() + " "
    return final


texts: Sending email notifications, each to a different set of subscribers

texts:
Here is a code which sends email notification on new comments.

<?php

namespace Rib\Src\Apps\ContentNotification\ContentNotificationControllers;

use Rib\Src\Apps\ContentNotification\Email\NewContentNotificationEmail;
use Rib\Src\Services\DbSql;
use Rib\Src\Services\Email;

class JobSendNotificationsCron
{
    public function sendEmails()
    {
        $db = ( new DbSql() )->db()->getConnection();

        # Collect jobs to process
        $jobsToProcess = $db->table( 'content_notifications_jobs' )
                            ->where( 'status', '=', 'active' )
                            ->orderBy( 'last_mailing_time', 'asc' )
                            ->limit( 5 )
                            ->get()->toArray() ?? null;

        # Treat each job indivicually....
        foreach ( $jobsToProcess as $job ) {

            # Get all users that subscribed to be notified about new content in a particular job
            $usersToNotify = $db->table( 'content_notifications_subscribers' )
                                ->where( 'content_id', '=', $job->content_id )
                                ->get()->toArray() ?? null;

            # ... and send notification to each user subscribed to the job
            foreach ( $usersToNotify as $user ) {

                # Send email confirmation email
                Email::getMailer()->send( NewContentNotificationEmail::setContent( $job, $user ) );
            }

            # Update job table. Set job to inactive so it is not treated if no new answer was posted.
            # And set last_mailing_time to also skip jobs that had a mailing before delay was expired.
            $db->table( 'content_notifications_jobs' )->update(
                [
                    'status'            => 'inactive',
                    'last_mailing_time' => time()
                ]
            );
        }
    }
}

I don't like this code because there are sql calls in loop.
I'm thinking of refactoring this code. What would be the best way to refactor it by moving the sql out of the loop ?


texts:
I'm curious if there is a way to slim down this code either with SQL or with C#.

-- VARS
declare @iagent_id int
declare @quarter int
declare @prev_quarter_1 int
declare @prev_quarter_2 int
declare @prev_quarter_3 int
declare @year int
declare @prev_quarter_year_1 int
declare @prev_quarter_year_2 int
declare @prev_quarter_year_3 int

set @quarter = datepart(QQ, getdate()) - 1
set @year = datepart(year, getdate())
set @prev_quarter_year_1 = @year
set @prev_quarter_year_2 = @year
set @prev_quarter_year_3 = @year

if @quarter = 0
    begin
        set @quarter = 4
        set @year = @year - 1
        set @prev_quarter_1 = 3
        set @prev_quarter_year_1 = @year
        set @prev_quarter_2 = 2
        set @prev_quarter_year_2 = @year
        set @prev_quarter_3 = 1
        set @prev_quarter_year_3 = @year
    end
else
    begin
        if @quarter = 3
            begin
                set @prev_quarter_1 = 2
                set @prev_quarter_2 = 1
                set @prev_quarter_3 = 4
                set @prev_quarter_year_3 = @year - 1
            end
        else
            begin
                if @quarter = 2
                    begin
                        set @prev_quarter_1 = 1
                        set @prev_quarter_2 = 4
                        set @prev_quarter_year_2 = @year - 1
                        set @prev_quarter_3 = 3
                        set @prev_quarter_year_3 = @year - 1
                    end
                else
                    begin
                        if @quarter = 1
                            begin
                                set @prev_quarter_1 = 4
                                set @prev_quarter_year_1 = @year - 1
                                set @prev_quarter_2 = 3
                                set @prev_quarter_year_2 = @year - 1
                                set @prev_quarter_3 = 2
                                set @prev_quarter_year_3 = @year - 1
                            end
                    end
            end
    end

select @quarter as 'Quarter', @year as 'Year', @prev_quarter_1 as 'pq1', @prev_quarter_year_1 as 'pqy1', @prev_quarter_2 as 'pq2', @prev_quarter_year_2 as 'pqy2', @prev_quarter_3 as 'pq3', @prev_quarter_year_3 as 'pqy3'


texts: Inserting new rows into an existing table

texts:
I want to insert about 10000 new rows into an existing table which already contains 10000 rows. I need to get the insertid for the query and to use that id in another function inside the loop.

foreach($values as $val){
   $sql = "INSERT INTO wp_posts (`post_author`, `post_date`, `post_content`, `post_title`, `post_excerpt`, `post_status`,`post_modified`,`post_type`)
   VALUES('".$val[author]."',NOW(),'".$val[content]."','".$val[title]."','".$val[excerpt]."','published',NOW(),'post')";
   $result = mysql_query($sql);
   $insertid = mysql_insert_id();
   add_post_meta($insertid, $val[metakey], $val[metaval], true );
}

I am fetching the values for the $values array from a CSV file. As of now, I can insert only 20 new rows per 3 minutes. Is there any way to speed up this insertion?


texts:
I'm using Rails with MongoDB for database. In my apps I have 1 action for displaying list of users. User has name, image, score and is_online attributes. The list of users is displayed after ordering with multiple fields (score and is_online) and paging them.

I should now get all users and order by is_online and score and then paging them:

User.where(role_id: Core::Role.where(name: 'member').first.id).order_by([:is_online, :desc], [:score, :desc]).page(params[:page]).per(10)

The problem are:

I think using pagination will ruin the list of users like a duplicate user in some page if the status is online or the score is changed.
If I remove pagination it will overload.

Should I using cache system like redis or else?


texts: Printing the last two digits of an exponential calculation

texts:
I am trying to create a program where a user inputs two numbers - a base and an exponent, while exponent is a binary number. Then prints out the last two digits of the result. My code is working well, but according to the time execution it is not the fastest way to do it. I read a little about using Horner's method, is there a way to use it here? If so, how?

base = int(input())
exponent = int(input())

def binaryToDec(binary):
    decimal, i = 0, 0
    while(binary != 0):
        dec = binary % 10
        decimal = decimal + dec * pow(2, i)
        binary = binary//10
        i += 1
    return decimal
exponent = binaryToDec(exponent)
result = base ** exponent
result = abs(result)%100
print(result)

For example, the output of 3 and 1010 should be 49.

Another example:

Input:

111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111111111111111111

Output:

31

I expect the program to work faster in doing so, how can I do this?


texts:
I'm clearing all the controls on a windows form with the following

form.Controls.Cast<dynamic>().ToList().ForEach(c =>
{
      switch (c)
      {
          case CheckBox t when c is CheckBox:
              c.Checked = false;
              break;
          case System.Windows.Forms.ComboBox t when c is System.Windows.Forms.ComboBox:
              c.Items.Clear();
              break;
          case CheckEdit t when c is CheckEdit:
              c.Checked = false;
              break;
          default:
              c.Text = "";
              break;
      }
});

I have to use dynamic because if I dont, I wont get the options for Checked and I also wont be able to clear any items in a combobox or list for that matter. Is there a neater way of achieving this? I'm using c# 7.3 which allows me to use the when keyword, I wasn't able to find how to do this with anything under 7.0, If there is something for under 7.0, what would it be?


texts:
Definition of Happy numbers taken from Wikipedia.

  A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers)

  Example: 19 is happy, as the associated sequence is

  1*1 + 9*9 = 82,
  8*8 + 2*2 = 68,
  6*6 + 8*8 = 100,
  1*1 + 0*0 + 0*0 = 1.

import scala.collection.mutable.Set

object HappyNumber extends App {

  def findSquareSum(n: Int): Int =
    n.toString.foldLeft(0) { (product, num) => product + num.asDigit * num.asDigit }

  val visited = Set[Int]()

  def isHappyNumber(n: Int): Boolean = {
    n match {
      case 1 => true
      case _  =>
        if (visited contains n) false
        else {
          visited += n
          if (isHappyNumber(findSquareSum(n))) { visited -= n; true} else false
        }
    }
  }

  (1 to 247) foreach { num => if(isHappyNumber(num)) println(num) }
}


texts: Better QOpenGLWidget by delaying GL code to initializeGL with lambda functions

texts:
When I am writing OpenGL applications with the QOpenGLWidget class, deciding what code goes into the initializeGL function has always been tricky. One example is when I have a setter that requires an initialized OpenGL context, I have to make sure the OpenGL context is initialized before calling the setter, which is a huge pain.

The following snippet allows me to put GL functions anywhere in the class without worrying whether the OpenGL context is initialized. This is done by wrapping the GL functions with the delayForInit function. It checks whether the OpenGL context is already initialized. If it is, then run the GL functions immediately. If not, then delay the GL functions until initializeGL is called.

A simple usage example is shown at the bottom.

#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H

#include <QOpenGLWidget>
#include <functional>

/**
 * @brief The OpenGLWidget class
 */
class OpenGLWidget : public QOpenGLWidget {
    Q_OBJECT
public:
    explicit OpenGLWidget(QWidget* parent = 0)
      : QOpenGLWidget(parent)
      , _isInitialized(false) {}

protected:
    virtual void initializeGL() override {
        for (auto& initFunc : _initFuncs)
            initFunc();
        _initFuncs.clear();
        _isInitialized = true;
    }
    void delayForInit(std::function<void()> func) {
        if (_isInitialized) {
            makeCurrent();
            func();
            doneCurrent();
        } else
            _initFuncs.push_back(func);
    }

private:
    bool _isInitialized;
    std::vector<std::function<void()>> _initFuncs;
};

#endif // OPENGLWIDGET_H

// usage example
class SomeWidget : public OpenGLWidget {
    Q_OBJECT
public:
    SomeWidget() {
        delayForInit([this]() {
            glClearColor(0.f, 0.f, 0.f, 0.f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        });
    }
};


texts:
What is the difference between this two way and Which one is best? What do you suggest?

1.
Use of query (db) directly in CI_Controller. as:

$id = $this->input->post('id');
$query = $this->db->get_where('table1', array('id' => $id))->row();
         $this->db->get_where('table2', array('idre' => $query->idre));

Or

2.
Use of query (db) in CI_Model and call it in CI_Controller. as:

CI_Model:

function GetWhere($table,$where){
    return $this->db->get_where($table, $where);
}

CI_Controller:

$id = $this->input->post('id');
$query = $this->model_name->GetWhere('table1', array('id' => $id))->row();
         $this->model_name->GetWhere('table2', array('idre' => $query->idre));

UPDATE:

3.
I use the following code true in model as mvc?

$id = $this->input->post('checked');
        foreach ($id as $val) {
            $query_check = $this->db->get_where(table3, array('id'=>$val));
            $row = $query_check->row();
            if($query_check->num_rows() > 0 || $row->id != $this->session->userdata('id')){
                foreach ($query_check->result() as $value) {
                    $id_relation = $value->id_relation;
                    $this->db->where('idre', $idre)->delete(array(table3, 'table4'));
                }
            }
        }

Whether this is a good example of mvc? How can fix 2 example above for good mvc?


texts:
Using DataTables (Table plug-in for jQuery) with server-side processing, I had to create filtering for my data with good performance. However, in my opinion it's kinda ugly, especially the part of (.Where(...)), where I have to manually compare each property with the search variable. Is it possible to make it better?

using System.Linq.Dynamic; // because of special .OrderBy

public class SomeRepository
{
    public DataTableDTO GetAllFromBase(int start, int length, string sortColumn, string sortColumnDir, string search)
    {
        var dataFiltered = db.User
            .AsNoTracking()
            .Select(x => new { x.Id, x.FirstName, x.LastName, x.Description})
            .OrderBy(sortColumn + " " + sortColumnDir)
            .Where(search.Length > 0, x => x.Id.ToString().Contains(search.ToLower())
                                        || x.FirstName.ToLower().Contains(search.ToLower())
                                        || x.LastName.ToLower().Contains(search.ToLower())
                                        || x.Description.ToLower().Contains(search.ToLower()));

        var recordsFiltered = dataFiltered.Count();
        var recordsTotal = db.User.Count();

        var dataToShow = dataFiltered
            .Skip(start)
            .Take(length)
            .ToList();

        var dataForTable = new DataTableDTO
        {
            Data = dataToShow,
            RecordsTotal = recordsTotal,
            RecordsFiltered = recordsFiltered
        };

        return dataForTable;
    }
}

public static class LinqExtensions
{
    public static IQueryable<T> Where<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> whereClause)
    {
        if (condition)
        {
            return query.Where(whereClause);
        }
        return query;
    }
}


texts:
Here's a bit of one of my web forms which is reached by clicking on a link in a calendar.  Based on what you click, you end up at this page with a different QueryString.  Based on that QueryString, we hide/show and enable/disable controls related to actions associated with the QueryString, as well as the role of user.

We have three different types of events:

VacationDays (days where people took paid vacation)
VacationDaysUnpaid (days where people took unpaid vacation)
CalendarEvents (everything else such as meetings and client visits)

Here's a slimmed down version of how the page is prepared:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InitializePage();
    }
}

private void InitializePage()
{
    CheckRoles();

    if (!String.IsNullOrEmpty(Request.QueryString["CalendarEventID"]))
    {
        if (!HttpContext.Current.User.IsInRole("Guest"))
        {
            //if this is just a regular calendar event, allow non-guests to edit
            btnedit.Enabled = true;
            btndelete.Visible = false;
        }
    }
    if (!String.IsNullOrEmpty(Request.QueryString["VacationDayID"]))
    {
        if (!HttpContext.Current.User.IsInRole("Guest"))
        {
            //for vacation days, edits are not allowed, but the ability to delete is
            btnedit.Visible = false;
            btndelete.Enabled = true;
            btndelete.Visible = true;
        }
    }
    if (!String.IsNullOrEmpty(Request.QueryString["VacationDayUnpaidID"]))
    {
        //unpaid vacation days can only be deleted by administrators
        if (HttpContext.Current.User.Identity.Name.ToString().ToLower() == "administrator")
        {
            btndelete.Visible = true;
        }
        else
        {
            btndelete.Visible = false;
        }
    }
}

private void CheckRoles()
{
    if (HttpContext.Current.User.IsInRole("Guest"))
    {
        //disable all write controls if guest
        btnedit.Visible = false;
        btndelete.Visible = false;
        btnsave.Visible = false;
    }
}

It's jumbled, it's confusing, and it's difficult to maintain.  Is there any kind of common design or plan of attack for doing what I'm trying to do here?  I mean this works, I can work with it, I guess, but I really feel like there must just be some technique that I don't know about which will help improve this into something much easier and manageable.

One idea that I'm considering, and that I know will work, is to separate the code related to the different types of events into separate files as "partial"

That way in my InitializePage() method, for each type of QueryString, I'll have code that says like EnableCalendarEventMode(), which would be located in the partial class and would contain all the code related to calendar events.  This idea will make it easier to manage for me personally, but it still doesn't change the code, it just moves it around.


texts:
I want to have a thin wrapper (low overhead) around c-style string. Also, with some additional features like == and < operators for map indexing. I have come up with the following class.

Can somebody comment on it? From what I've gathered this class would take only as much memory as a pointer, so much less than std::string.

I also heard that this class has more overhead (execution-wise) than std::string and indeed that is the case for the constructor (char *), copy constructor and move constructor. Can somebody explain why?

inline char * dupStr(const char * s){
    if(!s){return nullptr;}
    size_t l = strlen(s) + 1;
    char * d = new char[l];
    memcpy(d,s,l);
    return d;
}

class CString_{
    private:
        const char *s_;

    public:
        CString_(const char *s):s_(dupStr(s)){}
        CString_(const std::string &s):CString_(s.c_str()){}
        CString_(const CString_ &that):s_(dupStr(that.s_)){}
        CString_(CString_ &&that):s_(that.s_){
            that.s_ = nullptr;
        }

        CString_ & operator= (const CString_ & that) = delete;
        CString_ & operator= (CString_ && that) = delete;

        ~CString_(){ delete[] s_;}

        const char * get() const {return s_;}

        bool operator<(const CString_ &that) const{
            return strcmp(s_,that.s_) < 0;
        }

        bool operator==(const CString_ &that) const{
            return strcmp(s_,that.s_) == 0;
        }
};


texts:
I know there are many posts about different plugin or hook systems, but I would like to know what you think about my simple system.

Main index.php:

<?php
class mainClass {
    public static $content;
    public static $added = [];
    public static function page() {
        self::$content = 'Init content';
    }
}
mainClass::page();

foreach(glob(__DIR__ . '/plugins/*', GLOB_ONLYDIR) as $plugin) {
    if(file_exists($plugin . '/' . basename($plugin) . '.php')) {
        spl_autoload_register(function($plugin){
            include 'plugins/'.$plugin . '/' . basename($plugin) . '.php';
        });
        $pluginClass = basename($plugin);
        $pluginClass::page();
    }
}

require_once __DIR__ . '/tmpldir/maintemplate.php';
?>

Example of plugins/myplugin/myplugin.php to be implemented:

<?php
class myplugin extends mainClass {
    public static function page() {
        mainClass::$content = 'Content overrided by plugin';
        mainClass::$added['added_by_plugin'] = 'Something';
    }
}
?>

And it's enough to paste in the template:

<?=mainClass::$content?>
<?=mainClass::$added['added_by_plugin']?>

I saw the comments in this link about "design flaws" of dynamical class extending, but I don't understand why such a way is wrong. Could someone explain?

Is this the simplest plugin system with autoloading? If not, why?


texts:
The reason I created this is because the Material UI way of doing a simple 'menu that opens below the button' is convoluted as hell (see the 'toggle menu grow' example, and check the code out. I've basically copied the code for that, and put it in one nice wrapper.

Codepen

Here's the usage of the component:

<NavDropdownMenu
  buttonProps={{
    variant: "contained",
    color: "secondary"
  }}
  buttonChildren={"foo bar"}
>
  <MenuItem onClick={this.handleA}>Profile</MenuItem>
  <MenuItem onClick={this.handleB}>My account</MenuItem>
  <MenuItem>Logout</MenuItem>
</NavDropdownMenu>

Notes:

We can pass through whatever material props to the button.
We can put whatever content we like inside the button. (e.g. icons, avatars).
We put whatever we like as menu items, and bind our own onclick events to them.

Under the hood, in order to both trigger the close menu functionality, as well as allow the user to bind their own click events to the menu items, I have this code that uses React.cloneElement:

   <MenuList>
    {children.map((child, i) => {
      return React.cloneElement(child, {
        ...child.props,
        ...{
          onClick: this.generateOnClick(child.props.onClick),
          key: `${menuId}${i}`
        }
      });
    })}
  </MenuList>

And that function:

  generateOnClick = fn => {
    if (fn)
      return () => {
        fn();
        this.handleMenuClose();
      };
    else {
      return this.handleMenuClose;
    }
  };

Now, I haven't put in PropTypes; I have to confess I'm not in the habit of using them. And there's probably some more extensibility I could add - (e.g. configuring the placement of the menu).

But other than that, are there glaring issue with this code that make it a bad idea?


texts:
I have been trying to wrap my head around MVVM for the last week or more and still struggling a bit. I have watched Jason Dolingers MVVM video and gone through Reed Copsey lessons and still find myself wondering if i am doing this right...   I found both sources very interesting yet a bit different on the approach.  If anyone has any other links, I would be interested as I would really like to learn this.

What is the best practice for the model to alert the viewmodel the something has happened?  As you will see in the code below, I created a very simple clock application.  I am using an event in my model but am not sure if this is the best way to handle this.  The output of the program is as expected, however I'm more interested in if I'm actually using the pattern correctly.  Any thoughts comments etc would be appreciated.

My model

using System;
using System.Threading;

namespace Clock
{
    public class ClockModel
    {
        private const int TIMER_INTERVAL = 50;

        private DateTime _time;

        public event Action<DateTime> TimeArrived;

        public ClockModel()
        {
            Thread thread = new Thread(new ThreadStart(GenerateTimes));
            thread.IsBackground = true;
            thread.Priority = ThreadPriority.Normal;
            thread.Start();
        }

        public DateTime DateTime
        {
            get
            {
                return _time;
            }
            set
            {
                this._time = value;
                if (TimeArrived != null)
                {
                    TimeArrived(DateTime);
                }
            }
        }

        private void GenerateTimes()
        {
            while (true)
            {
                DateTime = DateTime.Now;
                Thread.Sleep(TIMER_INTERVAL);
            }
        }
    }
}

My View

<Window x:Class="Clock.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModels="clr-namespace:Clock"
        Title="MainWindow" Height="75" Width="375">
    <Window.DataContext>
        <ViewModels:ClockViewModel />
    </Window.DataContext>
    <StackPanel Background="Black">
            <TextBlock Text="{Binding Path=DateTime}" Foreground="White" Background="Black" FontSize="30" TextAlignment="Center" />
    </StackPanel>
</Window>

My View Model

using System;
using System.ComponentModel;

namespace Clock
{
    public class ClockViewModel : INotifyPropertyChanged
    {
        private DateTime _time;
        private ClockModel clock;

        public ClockViewModel()
        {
            clock = new ClockModel();
            clock.TimeArrived += new Action<DateTime>(clock_TimeArrived);
        }

        private void clock_TimeArrived(DateTime time)
        {
            DateTime = time;
        }

        public DateTime DateTime
        {
            get
            {
                return _time;
            }

            set
            {
                _time = value;
                this.RaisePropertyChanged("DateTime");
            }
        }

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises the property changed event.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        private void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}


texts:
Here is my implementation of memmove; where can I improve?

void* memmove(void* dest, const void* src, std::size_t count)
{
    char *dest_ = static_cast<char*>(dest), *src_ = (char*)(src);
    if ((char*)src + count > dest && src < dest) //
    {
        dest_ += (src_ += count - 1, count - 1);
        while (count--) *dest_-- = *src_--;
    }
    else while (count--) *dest_++ = *src_++;
    return dest;
}


texts: Implementation of Mahalanobis distances using Eigen

texts:
I'm trying to learn C++ with Eigen. Here's my attempt at computing
Mahalanobis distances of a set of points x with respect to a sub-matrix xs.

The aim of the project is to turn an R code describing a statistical procedure in C++ (and in the process to learn a bit about numerical computing in c++).
Some of these functions will have to be called literally 10,000 of times so the efficiency part is a bit important.

Is this an efficient implementation of what I'm trying to do in Eigen (the code does what I want)? Can it be improved? What are the beginner's mistake that I'm doing? (in the application I have in mind, x is an imported matrix, so 30 and 3 are only known at runtime)

#include <iostream>
#include <Eigen/Dense>
#include <fstream>
#include <Eigen/Cholesky>

using namespace Eigen;
using namespace std;

VectorXd mah(MatrixXd& x, MatrixXd& xs){
    int ps = xs.cols(), ns=xs.rows();
    RowVectorXd xs_mean=xs.colwise().sum()/ns;
    MatrixXd xs_cen = (xs.rowwise()-xs_mean);
    MatrixXd x_cen = (x.rowwise()-xs_mean);
    MatrixXd w = xs_cen.transpose()*xs_cen/(ns-1);
    MatrixXd b = MatrixXd::Identity(ps,ps);
    w.ldlt().solveInPlace(b);
    x_cen = (x_cen*b).cwiseProduct(x_cen);
    return x_cen.rowwise().sum();
}

MatrixXd sub(MatrixXd&  x, VectorXi& s){
    int p = x.cols();
    MatrixXd xs(p+1,p);
    for(int i=0;i<s.size();i++){
        xs.row(i)=x.row(s(i));
    }
    return xs;
}

int main(){
    MatrixXd x = MatrixXd::Random(30,3);
    VectorXi s = (VectorXd::Random(p+1)*n).cast<int>();
    MatrixXd xs = sub(x,s);
    ofstream file("test1.txt");
    if (file.is_open()){
            file <<  x << '\n';
    }
    cout << "m" << endl <<  mah(x,xs) << endl;
    cout << "s" << endl <<  s << endl;
    return 0;
}


texts: Count number of square integers in a given range of ints (faster function?)

texts:
The function below passes most test cases:
function numOfSquares(a, b) {
    const isSquare = function (n) {
        return n > 0 && Math.sqrt(n) % 1 === 0;
    };
    let squareCount = 0;
    for (let i = a; i <= b; i++){
        if (isSquare(i)) {
            squareCount++;
        }
    }
    return squareCount
}

numOfSquares(3, 9) //out: 2
numOfSquares(17, 24) //out: 0
The time complexity of this is O(n)... right?
The problem is that this function does not pass the test cases being provided due to the time complexity. For example, in one case, the input could be numOfSquares(465868129, 988379794) (expected out: 9855). In my case, using the function above, it seems to run... forever.
How can I make this function more efficient, and thus faster?


texts:
I wanted to write a function that when applied to another would rate limit it, but permit all calls to eventually make it through.

Comments and criticism welcome.

var MAX_RUNS_PER_WINDOW = 10;
var RUN_WINDOW = 1000;

function limit(fn) {
    var callQueue = [],
      invokeTimes = Object.create(circularQueue),
      waitId = null;

    function limited() {
        callQueue.push(() => {
            invokeTimes.unshift(performance.now())
            fn.apply(this, arguments);
        });

        if (mayProceed()) {
            return dequeue();
        }

        if (waitId === null) {
            waitId = setTimeout(dequeue, timeToWait());
        }
    }

    limited.cancel = function() {
      clearTimeout(waitId);
    };

    return limited;

    function dequeue() {
        waitId = null ;
        clearTimeout(waitId);
        callQueue.shift()();

        if (mayProceed()) {
            return dequeue();
        }

        if (callQueue.length) {
            waitId = setTimeout(dequeue, timeToWait());
        }
    }

    function mayProceed() {
        return callQueue.length && (timeForMaxRuns() >= RUN_WINDOW);
    }

    function timeToWait() {
        var ttw = RUN_WINDOW - timeForMaxRuns();
        return ttw < 0 ? 0 : ttw;
    }

    function timeForMaxRuns() {
        return (performance.now() - (invokeTimes[MAX_RUNS_PER_WINDOW - 1] || 0));
    }
}

var circularQueue = [];
var originalUnshift = circularQueue.unshift;

circularQueue.MAX_LENGTH = MAX_RUNS_PER_WINDOW;

circularQueue.unshift = function(element) {
    if (this.length === this.MAX_LENGTH) {
        this.pop();
    }
    return originalUnshift.call(this, element);
}

var printLetter = limit(function(letter) {
    document.write(letter);
});

['A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'X', 'Y', 'Z'].forEach(printLetter);


texts: Longest palindromic subsequence by memoization

texts:
I've written some code to solve the longest palindromic subsequence problem.

def memoize(f):
    """ Function decorator used to cache results """
    d = dict()
    def inner(*args):
        if args not in d:
            d[args] = f(*args)
        return d[args]
    return inner

def max_palindrome(s):
    """ Returns the longest length palindrome that can
        be generated from s

    >>> max_palindrome("BBABCBCAB")
    7
    """

    @memoize
    def inner(s):
        if len(s) == 1:
            return 1
        if s[0] == s[-1]:
            return 2 + inner(s[1:-1])
        return max(inner(s[1:]), inner(s[:-1]))
    return inner(s)

My solution uses memoization to improve performance. I'm wondering how my code can be improved to return the longest subsequence rather than just the longest length achievable from the input characters.


texts:
I'm trying to get better in Python and decided to rewrite my dice roller in Perl into Python.

#!/usr/bin/env python
"""roll D&D dice"""

from sys import argv
from random import randrange
import re

if len(argv) < 2:
    raise ValueError("args are dice in D&D format like 2d6")

for roll in argv[1:]:
    matched = re.match(r'^(\d*)d(\d+)$', roll)
    if matched:
        print roll + ':'
        roll_sum = 0
        count = 0
        if len( matched.group(1) ):
            count = int( matched.group(1) )
        else:
            count = 1
        sides = int( matched.group(2) )
        for z in range(count):
            rolled = randrange(1, sides+1)
            print "\troll " + str(z) + ': ' + str(rolled)
            roll_sum += rolled

        possible = str( sides * count )
        print "\ttotal: " + str(roll_sum) + "/" + possible
    else:
        print roll + ' is not a dice in 3d8 format'

I've fixed most of the complaints from Pylint.  I'm looking for ways to make this more pythonic.  If that means more succinct or less, so be it, but I am surprised that the Python version is longer than the Perl version.  Is this the cleanest way to handle the implicit roll count as in d6 instead of 1d6?


texts: Sort string's characters into alphabetic order

texts:
Any improvements that I can make with this code?
Also, is there another way to convert a vector to a string variable without using a for ranged-based loop? From the posts I've seen for converting, I only saw printing the vector instead of returning a string.

#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;

std::string AlphabetSoup(string str) {
std::vector<char>letters;

 istringstream iss(str);

 copy(istream_iterator<char>(iss),
        istream_iterator<char>(),
        back_inserter(letters));

 std::sort(letters.begin(),letters.end());

 //Regrouping the characters into a string
 std::string orderedString;
 for(auto element : letters)
 {
     orderedString += element;
 }

 return orderedString;
}


texts: Correcting coordinates of an image with polynomial root in python

texts:
I want to optimize this for loop for correcting coordinates of an image, it takes too long which is not suited for my system. I have done some profiling, the numpy roots is taking most of the time (near to 90%). Could someone suggest some optimization or vectorization of the code? Or a better alternative?
src = cv2.imread('distorted_JJ.bmp')
dist_center = np.array([512, 224])
k1 = 0.15
k2 = 0.52

h,w,_ = src.shape
xc = dist_center[0]
yc = dist_center[1]

dst = np.zeros([h,w,3],dtype=np.uint8)
dst[::]=((255,0,0))

for i in range(h):
    for j in range(w):
        ru = np.array([j-xc, yc-i])/w
        p = [k2 , 0, k1, 0, 1, ru]
        abs_rd = np.roots(p)
        if i == yc and j == xc:
            rd = np.array([0,0])
        else:
            rd = ru * (p/abs_rd)

        v = np.array([xc/w + rd[0], yc/w - rd[1]])

        v = v*w
        v = v.astype(int)

        dst[i][j] = src[v[1],v[0]]


texts: Code Quality Catch-22 -- Duplication vs Complexity

texts:
I've started using Code Climate to assess some of my code quality and ran into a situation that I can't seem to find a good solution for. In short, in trying to solve some code duplication that resulted in a low "grade" by using metaprogramming, I simply get a low grade for code complexity instead.

Anyone know a good a way out of this trap?

Code Quality Background Info

Here are some resources that point to the underlying libraries used by Code Climate to assess code quality. I think these are pretty standard in the ruby world so this  isn't a Code Climate specific question.

Deciphering Ruby Code Metrics

Tools used by Code Climate

Before Code (duplication problem)

Several associations on User that have basically identical functionality.

  has_many :user_conditions
  has_many :conditions, :through => :user_conditions do
    def <<(new_item) # disable duplicate addition
      super( Array(new_item) - proxy_association.owner.conditions )
    end
  end
  def activate_condition(condition)
    ActiveRecord::Base.transaction do
      self.conditions << condition
      self.update_attribute(:active_conditions, (self.active_conditions | [condition.id.to_s]))
    end
  end
  def deactivate_condition(condition)
    self.update_attribute(:active_conditions, (self.active_conditions - [condition.id.to_s]))
  end

  has_many :user_symptoms
  has_many :symptoms, :through => :user_symptoms do
    def <<(new_item) # disable duplicate addition
      super( Array(new_item) - proxy_association.owner.symptoms )
    end
  end
  def activate_symptom(symptom)
    ActiveRecord::Base.transaction do
      self.symptoms << symptom
      self.update_attribute(:active_symptoms, (self.active_symptoms | [symptom.id.to_s]))
    end
  end
  def deactivate_symptom(symptom)
    self.update_attribute(:active_symptoms, (self.active_symptoms - [symptom.id.to_s]))
  end

  has_many :user_treatments
  has_many :treatments, :through => :user_treatments do
    def <<(new_item) # disable duplicate addition
      super( Array(new_item) - proxy_association.owner.treatments )
    end
  end
  def activate_treatment(treatment)
    ActiveRecord::Base.transaction do
      self.treatments << treatment
      self.update_attribute(:active_treatments, (self.active_treatments | [treatment.id.to_s]))
    end
  end
  def deactivate_treatment(treatment)
    self.update_attribute(:active_treatments, (self.active_treatments - [treatment.id.to_s]))
  end

After Code (complexity problem)

Moved out of User into a module, admittedly this code is hard to grasp.

module UserTrackables
  extend ActiveSupport::Concern

  included do |base|

    %w( treatments conditions symptoms ).each do |trackable|

      base.class_eval do
        has_many "user_#{trackable}".to_sym
        has_many trackable.to_sym, :through => "user_#{trackable}".to_sym do

          # disable duplicate addition
          def <<(new_item)
            super( Array(new_item) - proxy_association.owner.send(proxy_association.reflection.plural_name.to_sym) )
          end

        end
      end

      define_method("activate_#{trackable.singularize}") do |trackable_object|
        ActiveRecord::Base.transaction do
          self.send(trackable) << trackable_object
          self.update_attribute("active_#{trackable}".to_sym, (self.send("active_#{trackable}") | [trackable_object.id.to_s]))
        end
      end

      define_method("deactivate_#{trackable.singularize}") do |trackable_object|
        self.update_attribute("active_#{trackable}".to_sym, (self.send("active_#{trackable}") - [trackable_object.id.to_s]))
      end

      define_method("current_#{trackable}") do
        trackable.singularize.capitalize.constantize.where(id: self.send("active_#{trackable}".to_sym).map(&:to_i))
      end

    end
  end

end


texts: Random item generation system to be used in a roguelike

texts:
New to programming with the goal being to create my own roguelike. I am mostly interested right now in creating my item generation system. I want the code to create a random item that can then be used, stored in an inventory etc. Want to know if the below is a smart way to begin with. Any suggestions to make the below better would be much appreciated.

The item description within function is just there as placeholder so I can see if the code was working. Will this object be permanent ? IE everytime I call create_item it will create a permanent object - Sorry for terminology and if incorrect legit second week of playing with Python :)

import random

i_quality = ["Good", "Bad"]
i_quality = random.choice(i_quality)
i_base = ["Sword", "Gun"]
i_base = random.choice(i_base)
i_element = ["Fire", "Water"]
i_element = random.choice(i_element)

class Item(object):
    def __init__ (self, quality, base, element):
        self.quality = quality
        self.base = base
        self.element = element

def create_Item():
    new_item = Item(i_quality, i_base, i_element)
    i_description = (new_item.quality + " " + new_item.base + " of " + new_item.element)
    print (i_description)

create_Item()


texts: Size out of limits in array made with malloc

texts:
I'm applying what I learned in statistics class to a program to calculate everything automatically, but encountered an unexpected 'mistake' in my code. I say unexpected, because it's not the first time I use malloc() to make a variable sized array and used reference from my previous work, but it goes off limits with the resulting size, when earlier, it worked fine as intended.

Can you tell me why the size ends up wrong?

I know something's wrong in the way I wrote it that should be corrected before I keep using this code, because it's exactly the same as before, and results should not change in a good code.

Code:

#include <stdio.h>
#include <stdlib.h>

int MakeSample();
int PrintSample();

int *sample;

int main(void)
{
    MakeSample();
    PrintSample();
}

int MakeSample()
{
    int sampleSize;
    int valueN;

    printf("Enter size of your sample: ");

    scanf("%d", &sampleSize);

    sample = malloc(sampleSize * sizeof(int));

    for (int i = 1; i <= sampleSize; i++)
    {
        printf("Enter value #%d: ", i);

        scanf("%d", &valueN);

        sample[i - 1] = valueN;
    }
}

int PrintSample()
{
    for (int k = 1; k <= sizeof(sample); k++)
    {
        printf("Value #%d: %d\n", k, sample[k - 1]);
    }
}

The result is this for a sampleSize of 1:

Value #1: 1
Value #2: 0
Value #3: 0
Value #4: 0
Value #5: 0
Value #6: 0
Value #7: 133057
Value #8: 0


texts: Converting from POS tagged word-tokens to POS tagged Phrases

texts:
I have sentences expressed as Parts of speech (POS) tagged words.
I want to have all the short phrases in them to be joined up with underscores.
I want them to have the Part of speech tag of the final word in the phrase -- not because this is necessarily linguistically correct, but because it will perform correctly in my system later when it has to "Unstem"/"Unlemmaize" derived words/phrases.

For example, if I had the following sentence, (based off of the first sentence in the Microsoft research paraphrase corpus):

  PCCW's chief operating officer, Mike Butcher, and the Arena brothers, the chief financial officers, will report directly to the police officer.

Then the POS tagged text is:

[('PCCW', 'NNP'), ("'s", 'POS'), ('chief', 'NN'),('operating', 'VBG'), ('officer', 'NN'),(',', ','),('Mike', 'NNP'),('Butcher', 'NNP'), (',', ','),('and', 'CC'),('the', 'DT'),('Arena', 'NNP'),('brothers', 'NNS'),(',', ','),('the', 'DT'),('chief', 'JJ'), ('financial', 'JJ'),('officers', 'NNS'),(',', ','),('will', 'MD'),('report', 'VB'),('directly','RB'),('to', 'TO'),('the', 'DT'), ('police', 'NN'),('officer', 'NN'), ('.', '.')]

And the POS tagged phrases (ie the output of my function) is:

[('PCCW', 'NNP'), ("'s", 'POS'), ('chief_operating_officer', 'NN'), (',', ','), ('Mike', 'NNP'), ('Butcher', 'NNP'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('Arena', 'NNP'), ('brothers', 'NNS'), (',', ','), ('the', 'DT'), ('chief_financial_officers', 'NNS'), (',', ','), ('will', 'MD'), ('report', 'VB'), ('directly', 'RB'), ('to', 'TO'), ('the', 'DT'), ('police_officer', 'NN'), ('.', '.')]

I am prepared to accept WordNet as the ground truth as to the existence or not of a phrase.

from nltk.corpus import wordnet as wn
def get_tagged_phrases(tagged_sent, max_phrase_length):

    tagged_phrase_sent = list(tagged_sent)
    for phrase_len in range(max_phrase_length,1,-1): #Go from largest to smallest to keep information
        for indexes in n_wise(phrase_len, range(len(tagged_sent))):
            tagged_words = [tagged_phrase_sent[index] for index in indexes]
            if not(any([tagged_word is None for tagged_word in tagged_words])):
                words, tags = zip(*tagged_words)
                possible_phrase = "_".join(words)
                if wn.synsets(possible_phrase): #If there are any, then it is a phrase
                    for index in indexes:
                        tagged_phrase_sent[index] = None #Blank them out with Nones which we will remove later
                    pos = tags[-1] #Use final tag, it will be the one we need for handling plurals
                    tagged_phrase_sent[indexes[0]] = (possible_phrase, pos)
    return [tagged_phrase for tagged_phrase in tagged_phrase_sent if not tagged_phrase is None]

The obvious code smell is that it is nested about 5 deep.
That is too much state to remember, perhaps.

This is in Python 2


texts: Newton's Method Polynomial solver in Ruby

texts:
I am learning Ruby programming from "Learn Ruby the Hard way" and I am doing the "Ruby koans".

I have heard a little bit about "Idiomatic" Ruby but I don't know much about it. How can I make it more idiomatic?

# Program to solve polynomials

def solve(coeff)
    coefficients = []
    coeff.each{ |a|
        coefficients.push a.to_f
    }
    diffrentiate = []
    n = 0
    coefficients.reverse_each { |a|
        diffrentiate.unshift n*a
        n += 1
    }
    diffrentiate.pop
    return newton(coefficients,diffrentiate,-1)
end

def newton(coefficients,diffrentiate,initialvalue)
    x = initialvalue
    10.times { |n|
        x -= evaluate_polynomial(coefficients,x)/evaluate_polynomial(diffrentiate,x)
    }
    return x
end

def evaluate_polynomial(coefficients,x)
    n = 0
    value = 0
    coefficients.reverse_each { |a|
        value += a*x**n
        n+=1
    }
    return value
end

puts solve ([1,0,0,0,-1,1])


texts: Designing a public API for a JavaScript module

texts:
I am writing a module that can access localStorage through a public API which exposes methods that allow string or array returns.

It doesn't feel as though I'm doing this in the most effective way. For example, I feel as though using:

var tudCache = getTud(); to grab the object from getTud() doesn't feel like the most correct implementation.

I'm inclined to use an if statement i.e. if(getTud().isSuccessful) to check the conditional but then I would have to re-execute getTud().result to return the result inside that conditional, causing the getTud() function to be called twice.

Does anyone have any thoughts?

_self.getTudCache = function () {

    // returns an object. {'isSuccessful': boolean, 'result': String}
    function getTud() {

        return localstorage.getItem(tudStorageKey);

    }

    function getString() {

        var tudCache = getTud();

        if (tudCache.isSuccessful)
            return tudCache.result;
        return "";

    }

    function getArr() {

        var tudCache = getTud();

        if (tudCache.isSuccessful)
            return JSON.parse(tudCache.result)[tudCacheKey];
        return [];
    }

     return {
         getString: getString,
         getArr: getArr
     }
};


texts:
This is a small utility that permutes a C++ standard container without modifying the container being iterated:

random_iterator.hpp

#ifndef RANDOM_ITERATOR_HPP
#define RANDOM_ITERATOR_HPP

#include <initializer_list>
#include <random>
#include <vector>

namespace net {
namespace coderodde {
namespace utilities {

template<typename T>
class random_iterator {
private:
    std::vector<T> vec;

public:

    template<typename Iterable>
    explicit random_iterator(Iterable iterable)
    {
        for (auto& x : iterable)
        {
            vec.push_back(x);
        }

        std::random_device rd;
        std::mt19937 g(rd());
        std::shuffle(vec.begin(), vec.end(), g);
    }

    template<typename Iterable>
    explicit random_iterator(Iterable iterable, std::random_device& rd)
    {
        for (auto& x : iterable)
        {
            vec.push_back(x);
        }

        std::mt19937 g(rd());
        std::shuffle(vec.begin(), vec.end(), g);
    }

    explicit random_iterator(std::initializer_list<T>& lst)
    {
        for (auto& x : lst)
        {
            vec.push_back(x);
        }

        std::random_device rd;
        std::mt19937 g(rd());
        std::shuffle(vec.begin(), vec.end(), g);
    }

    explicit random_iterator(std::initializer_list<T>& lst,
                             std::random_device& rd)
    {
        for (auto& x : lst)
        {
            vec.push_back(x);
        }

        std::mt19937 g(rd());
        std::shuffle(vec.begin(), vec.end(), g);
    }

    typename std::vector<T>::iterator begin()
    {
        return vec.begin();
    }

    typename std::vector<T>::iterator end()
    {
        return vec.end();
    }

    typename std::vector<T>::const_iterator begin() const
    {
        return vec.cbegin();
    }

    typename std::vector<T>::const_iterator end() const
    {
        return vec.cend();
    }
};

} // End of net::coderodde::utilities
} // End of net::coderodde
} // End of net
#endif // RANDOM_ITERATOR_HPP

main.cpp

#include "random_iterator.hpp"
#include <iostream>
#include <set>
#include <vector>

using namespace std;
using net::coderodde::utilities::random_iterator;

int main(int argc, const char * argv[]) {
    vector<int> v1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for (auto& x : random_iterator<int>(v1))
        cout << x << " ";

    cout << "\n";

    set<int> s1 {1, 2, 3, 4, 5};

    for (auto& x : random_iterator<int>(s1))
        cout << x << " ";

    cout << "\n";
}

Critique request

I would like to know, how a professional C++ programmer would implement this.


texts:
I am new to developing in Python and would like to see comments about my word count solution.

Please indicate my mistakes or best solutions.

def count_words(text):
  text = text.lower()

  symbols = "1234567890!#$%^&*\"()_+=-{}[].,:"
  for s in list(symbols):
    text = text.replace(s,"")
  text = text.split()
  lst = list(set(text))
  dictonary = {"words":lst, "nums":[0]*len(lst)}
  for word in text:
    dictonary['nums'][dictonary['words'].index(word)] += 1

  import pandas as pd
  df = pd.DataFrame(dictonary)
  return df.sort_values(by=['nums'], ascending=False)#.to_csv("./words.csv")

count_words("Hello world, World War, War and Peace")


texts: Testing a list of proxies for validity concurrently

texts:
I have a class that tests a list of proxies for validity concurrently, which I have created in 2 different ways, one utilizing Parallel.ForEach and the other using a TPL Dataflow ActionBlock.

I am just wondering which is one is preferred, and if I am overlooking something important.  As a side note, I created the Dataflow version because I want to be able to queue proxy tests, with the Parallel.ForEach version I could probably achieve that but it would take more code and some refactoring.

I still need some add some functionality to these methods. I realize the 'tests' parameter isn't being used.

Parallel.ForEach version:

public class ProxyTester
{
    public async Task ValidateProxiesAsync(IEnumerable<Proxy> proxies, IEnumerable<ProxyJudge> judges, IEnumerable<ProxyTest> tests)
    {
        await Task.Run(async () =>
        {
            foreach (var proxy in proxies)
            {
                proxy.Status = ProxyStatus.Queued;
            }
            await proxies.ProcessWithParallelAsync(new Action<Proxy>((proxy =>
            {
                proxy.Status = ProxyStatus.Testing;
                proxy.Status = proxy.TestValidity(judges.ElementAt(0));
            })));
        });
    }
}

ProcessWithParallelAsync Extension method:

public static async Task ProcessWithParallelAsync<T>(this IEnumerable<T> list, Action<T> action, int maxConcurrency = 100)
{
    await Task.Run(() => {
        var options = new ParallelOptions();
        options.MaxDegreeOfParallelism = maxConcurrency;
        Parallel.ForEach(list, options, action);
    });
}

TPL Dataflow version (supports queuing):

class ProxyTester2
{

    private ActionBlock<(Proxy, IProxyTest)> actionBlock;

    public ProxyTester2()
    {
        actionBlock = new ActionBlock<(Proxy proxy, IProxyTest test)>(tup =>
        {
            tup.proxy.Status = ProxyStatus.Testing;
            tup.proxy.Status = tup.proxy.TestValidity(tup.test);
        }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 100 });
    }

    public void QueueProxyTest(Proxy proxy, IProxyTest test)
    {
        proxy.Status = ProxyStatus.Queued;
        actionBlock.Post((proxy, test));
    }

    public void QueueProxyTests(IEnumerable<Proxy> proxies, IEnumerable<ProxyJudge> judges, IEnumerable<ProxyTest> tests)
    {
        foreach (var proxy in proxies)
        {
            QueueProxyTest(proxy, judges.ElementAt(0));
        }
    }
}


texts: Search Function With Wildcard in Haskell

texts:
I'm teaching myself how to program Haskell, and I decided to make a find function in Haskell. What it does is it takes two strings, such as "hello" and "he", and it counts how many times "he" appears in "hello". In addition, it also uses the * character as a wildcard, so searching for "he*o" in "hello" will return 1.

Latest Update

This update used pattern matching and less guards, and also outputs 1 if ssearch "blah" "*".

ssearch _ [] = 0
ssearch [] _ = 0
ssearch ('*':_) _ = error "no '*' allowed in hay"
ssearch _ ['*'] = 1
ssearch haystack ('*':needles) = ssearch haystack needles --removes '*', and then searches through hay for the char after the '*'
ssearch (hay:haystack) (needle:needles)
  | needle == hay = search2 haystack needles + ssearch haystack (needle:needles)
  | otherwise = ssearch haystack (needle:needles)
    where
    search2 _ [] = 1
    search2 [] _ = 0
    search2 ('*':_) _ = error "no '*' allowed in hay" -- I need to declare this twice because search2 often jumps ahead of ssearch.
    search2  _ ['*'] = 1
    search2 haystack ('*':needles) = ssearch haystack needles
    search2 (hay:haystack) (needle:needles)
      | needle == hay = search2 haystack needles
          | otherwise = 0

Update:

Thinking over dave4420's comments, I decided to redo the entire algorithm. I think that it fixes most of the bugs.

ssearch _ [] = 0
ssearch [] _ = 0
ssearch (hay:haystack) (needle:needles)
  | hay == '*' = error "no '*' allowed in hay" --no confusion with wildcard things
  | needle == '*' = ssearch (hay:haystack) needles --removes '*', and then searches through hay for the char after the '*'
  | needle == hay = search2 haystack needles + ssearch haystack (needle:needles)
  | otherwise = ssearch haystack (needle:needles)
    where
    search2 _ [] = 1
    search2 [] _ = 0
    search2 (hay:haystack) (needle:needles)
      | hay == '*' = error "no '*' allowed in hay" -- I need to declare this twice because search2 often jumps ahead of ssearch.
      | (needle == '*') && (needles /= []) = ssearch (hay:haystack) needles
      | (needle == '*') && (needles == []) = 1
      | needle == hay = search2 haystack needles
          | otherwise = 0

I'm wondering if there are still any bugs, and also, if there is any way I can improve this code.

Old Code

search :: String -> String -> Integer
search x y = search1 x y y 0 -- n is set to 0, because nothing has been found yet :)
  where
    search1 :: String -> String -> String -> Integer -> Integer
    search1 _ _ [] n = n -- z can't be empty
    search1 x [] z n = search1 x z z (n+1) -- if y is empty but x isn't, it means the word was found, and y needs to be reset
    search1 [] _ _ n = n --end the program, bc if x is empty, the program has searched through the entire string
    search1 (x:xs) (y:ys) z n
      | x == '*' = error "you can not enter the character '*' in the first field: the '*' character is reserved for wildcard searches"
      | (y == '*') && ((head ys) == '*') = error "You can not include two '**' in a row, that messes up the wildcard operator"
      | x == y = search1 xs (ys) z n
      | (y == '*') && (ys /= []) = if (x == (head ys)) --this section is so search "hello" "h*llo" = 1
                        then search1 (x:xs) ys z n --if the string matches up with the rest of the string, excluding the '*', then redu the query, excluding the '*'
                       else search1 xs (y:ys) z n --} --otherwise keep on searching for the wildcard thing
      | (y == '*') && (ys == []) = n + 1 -- so search "hello" "*" = 1
      | otherwise = search1 xs z z n -- don't include (y:ys), otherwise search "hihe" "hhe" = 1


texts: Group items by types: replace nested for loops with reduce

texts:
I have a working code that groups items by their type values. The types can be one or multiple, however they are always returned as an array.

To illustrate: if an item has types with values type1 and type2, it should be included in both type1 and type2 properties of the resulting grouped object.

Although the code works, I was wondering if it would be possible to rewrite it without using nested for loops, to make it more aligned with the principles of functional programming, ideally using reduce. Since the data sets are not too large, performance is a secondary consideration, but should be taken into account if possible.

The code is as follows. getTypes is added primarily to show how the types are extracted and ideally shouldn't be changed.

const items = [{
    name: 'First item',
    types: [{
        value: 'type1',
      },
      {
        value: 'type2',
      },
    ],
  },
  {
    name: 'Second item',
    types: [{
        value: 'type1',
      },
      {
        value: 'type3',
      },
    ],
  },
  {
    name: 'Third item',
    types: [{
        value: 'type1',
      },
      {
        value: 'type2',
      },
    ],
  },
];

const getTypes = item => item.types.map(type => type.value);

const groupedItems = {};

for (const item of items) {
  for (const type of getTypes(item)) {
    groupedItems[type] = [...(groupedItems[type] || []), item];
  }
}

console.log(JSON.stringify(groupedItems, null, 4));

Code output:

{
    "type1": [
        {
            "name": "First item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type2"
                }
            ]
        },
        {
            "name": "Second item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type3"
                }
            ]
        },
        {
            "name": "Third item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type2"
                }
            ]
        }
    ],
    "type2": [
        {
            "name": "First item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type2"
                }
            ]
        },
        {
            "name": "Third item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type2"
                }
            ]
        }
    ],
    "type3": [
        {
            "name": "Second item",
            "types": [
                {
                    "value": "type1"
                },
                {
                    "value": "type3"
                }
            ]
        }
    ]
}


texts: Compare every combination of variables within the powerset

texts:
I have some survey data that represents individual's responses to multiple survey questions.  There are about 10,000 people in my actual dataset, and each person answered 35 questions.  From these 35 survey questions, I create 1 composite score for each individual by taking the average of the values of all the questions that person answered. I am looking to see if I can find a subset of less than all 35 variables that produces a composite score that is highly correlated with the scores individuals receive if I use all of the questions.

Essentially, I want to be able identify which questions you should ask, if you can only ask X questions, and still end up with a composite score that is similar to if you asked all the questions.

I have created an example dataset, but with only 1,000 individuals and 10 questions.  I have then written the code below to identify every subset of variables and compare the correlation of individual's scores when using just that subset to individual's scores when using all of the variables.

While my method below works when there are 1,000 individuals and 10 questions, it does not scale to my reality of 10,000 individuals and 35 questions, because of all the possible combinations of variables (2^35 = 34,359,738,368).

(Note: I have simplified my question and the sample data below for the purpose of this question.)

Code on GitHub: https://github.com/CurtLH/variable_subset/blob/master/powerset%20correlations.ipynb

import random
import numpy as np
import pandas as pd
from itertools import chain, combinations

# initial parameters
random.seed(1234)
num_ids = 1000
num_vars = 10

# create repeating IDs
ids = sorted(list(range(0, num_ids)) * num_vars)

# create repeating variables
variables = list(range(0, num_vars)) * num_ids

# create random integers
values = np.random.randint(1, 5, size = num_ids * num_vars)

# create a dataframe with these values
df = pd.DataFrame({"id": ids, "variable": variables, "values": values})

# sort the dataframe
df.sort_values(['id', 'variable'], inplace=True)

def powerset(iterable):
    """
    Thanks to https://stackoverflow.com/questions/1482308
    """
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

# create every subset of variables
subsets = list(powerset(set(variables)))

# calculate the average value by ID when including all variables
actual = df.groupby('id')['values'].mean()

def calculate(df, subsets):

    """
    1. Iterate over each permutation of variables
    2. Subset the dataframe to only include those variables
    3. Group by ID and recalculate the mean values per ID
    4. Measure correlation with complete set of variables
    """

    # create a dictionary to hold the results
    results = {}

    # iterate over each subset
    for s in subsets:

        # make sure there is at least 1 variable...
        if len(s) > 0:

            # filter the dataframe to only the variables in the subset
            sub = df[df['variable'].isin(s)]

            # group by ID and calculate average value
            scores = sub.groupby('id')['values'].mean()

            # calculate correlation compared to complete set of variables
            corr = actual.corr(scores)

            # add results to dictionary
            results[s] = {'num_items': len(s),
                          'correlation': corr}

    return results

# time how long it takes to run
%%timeit results = calculate(df, subsets)

Timing results:

2.23 s ± 3.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


texts:
I am using a set of data points (currently randomly generated), and drawing a line graph inside a box:

struct DrawLine: View {
    var body: some View {
        ZStack {
            Rectangle()
                .stroke(lineWidth: 1.0)
                .fill(Color.purple)
                .frame(width: InstrumentPrices.boxWidth, height: InstrumentPrices.boxHeight, alignment: .center)

            SparkLine()

        }
        .frame(width: 0, height: 0).border(Color.black)
    }
}

struct SparkLine: View {
    @State var myPoints = InstrumentPrices.points

    static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255)
    static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 20.0 / 255)

    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color.white)
                .onTapGesture {
                    // print ("Tap!")
                    InstrumentPrices.resetPoints()
                    self.myPoints = InstrumentPrices.points
                }

            GeometryReader { geometry in
                Path { path in
                    path.move(to: InstrumentPrices.points[0])

                    self.myPoints.forEach {
                        path.addLine(
                            to: CGPoint(x: $0.x, y: $0.y)
                        )
                    }
                }
                .stroke(lineWidth: 2)
                .fill (LinearGradient (
                    gradient: .init(colors: .init([Self.gradientStart, Self.gradientEnd])),
                    startPoint: .init(x: 0, y: 0),
                    endPoint: .init(x: 1.0, y: 0)
                ))
            }
        }
    }
}

SwiftUI is new enough to me. I'm always looking for better code conventions. Any comments are welcome!


texts: While loops in SCSS to produce circles for an animation

texts:
I've finally written my first loop in SCSS, trying to avoid it for quite some time since I thought it was unnecessary (was writing vanilla CSS not so long ago, so I was used to manual work).

However, I feel this code isn't very optimized, especially since I seem to need two different while-loops (one for divs from center to left, and one for divs to the right).

Demo is available at http://codepen.io/pestbarn/pen/myqvEq

The loops

I found myself needing an @if condition for tweaking the margin for the center div by just 1vh.

// generate 6 circles from center to left
$i: 6;
$s: 38;
$t: -19;
$l: -90;
$z: 2;
@while $i > 0 {
  &:nth-child(#{$i}) {
    @include sqsize($s);
    margin-top: $t+vh;
    margin-left: $l+vh;
    z-index: $z;
  }
  $i: $i - 1;
  $s: $s - 2;
  $t: $t + 1;
  @if $l == -30 {
    $l: $l + 16
  } @else {
    $l: $l + 15;
  }
  $z: $z + 1;
}
// generate 5 circles to the right
$i: 11;
$s: 38;
$t: -19;
$l: 52;
$z: 2;
@while $i > 6 {
  &:nth-child(#{$i}) {
    @include sqsize($s);
    margin-top: $t+vh;
    margin-left: $l+vh;
    z-index: $z;
  }
  $i: $i - 1;
  $s: $s - 2;
  $t: $t + 1;
  $l: $l - 13;
  $z: $z + 1;
}

Is there perhaps a way of only needing to write one while-loop for this? From left to right, the div sizes (where 1 is smallest and 6 is largest) go 6 5 4 3 2 1 2 3 4 5 6, in that order.


texts: Unit testing Roman-Arabic-Roman numeric converter

texts:
As you can see here, I wrote the methods public static int romanToArabic(String number) and public static String arabicToRoman(int number) to convert roman numbers to arabic numbers and vice versa.

I now wrote a unit-testing-class to test these methods. It is my first attempt to write a (real) unit test, so I would like to know your opinion.

Here's the code:

import org.junit.Test;
import static org.junit.Assert.*;

public class TestCases {

    @Test
    public void testRomanToArabic() {
        String[] input = {null, "", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "MMMMXI", "KMXI",
                "VX", "VL", "VC", "VD", "VM", "LC", "LD", "LM", "DM", "IL", "IC", "ID", "IM", "XD", "XM", "CXLV", "MIXI", "IXI", "MXIII", "MMMM", "IIII"};
        int[] expectedOutput = {-1, -1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, 1013, -1, -1};
        for(int i = 0; i < input.length; i++) {
            int k = RomanNumbers.romanToArabic(input[i]);
            try {
                assertEquals(k, expectedOutput[i]);
            }
            catch(AssertionError assertFailed) {
                System.out.println("Test failed!");
                System.out.println("Input: " + input[i]);
                System.out.println("Output: " + k + "| Expected: " + expectedOutput[i]);
            }
        }
    }

    @Test
    public void testArabicToRoman() {
        int[] input = {-1, 1, 5, 33, 747, 929, 1232, 3999, 4000};
        String[] expectedOutput = {"Error", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "Error"};
        for(int i = 0; i < input.length; i++) {
            String k = RomanNumbers.arabicToRoman(input[i]);
            try {
                assertEquals(k, expectedOutput[i]);
            }
            catch(AssertionError assertFailed) {
                System.out.println("Test failed!");
                System.out.println("Input: " + input[i]);
                System.out.println("Output: " + k + "| Expected: " + expectedOutput[i]);
            }
        }
    }
}

Is this the way to go, or is it considered bad practice to put more than one test in a method?
Do you have any other suggestions on improving the code?


texts:
Question:

Input String 1 = {1, 2, 3, ... , 26}

Input String 2 = {A, B, C, ... , Z}

Output Result 1 = {1, A, 2, B, 3, C, ... , 26, Z}

Output Result 2 = {1, A, 2, A, B, 3, A, B, C, ... , 26, A, B, C, . , Z}

Solution:

public class Combinations {

    private static String stringNumbers[];                  //1, 2, 3, ... , 26
    private static String stringAlphabets[];                //A, B, C, ... , Z

    private static String resultNumberAlphabet[];           //1, A, 2, B, 3, C, ... , 26, Z
    private static String resultNumberAlphabets[];          //1, A, 2, A, B, 3, A, B, C, ... , 26, A, B, ... , Z

    private static final int MAX_NUMBERS = 26;
    private static final int MAX_ALPHABETS = 26;

    public static void main(String[] args) {
        initVariables();
        findCombinations();
        printResults(resultNumberAlphabet);
        printResults(resultNumberAlphabets);
    }

    private static void initVariables() {
        stringNumbers = new String[MAX_NUMBERS];
        stringAlphabets = new String[MAX_ALPHABETS];
        resultNumberAlphabet = new String[stringNumbers.length + stringAlphabets.length];
        resultNumberAlphabets = new String[stringNumbers.length + (stringAlphabets.length * (stringAlphabets.length + 1)/2)];   //  Summation Equation = [n*(n+1)/2];

        for (int i = 0; i < 26; i++) {
            stringNumbers[i] = (i + 1) + "";
            stringAlphabets[i] = Character.toString((char)(i + 65));
        }
    }

    private static void findCombinations() {
        int k = -1;
        int l = -1;
        for (int i = 0; i < stringNumbers.length; i++) {
            resultNumberAlphabet[++k] = stringNumbers[i];
            resultNumberAlphabet[++k] = stringAlphabets[i];
            resultNumberAlphabets[++l] = stringNumbers[i];
            for (int j = 0; j <= i; j++) {
                resultNumberAlphabets[++l] = stringAlphabets[j];
            }
        }
    }

    private static void printResults(String result[]) {
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i]);
            if ((i + 1) == result.length) {
                System.out.println(".");
            } else {
                System.out.print(", ");
            }
        }
    }

}

Any review comments or suggestions?


texts:
I'm attempting to escape ampersands from a string before passing to PHP's SimpleXMLElement->addChild() for use with some SOAP webservices, but I don't want to double escape them. I'm getting these strings from a variety of sources so I can't count on them not being escaped already.  &amp;amp; or &amp; should be untouched but & or &blah blah blah should not.

<?php $s = preg_replace('/&([^; ]*)( |$)/','&amp;$1$2',$s)


texts: Kadane's Algorithm, finding maximum contiguous array

texts:
Description of Kadane's algorithm.
Please comment on the efficiency and approach.

class Kadane {
int sum = 0;
int max = 0;

public static void main(String[] args) {
    int[] full = { 1, 2, 3, 4, 5, -6, -77, 3, 14, -10 };
    Kadane Kadane = new Kadane();
    int max = Kadane.splitArr(full);
    System.out.println("The maximum value of the seq is " + max);
}

public int localMax(int[] full, int sublength) {
    for (int i = sublength; i >= 0; i--) {
        sum = sum + full[i];
        if (sum > max) {
            max = sum;
        }
    }
    sum = 0;
    return max;
}

public int splitArr(int[] full) {
    int sum_final = 0;
    int max_final = 0;
    for (int j = 0; j < full.length; j++) {
        sum_final = localMax(full, j);
        if (sum_final > max_final) {
            max_final = sum_final;
        }
    }

    return max_final;
}
}


texts:
I am trying to find the path of property in an object in JavaScript.  For example, given

var myObj = { 'a': {'b': {'c': {'x': 1, 'y': 2 }}} }

the path of 'x' in myObj would be a.b.c.x (dot notation).

I wrote the code below using a recursive mechanism.

function findPropPath(obj, name, currentPath) {
    var currentPath = currentPath || '';

    for (var i in obj)
    {
        if (i == name)
        {
            return name;
        }
        else if (obj[i] && typeof obj[i] == "object")
        {
            var result = findPropPath(obj[i], name, currentPath + '.' + i);
            if (result == name)
            {
                return currentPath += '.' + name;
            }
            else if (result && result.endsWith('.' + name)) {
                return result;
            }
        }
    }
}

It works as expected, I would like to know if it can be optimized or other better ways find property path. Also I assume the call stack size would grow for  enormous object. Any review would be of great help!


texts:
Here's my first shot at implementing Tic Tac Toe in Ruby. After watching Gary Bernhardt's Functional Core, Imperative Shell, I thought this would be a great exercise in trying out the ideology presented in that screencast. Tear my code apart.

Link to GitHub repo (includes video of usage)

tic_tac_toe.rb -- the procedural shell

require_relative "board"
require_relative "cell"
require "pry"

def initialize_board
  @board = Board.new
end

def choose_characters
  puts "X or O?"
  @player_character = gets.chomp
  @computer_character = case @player_character
                        when "X" then "O"
                        when "O" then "X"
                        end
end

def start_game
  initialize_board
  choose_characters
  play
end

def play
  loop do
    puts "Make a move: "
    move = gets.chomp
    board_index = Board::POSITIONS[move]
    winner = @player_character

    @board.board[board_index].value = @player_character

    if !@board.winner?
      @board.available_cells.sample.value = @computer_character
      winner = @computer_character if @board.winner?
    end

    if @board.winner?
      p "#{winner.upcase} WINS!!!"
      @board.display
      puts "Do you want to play again?"

      start_game if gets.chomp == "Yes"
    else
      @board.display
      play
    end

    break if @board.winner?
  end
end

start_game

board.rb

class Board
  attr_accessor :board

  WINNING_COMBINATIONS = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ]

  POSITIONS = {
    "top left" => 0,
    "top middle" => 1,
    "top right" => 2,
    "middle left" => 3,
    "center" => 4,
    "middle right" => 5,
    "bottom left" => 6,
    "bottom middle" => 7,
    "bottom right" => 8
  }

  def initialize
    @board = Array.new(9) { Cell.new }
  end

  def winner?
    winner = false
    WINNING_COMBINATIONS.each do |combination|
      first_cell = board[combination[0]].value
      second_cell = board[combination[1]].value
      third_cell = board[combination[2]].value
      consideration = [first_cell, second_cell, third_cell]

      if consideration.uniq.length == 1 && first_cell.is_a?(String)
        winner = true
      end
    end
    winner
  end

  def available_cells
    board.select { |cell| cell.value == :blank }
  end

  def display
    rows = board.each_slice(3).to_a

    rows.each do |row|
      p row.map(&:value)
    end
  end
end

cell.rb

class Cell
  attr_accessor :value

  def initialize(options = {})
    @value = options.fetch(:value, :blank)
  end
end


texts:
I have got a piece of code that initialize Scanner in two possible ways:

no argument constructor creates Scanner that uses stdIO (System.in) as source
contructor with String, which creates Scanner, that uses file as source, where String is a path to file

It looks like this:

public class InputMethod implements IInputMethod {

private final Scanner fileReader;
private final Scanner userInput = new Scanner(System.in);

public InputMethod(String[] args) throws FileNotFoundException {
    if (args.length == 1)
        fileReader = setFileAsSource(args[0]);
    else
        fileReader = setStdIOAsSource();
}

private Scanner setFileAsSource(String filename) throws FileNotFoundException {
        return new Scanner(new File(filename));
}

private Scanner setStdIOAsSource() {
    return new Scanner(System.in);
}
}

In main:

public static void main(String[] args) throws FileNotFoundException {
    IInputMethod input= new InputMethod(args);

    while (!input.getUserInput().equals("Exit")) {
        // awesome stuff
    }
    input.closeInput();
}

It works great, but it does not look pretty when it comes to exception handling. My dream would be creating a method, in which I will handle possible File-related problems and next one, that will do the job, just like good old Uncle Bob said.

Can anyone take a look at this and maybe suggest some minor changes, to make it clean and friendly?


texts: Method for gathering the correct data to a specific user

texts:
I have quite a lengthy method that I know for sure can be optimized, yet I am not sure how to do it. The method is in my User model, and essentially gets the questions assigned to the user in the current week. Questions can be assigned to a variety of intervals, so it's important that for each week we get the right ones.

  def collect_right_questions_for_this_week
    current_week = Time.zone.now.strftime('%V').to_i

    odd_or_even_week = current_week.odd? ? :odd_weeks : :even_weeks

    beginning_week_of_month =
      Time.zone.now.beginning_of_month.strftime('%V').to_i
    end_week_of_month       =
      Time.zone.now.end_of_month.strftime('%V').to_i

    beginning_week_of_quarter =
      Time.zone.now.beginning_of_quarter.strftime('%V').to_i
    end_week_of_quarter       =
      Time.zone.now.end_of_quarter.strftime('%V').to_i

    frequency_values = [questions.frequencies[:weekly]]
    frequency_values << questions.frequencies[odd_or_even_week]

    frequency_values << questions.frequencies[:start_of_month] if
      current_week == beginning_week_of_month

    frequency_values << questions.frequencies[:end_of_month] if
      current_week == end_week_of_month

    frequency_values << questions.frequencies[:start_of_quarter] if
      current_week == beginning_week_of_quarter

    frequency_values << questions.frequencies[:end_of_quarter] if
      current_week == end_week_of_quarter
    frequency_values
  end

As you can see here, it's quite lengthy and repetitive. Essentially what I'd like to achieve is for it to be reduced, and better written, it doesn't have this nice flow to it.

I also recall that a method should only do 1 thing, while at least in my opinion this method does two things. It sets dates, and then gets questions.


texts: Moving an element from one unordered_map to another

texts:
This code moves one element from one unordered_map to another.

I would like to ask if my code below can be improved.

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <unordered_map>

int main()
{
    struct Data
    {
        int foo;
        bool boo;
    };
    std::unordered_map<std::string, Data> map_A = {{"A", {1, true}}, {"B", {2, false}}};
    std::unordered_map<std::string, Data> map_B = {{"C", {3, false}}, {"D", {4, true}}};;

    std::string keyToMove = "C";
    map_A.insert({keyToMove, map_B[keyToMove]});
    map_B.erase(keyToMove);

    std::cout << "map_A" << std::endl;
    auto it = map_A.begin();
    while(it != map_A.end())
    {
        std::cout<<it->first<<" :: "<<it->second.foo<<std::endl;
        it++;
    }
    std::cout << "map_B" << std::endl;
    auto it2 = map_B.begin();
    while(it2 != map_B.end())
    {
        std::cout<<it2->first<<" :: "<<it2->second.foo<<std::endl;
        it2++;
    }
    return 0;
}

Result:

map_A
C :: 3
B :: 2
A :: 1
map_B
D :: 4
Program ended with exit code: 0


texts: Flatten JSON to get relevant data in Postgresql

texts:
Following is my table:

CREATE TABLE test.individuals
  (
     id        INT PRIMARY KEY,
     firstname VARCHAR,
     lastname  VARCHAR,
     phone     JSONB,
     email     JSONB
  );

Which contains the following records (say):

INSERT INTO test.individuals (
            id,
            firstname,
            lastname,
            phone,
            email
) VALUES (  1,
            'Ajay',
            'Upadhaya',
            '[{"Type": "Mobile", "Number": "9876543210"}, {"Type": "Home", "Number": "23456789"}, {"Type": "Work", "Number": "24356758"}]',
            '[{"Type": "Home", "Email": "ajay@xyz.com"},{"Type": "Work", "Email": "ajay@abc.com"}]'
), (        2,
            'Vikas',
            'Singh',
            '[{"Type": "Mobile", "Number": "8978675612"}, {"Type": "Home", "Number": "21324354"}, {"Type": "Work", "Number": "24256376"}]',
            '[{"Type": "Work", "Email": "vikas@xyz.com"}]'
), (        3,
            'Atul',
            'Prasad',
            '[{"Type": "Mobile", "Number": "7895674563"}]',
            '[]'
), (        4,
            'Soumil',
            'Roy',
            '[{"Type": "Mobile", "Number": "8798765632"}]',
            '[{"Type": "Home", "Email": "soumil@xyz.com"}]'
);

My requirement was to get mobile numbers in one field, and the rest of the numbers in another field (Since, there can be multiple numbers, they have to be separated by commas). Same for email ids.

Following is my query:

WITH persons
     AS (SELECT id,
                firstname,
                lastname
         FROM   test.individuals),
     email_ids
     AS (SELECT id,
                Jsonb_array_elements(email) :: jsonb AS email_object
         FROM   test.individuals),
     email_aggregated
     AS (SELECT id,
                String_agg(email_object ->> 'Email', ',') AS email_id
         FROM   email_ids
         GROUP  BY id),
     phone_numbers
     AS (SELECT id,
                Jsonb_array_elements(phone) :: jsonb phone_object
         FROM   test.individuals),
     mobile_numbers
     AS (SELECT id,
                String_agg(phone_object ->> 'Number', ',') AS mobile_number
         FROM   phone_numbers
         WHERE  phone_object ->> 'Type' = 'Mobile'
         GROUP  BY id),
     other_numbers
     AS (SELECT id,
                String_agg(phone_object ->> 'Number', ',') AS phone_number
         FROM   phone_numbers
         WHERE  phone_object ->> 'Type' <> 'Mobile'
         GROUP  BY id)
SELECT p.*,
       mob.mobile_number mobile_phone_number,
       oth.phone_number  unformatted_phone_numbers,
       eml.email_id      email_addresses
FROM   persons p
       left join email_aggregated eml
              ON p.id = eml.id
       left join other_numbers oth
              ON p.id = oth.id
       left join mobile_numbers mob
              ON p.id = mob.id

This gives me the required result:

I came up with this query intuitively. I don't know if there is a better way to do this. Any comments will be appreciated.


texts: Parsing data from XML in C#, filtering, categorizing in LINQ, displaying on Chart control

texts:
This is my sample XML file:

<?xml version="1.0" encoding="utf-8"?>
<receipts>
  <receipt id="F66BF89E-1070-4E02-9B98-B934A66D0E16" year="2014" month="9" day="17" place="Place#1">
    <purchase name="Coca-Cola" quantity="1" price="3.99" category="Drinks" />
    <purchase name="Watermelon" quantity="1" price="1.98" />
    <purchase name="Water" quantity="1" price="1.49" category="Drinks" />
  </receipt>
  <receipt id="13ECD7F9-F639-4E65-9C80-9E1A8C2E305B" year="2014" month="9" day="17" place="Place#1">
    <purchase name="Sweets" quantity="1" price="3.98" category="Sweets" />
    <purchase name="Water" quantity="1" price="1.99" category="Drinks" />
    <purchase name="Flour" quantity="1" price="1.99" />
    <purchase name="Bread" quantity="1" price="1.19" />
    <purchase name="Milk" quantity="1" price="1.98" category="Drinks"/>
    <purchase name="Potatoes" quantity="0.345" price="1.49" />
  </receipt>
</receipts>

And this is my approach to parsing, filtering, categorizing and displaying it:

// load XML
XElement xmlReceipts = XElement.Load(@".\receipts.xml");

// create objects from XML
List<Receipt> receipts = new List<Receipt>();

foreach (var xmlReceipt in xmlReceipts.Elements("receipt"))
{
    Guid id = new Guid(xmlReceipt.Attribute("id").Value);
    string place = xmlReceipt.Attribute("place").Value;
    int year = Int32.Parse(xmlReceipt.Attribute("year").Value);
    int month = Int32.Parse(xmlReceipt.Attribute("month").Value);
    int day = Int32.Parse(xmlReceipt.Attribute("day").Value);

    List<ProductLine> products = new List<ProductLine>();

    foreach (var xmlProduct in xmlReceipt.Elements("purchase"))
    {
      string name = xmlProduct.Attribute("name").Value;
      string quantity = xmlProduct.Attribute("quantity").Value;
      string price = xmlProduct.Attribute("price").Value;
      string category = xmlProduct.Attribute("category") == null ? "(no category)" : xmlProduct.Attribute("category").Value;
      products.Add(new ProductLine(name, quantity, price, category));
    }
    receipts.Add(new Receipt(id, place, year, month, day, products));
}

// filter to this month's receipts
var receiptsFiltered = from receipt in receipts
                 where receipt.Date.Year == DateTime.Now.Year &&
                 receipt.Date.Month == DateTime.Now.Month
                 select receipt.Products as List<ProductLine>;

// flatten lists of receipts and products
var productsFiltered = from products in receiptsFiltered
                 from product in products
                 select new { Name = product.Name, Price = product.Price, Quantity = product.Quantity, Category = product.Category };

// group products by category
var productsByCategory = from product in productsFiltered
                 group product by product.Category;

// calculate totals per category
Dictionary<string, double> categoriesTotals = new Dictionary<string, double>();

foreach (var category in productsByCategory)
{
    double totalSum = 0;

    foreach (var product in category)
    {
      totalSum += product.Quantity * (double)product.Price;
    }

    categoriesTotals.Add(category.Key, totalSum);
}

// show data on chart
chart1.Series[0].Points.DataBindXY(categoriesTotals.Keys, categoriesTotals.Values);

Is there a way to simplify it? I tried to use XML to LINQ or linking XML directly to Chart but I couldn't manage grouping before flattening the lists.

Sources:

https://stackoverflow.com/a/6429081/1813219
https://stackoverflow.com/a/8135087/1813219
https://stackoverflow.com/a/7325306/1813219