texts:
I am fully aware that Qt is quite good with handling ownership in its object trees. The usual pattern seems to be to use a raw new, assigning the result to a raw pointer and then giving up the ownership with some widget->add(...) call.

This does not seem C++11/C++14, or modern, or RAII-style to me -- especially not in the light of the new C++ Core guidelines and the Guidelines Support library (GSL).

I started using unique_ptr to be on the safe side during set-up. The widget->add(...) then  gets the unique_ptr::release()-result. So if anything goes awry it is still sure there is no leak. But because after release() the content of the unique_ptr is nullptr I stored its content non-owning (an "alias") in a separate variable for later use (like conntect and other method calls).

That looks quite ok to me in simple cases. But when I designed my first own Widget class I had a lot of boiler-plate code around all this unique_ptr/non-owning-alias.

Here is my header file:

// 005-my-window/my_window.hpp
#ifndef MY_WINDOW_HPP
#define MY_WINDOW_HPP
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QObject>
class MyWindow : public QWidget {
    Q_OBJECT
public:
    MyWindow(QWidget* parent = nullptr);
private: // nicht selbst Besitzer dieser QWidgets:
    QLabel* label_ = nullptr;
    QPushButton* button0_ = nullptr;
    QPushButton* button1_ = nullptr;
    QVBoxLayout* layout_ = nullptr;
    int cnt_ = 0; // zählt die Klicks mit
private slots:
    void setText();
};
#endif // MY_WINDOW_HPP

And here the implementation:

// 005-my-window/my_window.cpp
#include "my_window.hpp"
#include <QApplication>
#include <memory>
MyWindow::MyWindow(QWidget *parent)
    : QWidget{parent}
{
    auto label = std::make_unique<QLabel>("old text");
    label_ = label.get();
    auto button0 = std::make_unique<QPushButton>("Increment");
    button0_ = button0.get();
    auto button1 = std::make_unique<QPushButton>("Quit");
    button1_ = button1.get();
    auto layout = std::make_unique<QVBoxLayout>(this);
    layout_ = layout.get();
    layout->addWidget(button0.release());
    layout->addWidget(button1.release());
    layout->addWidget(label.release());
    setLayout(layout.release());
    connect( button0_, SIGNAL( clicked() ), this, SLOT( setText() ) );
    connect( button1_, SIGNAL( clicked() ), qApp, SLOT( quit() ) );
}
void MyWindow::setText() {
    QString msg{"Label updated "};
    msg.append(QString{}.setNum(++cnt_));
    msg.append(" times");
    label_->setText(msg);
}

Well, I need the non-owning raw pointer members to the QWidgets for later use, obviously. But in the constructor I use my safe RAII unique_ptr-machinery to initialize them. Disadvantages:

quite some boiler-plate per item for initialization
initialization not done in c'tors init-section
members are first ini'd with nullptr and later re-assigned with actual values.

Therefore I am only 70% satisfied with this code.

Is there a more comprehensive way to init Qt5 Widgets in a safe, modern RAII manner in C++14?


texts:
When I need to get maximum value of A, B, and C, then I would write like:

val = A;
val = max(val, B);
val = max(val, C);

But, in this case, I need to write two "val" in the one line. And, it is cumbersome if the "val" is more complex like "val[0][1][2].element"... If it is adding value, I can write like "val += B" without writing "val" twice in the line.

I can make macro like:

#define MAXEQ(A,B) (A) = max((A), (B))

But, it looks not very intuitive.

Is there any smarter way to write these things ?


texts:
I have this WCF data service class and I believe it is doing a lot:

[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class PetSuppliesRelationalData : EntityFrameworkDataService<PetSuppliesEntities>
{
    private string _TenantID
    {
        get
        {
            return HttpContext.Current.User.Identity.Name;
        }
    }

    public static void InitializeService(DataServiceConfiguration config)
    {
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        config.UseVerboseErrors = true;

        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

        config.SetEntitySetAccessRule("Categories", EntitySetRights.All);
        config.SetEntitySetAccessRule("Products", EntitySetRights.All);

        config.SetEntitySetAccessRule("RealErrors", EntitySetRights.None);
        config.SetEntitySetAccessRule("OtherDiagrams", EntitySetRights.None);
        config.SetEntitySetAccessRule("Favourites", EntitySetRights.None);
        config.SetEntitySetAccessRule("Auditing", EntitySetRights.None);

        config.SetEntitySetAccessRule("Compaines", EntitySetRights.None);

        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
    }

    protected override void OnStartProcessingRequest(ProcessRequestArgs args)
    {
        base.OnStartProcessingRequest(args);
        ThrowIfNotAuthenticated();
    }

    protected override void HandleException(HandleExceptionArgs args)
    {
        LoggingFramework.LogError("Exception ", args.Exception);
        base.HandleException(args);
    }

    private static void ThrowIfNotAuthenticated()
    {
        var identity = HttpContext.Current.User.Identity;
        if (identity == null || !identity.IsAuthenticated)
        {
            throw new Exception("Not Authenticated");
        }
    }

    #region Query Intercepters

    [QueryInterceptor("Table1")]
    public Expression<Func<Table1, Boolean>> OnQueryTable1()
    {
        return x => x.TenantID == _TenantID;
    }

    // one for each table in db

    #endregion

    #region Change Interceptors

    [ChangeInterceptor("Table1")]
    public void OnChangeTable1(Table1 data1, UpdateOperations operations)
    {
        // check if user is authorized etc..
        switch (operations)
        {
            case UpdateOperations.Add:
                break;
            case UpdateOperations.Change:
                break;
            case UpdateOperations.Delete:
                break;
            case UpdateOperations.None:
                break;
        }
    }

    // one for each table in db

    #endregion
}

I'm thinking moving out Query and Change interceptors out of this class but not sure if this will be a good move. I also don't know if it is possible, but the code is working as it is, so any improvement would help.


texts:
I've been toying around with writing a decentralized, P2P application in REBOL 2, and one of the things I need to do is generate a universally unique identifier for users. I have written a function that generates a Version 4 UUID that is compliant with RFC 4122, as best as I can tell.

I have a few questions ...

Is it compliant with RFC 4122? Have I missed anything?
I am fairly new to REBOL. Is there a simpler approach I could have taken with the code? Am I using best practices in the language?
The code picks random integers and does some bitwise operations using integers too. Is it correct to do things this way? All the online examples I've come across use bytes directly and does the bitwise operations using hexidecimal numbers. REBOL doesn't support bytes directly and so that's why I've coded things this way. It appears to work correctly, but I have this nagging feeling that maybe I've overlooked something at a lower level.

Here is the REBOL 2 code

REBOL []

; IMPORTANT - random/seed now/precise must be called before running this function
; Also, it must only be seeded ONCE per application process or duplicates will occur
makeUUID: func [
    "Generates a Version 4 UUID that is compliant with RFC 4122"
    /local data
][
    ; generate 16 random integers

    ; Note: REBOL doesn't support bytes directly
    ; and so instead we pick numbers within the
    ; unsigned, 8-bit, byte range (0 - 255)

    ; Also random normally begins the range at 1,
    ; not 0, and so -1/256 allows 0 to be picked
    data: collect [loop 16 [keep -1 + random/secure 256]]

    ; set the first character in the 7th "byte" to always be 4
    data/7: data/7 and 15 or 64

    ; set the first character in the 9th "byte" to always be 8, 9, A or B
    data/9: data/9 and 63 or 128

    ; convert the integers to hexadecimal
    data: enbase/base to binary! data 16

    ; add the hyphens between each block
    data: insert skip data 8 "-"
    data: insert skip data 4 "-"
    data: insert skip data 4 "-"
    data: insert skip data 4 "-"

    head data
]

random/seed now/precise
for num 1 30 1 [print makeUUID]
halt


texts: Small BM25+ implementation for probibalistic result ranking

texts:
I came up with this small implementation of an Okapi BM25+ ranker using Ruby. I cooked it up in a very short time so it's very simple but I'm trying to think whether there's a better way to write it. In particular, I'm wondering if I should have something like a Ranker class -- intuitively I feel as though I should but it seems to work fine this way too.

The two classes used are Document and Collection. A Collection can contain many Documents. Very simple.

document.rb

class Document
  attr_accessor :body, :rank

  def initialize(params={:body=>'', :rank=>nil})
    @body = params[:body]
    @rank = params[:rank]
  end

  def length
    @body.length
  end

  def include?(term)
    @body.include?(term)
  end

  def term_freq(term)
    # Will need something better here to clean out the document.
    # This is temporary ;)
   @body.gsub(/[^\s\p{Alnum}\p{Han}\p{Katakana}\p{Hiragana}\p{Hangul}]/,'')
    .downcase
    .split
    .count(term)
  end
end

collection.rb

class Collection

  def initialize(params={:docs=>[], :query=>nil})
    @docs = params[:docs]
    @query = params[:query]
  end

  def containing_term(term)
    total = 0
    @docs.each do |doc|
      total += 1 if doc.include?(term)
    end
    total
  end

  def avg_dl
    doc_lengths = 0
    @docs.each do |doc|
      doc_lengths += doc.length
    end
    doc_lengths / total_docs
  end

  def total_docs
    @docs.size
  end

  def idf(term)
    numerator = total_docs - containing_term(term) + 0.5
    denominator = containing_term(term) + 0.5
    Math.log(numerator / denominator)
  end

  def bm25(params={:k => 1.2, :b => 0.75, :delta => 1.0})
    @k = params[:k]
    @b = params[:b]
    @delta = params[:delta]

    @docs.each do |doc|
      score = 0
      dl = doc.length
      query_terms = @query.split

      query_terms.each do |term|
        dtf = doc.term_freq(term)
        numerator = dtf * (@k + 1)
        denominator = dtf + @k * (1 - @b + @b * (doc.length / avg_dl))
        score += idf(term) * (numerator/denominator) + @delta
      end
      doc.rank = score
    end
    @docs
  end

  def sort_by_rank
    @docs.sort! {|a, b| a.rank <=> b.rank}
  end
end


texts:
I have a 9-dimensional signal (as a csv from this Gist) that looks like this:

A signal peaks every 30 steps. I want to get the maximum values of the peaks in that 30 second window. Here's what I've hacked together so far, where sig is the signal loaded from the csv file and max_res is the desired result:

trial_num = 8
dims = 9
step = 30
max_res = np.zeros(trial_num)

tmp = sig.reshape((trial_num, step, dims))
max_dim = np.argmax(np.sum(tmp, axis=1), axis=1)

sing_dim = np.zeros((trial_num, step))
for t_i in range(trial_num):
    sing_dim[t_i] = tmp[t_i, :, max_dim[t_i]]

max_res = np.max(sing_dim, axis=1)

How can I replace the for-loop with a vectorized operation?


texts: Handling conditional logic inside controller actions

texts:
I am looking for best practice in handling conditions inside the controller actions in ASP.NET MVC:

public ActionResult Edit(int Id = 0)
{
   var Item = _todoListItemsRepository.Find(Id);
   if (Item == null)
      return View("NotFound");
   if (!Item.IsAuthorized())
      return View("NotValidOwner");

   return View("Edit", Item);
}

The above two ifs are used in other actions inside the controller. So, in order not to repeat these conditions in all the actions. I have used the below approach:

[HttpGet]
[Authorize]
[ModelStatusActionFilter]
public ActionResult Edit(int Id = 0)
{
    var Item = _todoListItemsRepository.Find(Id);
    return View("Edit", Item);
}

public class ModelStatusActionFilterAttribute : ActionFilterAttribute
{
    private readonly ITodoListItemsRepository _todoListItemsRepository;
    public ModelStatusActionFilterAttribute()
        : this(new TodoListItemsRepository())
    {

    }
    public ModelStatusActionFilterAttribute(ITodoListItemsRepository     todoListItemsRepository)
    {
        _todoListItemsRepository = todoListItemsRepository;
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        try
        {
            var Id = Convert.ToInt32(filterContext.RouteData.Values["Id"]);
            var Item = _todoListItemsRepository.Find(Id);
            if (Item == null)
            {
                filterContext.Result = new ViewResult() { ViewName = "NotFound" };
            }
            else if (!Item.IsAuthorized())
            {
                filterContext.Result = new ViewResult() { ViewName = "NotValidOwner" };
            }
        }
        catch
        {

        }
    }
}

I am unsure if this is the best practice in handling such scenarios. Could someone please advise?


texts: Give me some change as asked in interview

texts:
Description:

The goal in this problem is to find the minimum number of coins needed
to change the input value (an integer) into coins with denominations 1,
5, and 10
The input consists of a single integer m.
1≤m≤103
Output the minimum number of coins with denominations 1, 5, 10 that changes m.

Code:
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Main
{

  public static int CountChange(int m) {
    if (m <= 0) return 0;

    int[] denomenations = new int[]{10, 5, 1};
    int change = 0;

    for (int i : denomenations) {
      while (m - i >= 0) {
        m -= i;
        change++;
      }
    }

    return change;
  }

    public static void main (String[] args) throws java.lang.Exception
    {
      // edge cases
      System.out.println(CountChange(0));  // 0
      System.out.println(CountChange(-1)); // 0
      System.out.println(CountChange(Integer.MIN_VALUE)); // 0
      System.out.println(CountChange(Integer.MAX_VALUE));

      System.out.println(CountChange(1));  // 1 = 1
      System.out.println(CountChange(2));  // 2 = 1 + 1
      System.out.println(CountChange(5));  // 1 = 5
      System.out.println(CountChange(10)); // 1 = 10
      System.out.println(CountChange(28)); // 6 = 10 + 10 + 5 + 1 + 1 + 1
    }
}

Questions

This seems exponential algorithm to me but what is the correct approach for finding the running time of this algorithm?
I put some thoughts on testing strategies in this problem, since the input is integer I had few number of edge cases also the problem description doesn't cover edge cases (e.g.: maximum integer) but then also I thought to test it, is this the correct approach?
For m = 0 the algorithm works fine but still I gave a guard condition for readability, don't know if this is a good strategy.
I think that a better algorithm can be developed and suggestions are welcome.


texts: File Output given repeated small operations

texts:
I want to write a file which contains values for each cell of a CFD computation. This will be an input file to the program which runs the computation.

Currently, the most dubious section of my code looks like:

for (int y = 0; y < ycells; y++)
{
    double yPos = yMin + (cellToY * (y + 0.5));
        for (int x=0; x<xcells; x++)
        {
            double deltaY = yProfileHeight[x] - yPos;
            if (deltaY < -cellToY)
            {
                file << "1\n";
            }
            else if (deltaY > cellToY)
            {
                file << "0\n";
            }
            else
            {
                double value = (0.5 + (-0.5 * (deltaY / cellToY)));
                file << value << "\n";
            }
        }
    }
}

For most of the file these if checks are going to be slow/useless - since depending on the value of yPos, they will all evaluate to true/false for large regions.

I can rewrite it like this (with appropriate min/max functions):

for (int y = 0; y < ycells; y++)
{
    double yPos = yMin + (cellToY * (y + 0.5));
    if (yPos < yHeightMin)
    {
        for (int x=0; x<xcells; x++)
        {
            file << "0\n";
        }
    }
    else if (yPos > yHeightMax)
    {
        for (int x=0; x<xcells; x++)
        {
            file << "1\n";
        }
    }
    else
    {
        for (int x=0; x<xcells; x++)
        {
            double deltaY = yProfileHeight[x] - yPos;
            if (deltaY < -cellToY)
            {
                file << "1\n";
            }
            else if (deltaY > cellToY)
            {
                file << "0\n";
            }
            else
            {
                double value = (0.5 + (-0.5 * (deltaY / cellToY)));
                file << value << "\n";
            }
        }
    }
}

Now my if conditions are evaluated less frequently, but I'm still left with segments like

for (int x=0; x<xcells; x++) // where xcells is ~ 1-10k
{
    file << "1\n";
}

Can I rewrite this in a way that doesn't require several thousand separate (identical) writes to a single file?


texts: Check if all objects have the property value of all other objects

texts:
I have a list of objects. These objects have a processname, amount and a date. I need every object to have all dates (if it doesnt exist add a new one with amount 0). So if I have 2 processnames: 'Inflate' and 'Deflate' and they have different dates: 'Inflate':12-01-2017 and 'Deflate': 13-01-2017. I need them to have the other object's dates.

I have the following code but it feels devious:

        HashSet<Date> dates = new HashSet<>();
        HashSet<String> processes = new HashSet<>();

        //Get all the unique values from the objects. processAmounts is the list of objects
        for (ProcessAmount processAmount : processAmounts) {
            dates.add(processAmount.getDate());
            processes.add(processAmount.getProcessName());
        }

        //Loop through processnames
        for (String s : processes) {
            //Loop through all the unique dates
            for(Date date : dates) {
                //loop through the objects we have and check if the date exists.
                boolean dateFound = false;
                for(ProcessAmount processAmount : processAmounts) {
                    if(processAmount.getProcessName() != null && processAmount.getProcessName().equals(s)) {
                        if(processAmount.getDate().equals(date)) {
                            dateFound = true;
                        }
                    }
                }

                //If the date is not found add a new object with amount 0
                if(!dateFound) {
                    processAmounts.add(new ProcessAmount(date, 0, s));
                }
            }
        }

It might be a bit unclear for some people so if you don't understand I will try to explain it another way.


texts:
Background

I wrote my_length class and some code. my_length can be stringified using << operator, and main() tests this.

Questions

I think operator<< can be refactored. How can I rewrite operator<< of my_length, and make it better code?
How can I make rest of code better?

Code

#include <vector>
#include <string>
#include <cstdint>
#include <iostream>

class my_length {
  int id;
  std::string name;
  uint64_t v;     // unit is 'mm'
  bool fmt_auto;

  public:
  my_length (int id, std::string name, uint64_t v)
    : id{id}, name{name}, v{v}, fmt_auto(false) {}
  friend std::ostream &operator<<(std::ostream &out, const my_length &l) {
    out << l.id << "/" << l.name << " : ";
    if (!l.fmt_auto) {
        return out << l.v << "mm";
    } else {
        if (l.v<10)
            return out << l.v << "mm";
        else if (l.v<1000)
            return out << double(l.v)/10 << "cm";
        else if (l.v<1000000)
            return out << double(l.v)/1000 << "m";
        else
            return out << double(l.v)/1000000 << "km";
    }
  }
  void set_fmt_auto(bool b) {fmt_auto = b;}
};

bool need_fmt_auto(int x) {
  return (x%2) != 0;
}

int main() {
  std::vector<my_length> lengths;
  my_length l{0, "a", 1};
  lengths.push_back(l);
  uint64_t val = 17;
  for (int i=1; i<10; i++) {
    my_length l{i, std::string(1, 'a'+i), val};
    lengths.push_back(l);
    val *= 10;
  }
  for (int i=0; i<lengths.size(); i++) {
    if (need_fmt_auto(i)) {
        lengths[i].set_fmt_auto(true);
        std::cout << "fmt_auto: ";
    }
    std::cout << lengths[i] << "\n";
  }
}


texts:
Background:  I'm trying to learn basic OOP with Python.  I have this program I wrote to help my son practice math problems.  It does addition, subtraction, multiplication, and division.  He can choose easy, medium, or hard for each operator.

Here's an excerpt of the code.  It's the "easy" addition function. (The "medium" and "hard" functions simply choose bigger random numbers.)

def addition_problems_1():
    global name
    score = 0

    while score < 30:
        a = randint(1,10)
        b = randint(1,10)
        sum = a + b

        answer = int(raw_input("%i + %i = " % (a, b)))

        if answer == sum:
            score = score + 1
            print "Good job. Current score is %d" % score

        elif answer != sum:
            print "Oops, the correct answer is %i. Try another one." % sum

    print "Good job, %s. You passed this course!" % name
    enter_lobby()

And here's the "easy" Subtraction function.  (The multiplication and division functions are very similar.)

def subtraction_problems_1():
    global name
    score = 0

    while score < 30:
        a = randint(1,10)
        b = randint(1,10)

        if a > b:
            sum = a - b
            answer = int(raw_input("%i - %i = " % (a, b)))
        else:
            sum = b - a
            answer = int(raw_input("%i - %i = " % (b, a)))

    if answer == sum:
        score = score + 1
        print "Good job. Current score is %d" % score

    elif answer != sum:
        print "Oops, the correct answer is %i. Try another one." % sum

    print "Good job, %s. You passed this course!" % name
    enter_lobby()

My Question:  Could this script be shortened and/or simplified by re-writing it in OOP style?  If so, can you show me an example of what that might look like?


texts:
The following is a struct to extract a value between named XML element tags. Though it works, I feel there is functional approach in Rust that I am missing. Any other tips on Rust preferred styling are also appreciated.

pub struct XmlDoc {
    doc: String,
}

impl XmlDoc {
    pub fn new(doc: String) -> XmlDoc {
        XmlDoc { doc }
    }
    pub fn get_value(&self, element: &str) -> String {
        let begin_tag = format!("<{}>", element);
        let end_tag = format!("</{}>", element);
        let value_begin = self.doc.find::<&str>(begin_tag.as_str()).unwrap();
        let value_end = self.doc.find::<&str>(end_tag.as_str()).unwrap();
        self.doc[value_begin + begin_tag.len()..value_end].to_string()
    }
}

mod tests {
    use super::*;

    #[test]
    fn get_value() {
        let xml = XmlDoc::new("<element>value</element>".to_string());
        let value = xml.get_value("element");
        assert_eq!(value, "value".to_string(), "{}", value);
    }
}

Note, I understand that XML libraries for Rust already exist. This is intended as a learning tool for working with string manipulations inside vanilla Rust.

Edit:
I thought using regex to parse XML may be a good idea. I was wrong.


texts: Javascript: Canvas drawing - storing mouse coordinates

texts:
I have a small JS application that allows a user, after clicking on a canvas, to draw a picture.

Once the user clicks the mouse, the user is allowed to drag the mouse wherever they want within the canvas and a line will be drawn from where they started moving the mouse to where the mouse stopped.

Only by clicking again will the drawing cease.

The code I have for this is below, and one concern of mine is how I'm storing the coordinates of the mouse's position each time it moves.

var draw = false;
var coords = [];
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.addEventListener('click', function (event) {
    coords = [];
    draw = !draw;
});
canvas.addEventListener('mousemove', function (event) {
    if (draw) {
        context = canvas.getContext("2d");
        var coord = { 'x': event.x - this.offsetLeft, 'y': event.y - thisoffsetTop };
        coords.push(coord);
        var max = coords.length - 1;
        if (typeof coords[max - 1] !== "undefined") {
            var curr = coords[max], prev = coords[max - 1];
            context.beginPath();
            context.moveTo(prev.x, prev.y);
            context.lineTo(curr.x, curr.y);
            context.stroke();
        }
    }
});

I have a feeling that I could be storing the coordinates more efficiently, rather than just add them to an ever-increasing Array. Is this the right approach, or is there a more efficient way of handling this sort of storage?


texts:
My application state is represented by a string of numbers and I'm trying to encode the string so that it is as small as possible (ie. fewest number of characters). An example string would be: 133223333302302040

I realized that most of these strings consist of number pairs containing 0, 1, 2, 3 (4 and 5 also exist but are rare). I decided to replace the most common number pairs with letters, shortening my encoded string by ~50%

I have a function that returns the mapping:

function getValueMap(lettersFirst = false) {
  const map = {
    '00': 'a',
    '01': 'b',
    '02': 'c',
    '03': 'd',
    '10': 'e',
    '11': 'f',
    '12': 'g',
    '13': 'h',
    '20': 'i',
    '21': 'j',
    '22': 'k',
    '23': 'l',
    '30': 'm',
    '31': 'n',
    '32': 'o',
    '33': 'p'
  };

  if (lettersFirst) {
    return Object.fromEntries(Object.entries(map).map(([k, v]) => [v, k]));
  } else {
    return map;
  }
}

To encode, I iterate through every pair of input numbers, check if it is in the map, and if so, add the letter to the encoded output. For odd length inputs I simply remove the last digit, dont encode it, and simply append the number to the output string untouched:

encode(text) {
  const map = getValueMap();
  let values;
  let suffix = '';

  if (text.length % 2 !== 0) {
    suffix = text.charAt(text.length - 1);
    values = text.slice(0, -1);
  } else {
    values = text;
  }

  let encoded = '';
  for (let i = 0; i <= text.length - 2; i += 2) {
    if (map[values[i] + values[i + 1]]) {
      encoded += map[values[i] + values[i + 1]];
    } else {
      encoded += values[i] + values[i + 1];
    }
  }
  encoded += suffix;
  return encoded;
}

To decode, iterate through the string, if its a letter, add the corresponding number pair to the decoded output. If its already a number, simply add the number instead:

decode(encoded) {
  const map = getValueMap(true);
  let decoded = '';

  for (let i = 0; i < encoded.length; i++) {
    if (encoded[i].toLowerCase() !== encoded[i].toUpperCase()) {
      decoded += map[encoded[i]];
    } else {
      decoded += encoded[i];
    }
  }

  return decoded;
}

Some example inputs and outputs:

Encode:
13223233202200252044 -> hkopika25i44

Decode:
holppcmi40 -> 133223333302302040

Is there a more straightforward way to do this? My implementation feels unnecessarily obtuse. For example, do I actually need to create a map/reverse map when I could maybe rely on indexing the pair array or alphabet instead? Is there a more elegant way to iterate over pairs of numbers? Or to build up the final encoded/decoded form without appending to a string?


texts: automating to push changes to github for multiple repos using python

texts:
This Python script does following activities:

clone repo, as provided from the list
creating a new branch "jenkinsMigrate"
rename Jenkinsfile to Jenkinsfile.migrate
push code to GitHub in a new branch.

NOTE: credentials were configured already.

import git
import os
import subprocess

gitUrl = "https://*****"
cwd = "*****"

with open("migrateList.txt", "r") as file:
    for line in file:
        #configure gitUri for each repository
        gitUri = gitUrl + line.strip() + ".git"
        try:
            global repo
            repo = git.Repo.clone_from(gitUri, cwd + line.strip())
        except:
            print(" directory already available")
        os.chdir(cwd + line.strip())

        #checkout new branch for migration
        repo.git.checkout('-b', "jenkinsMigrate")

        subprocess.call(["git", "mv", "Jenkinsfile", "Jenkinsfile.migrate"])
        repo.git.add(update=True)
        repo.index.commit("jenkins migration")
        origin = repo.remote(name='origin')

        #push new branch to github
        subprocess.call(["git","push", "--set-upstream", "origin", "jenkinsMigrate"])
        subprocess.call(["cd", ".."])

Sample text file:

$ cat migrateList.txt
repo1
repo2
repo3
repo4

This is a working code, but all I am looking for is to maintain consistency in the commands that I use. eg: For some of the git commands that I have used are from gitpython module where as others are invoked with shell commands. Apart from these any other suggestions are welcome.

Thanks!

UPDATE 1: python - 2.7.10

gitPython module


texts: Find number of whole weeks between months in the same year

texts:
I wrote a class to return the number of whole weeks between months in the same year. I need suggestions on my code.

public int year;
public String m1;
public String m2;

public Solution(int Y, String A, String B) throws ParseException {
    this.year = Y;
    this.m1 = A;
    this.m2 = B;

    String dateOneInput = year + "-" + m1;
    String dateTwoInput = year + "-" + m2;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM");

    //DATE 1
    Calendar c1 = Calendar.getInstance();
    c1.setTime(formatter.parse(dateOneInput));
    //Get first monday of the month
    c1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    c1.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);

    System.out.println("Date 1 : " + c1.getTime());

    //DATE 2
    Calendar c2 = Calendar.getInstance();
    c2.setTime(formatter.parse(dateTwoInput));
    //Get last sunday of the month
    c2.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    c2.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1);

    System.out.println("Date 2 : " + c2.getTime());

    //Difference in weeks
    int weeks = c2.get(Calendar.WEEK_OF_YEAR) - c1.get(Calendar.WEEK_OF_YEAR);
    System.out.println("Number of weeks :" + (1 + weeks));

}

/**
 * @param args the command line arguments
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException {
    Solution s = new Solution(2012, "June", "July");
}


texts: First index of number in the arithmetic progression (which is multiple of prime)

texts:
Things to deal with this problem.

  An infinite Arithmetic progression.
  A prime number. - p.
  The starting number of an Arithmetic Progression. - a.
  Common difference in the arithmetic progression given to him. - d.

  You have to print the first index
  of a number in that Arithmetic Progression, which is a multiple of the
  given prime number, p.

  Input format: The first line contains a number, tc, denoting the
  number of test cases. After that follow tc number of test cases, each is 2 lines - the first contains two integers, a and d -
  a depicts the first term in the AP, d depicts the common difference.
  The next line contains the prime number.

  Output format: You have to print the FIRST index (0-based) of the
  multiple of the given prime number in the given AP. If no such element
  exists in this infinite AP, then print -1.

  Constraints: 0 <= a, d, <= 10^18 1 <= p <= 10^9

My code:

public static void main(String[] args) throws NumberFormatException, IOException{
StringBuilder output = new StringBuilder();
        BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
            int noOfTestCaseT=Integer.parseInt(reader.readLine().trim());

            while (noOfTestCaseT != 0){
                noOfTestCaseT--;
                String[] inputAandD = reader.readLine().split(" ");
                long firstElement = Long.parseLong(inputAandD[0].trim());
                long commonDifference = Long.parseLong(inputAandD[1].trim());
                long primeNo = Long.parseLong(reader.readLine().trim());
                firstElement %= primeNo;
                commonDifference %= primeNo;
                int result = 0;
                if(commonDifference == 0) output.append(-1);
                else if (firstElement == 0) output.append(0);
                else{
                    long inverseMod =  getPowerValue(commonDifference, primeNo);
                    result = (int) ((inverseMod * (primeNo-firstElement)) % primeNo) ;
                    output.append(result);
                }
                output.append("\n");

            }

            System.out.println(output);
    }

    private static long getPowerValue(long base, long primeNo) {
        long exp = primeNo -2;
        long powerResult = 1;
        while (exp > 0){
            if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo;
            base = (base * base) % primeNo;
            exp = exp >> 1 ;
        }
        return powerResult;
    }

How could I can optimize this code further so that its performance improves (though the solution is within the given time limit and I really want to know what are the possible improvement I can make)?


texts: Inserting a record into MySQL with a timestamp

texts:
I'm starting with PHP so I can save data to a MySQL database. I read a lot and it seems the "escape" strings is not so safe.

This is my code:

<?php
session_start();
date_default_timezone_set('America/Argentina');
require_once("config/db.php");
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
mysqli_select_db($link, DB_NAME);
$tildes = $link->query("SET NAMES 'utf8'");

$NombreOferta = mysqli_real_escape_string($link,(strip_tags($_POST['NombreOF'], ENT_QUOTES)));
$CantidadArt = mysqli_real_escape_string($link,(strip_tags($_POST['CantidadArt'], ENT_QUOTES)));
$PrecioOf = mysqli_real_escape_string($link,(strip_tags($_POST['PrecioOf'], ENT_QUOTES)));
$NomComercio = mysqli_real_escape_string($link,(strip_tags($_POST['PrecioOf'], ENT_QUOTES)));
$DirComercio = mysqli_real_escape_string($link,(strip_tags($_POST['PrecioOf'], ENT_QUOTES)));
//$userid = "1";
$fecha =date("Y-m-d");
$hora = date("G:i:s
", time());

mysqli_query($link, "INSERT INTO ofertas (nombreoferta, cantidadarticulos, precio,user_id,fecha,hora) VALUES('" . $NombreOferta . "', '" . $CantidadArt . "', '" . $PrecioOf . "', '" . $_SESSION['user_id'] . "', '" . $fecha . "', '" . $hora .  "');");

mysqli_close($link);
//echo "title"
header("Location: OfertaGrabada.html");
//echo $fecha;
?>

So, is this ok?


texts: Loading .txt file content and filename into pandas dataframe

texts:
Is there a better way to read in

the name of a textfile and
the content of a text file into a dataframe?

(Or is my implementation even okay?) Can I avoid storing the data in lists?

path =r'.../test_age7'
allFiles = glob.glob(path + "/*.txt")
df_7 = pd.DataFrame()  # create empty DF
stories = []
filenames = []
for file_ in allFiles:
    with open(file_) as f:
        textf = " ".join(line.strip() for line in f)
    stories.append(textf)
    filenames.append(os.path.basename(file_[0:-4]))    # extract filename without .txt

df_7["filename"] = filenames
df_7["stories"] = stories
df_7["age"] = path[-1]


texts:
Description of the problem:

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem class:
ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.
bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.

Below is my code, I would appreciate any suggestions on how to improve the code.
#include <iostream>

class ParkingSystem {

public:
    ParkingSystem(int big, int medium, int small) :
    m_big_max(big),
    m_medium_max(medium),
    m_small_max(small),
    m_big_curr(0),
    m_medium_curr(0),
    m_small_curr(0)
    {}

    bool addCar(int carType) {
        if (carType == 1) {
            // big car
            if (m_big_curr == m_big_max) {
                return false;
            } else {
                m_big_curr++;
            }
        } else if (carType == 2) {
            // medium car
            if (m_medium_curr == m_medium_max) {
                return false;
            } else {
                m_medium_curr++;
            }
        } else {
            // small car
            if (m_small_curr == m_small_max) {
                return false;
            } else {
                m_small_curr++;
            }
        }

        return true;
    }

private:
    int m_big_max;
    int m_medium_max;
    int m_small_max;

    int m_big_curr;
    int m_medium_curr;
    int m_small_curr;

};

int main() {

    ParkingSystem parking_system(1, 1, 0);

    std::cout << "parking_system.addCar(1) " << parking_system.addCar(1) << std::endl;
    std::cout << "parking_system.addCar(2) " << parking_system.addCar(2) << std::endl;
    std::cout << "parking_system.addCar(3) " << parking_system.addCar(3) << std::endl;
    std::cout << "parking_system.addCar(1) " << parking_system.addCar(1) << std::endl;

    return 0;
}


texts: Workflow class with Start(), Continue(), and Resume() methods

texts:
I have a session class that needs to be setup based on different needs of the client code. Sometimes a new session needs to be created, or continued, or resumed (loaded from database after a user has saved their progress and came back).

Right now the client code has to ALWAYS execute Start(), Continue(), or Resume() after instantiating the WorkflowSession class or the instance is useless. Like this:

var workflowSession = new WorkflowSession(Session);
workflowSession.Continue(); // or .Continue() or .Resume()

Should I do a return this; in order to be able to chain?

var workflowSession = new WorkflowSession(Session).Continue();

Or make some type of factory or builder? If so, how?

/// <summary>
/// Manages workflow session persistence.
/// </summary>
public class WorkflowSession
{
    private int workflowPlanId;
    private int dataClipId;
    private HttpSessionStateBase session;
    private WorkflowRepository workflowRepository;
    private DataClipRepository dataClipRepository;
    private StateRepository stateRepository;

    public WorkflowSession(HttpSessionStateBase session)
    {
        this.session = session;
        workflowPlanId = (int)session[SessionKeys.WorkflowPlanId];
        dataClipId = (int)session[SessionKeys.DataClipId];

        dataClipRepository = new DataClipRepository();
        stateRepository = new StateRepository();
        workflowRepository = new WorkflowRepository();
    }

    public SchemaProvider Provider { get; set; }

    public SchemaRoot Root { get; set; }

    public DataClip Clip { get; set; }

    public WorkflowPlan Plan { get; set; }

    public WorkflowContext Context { get; set; }

    public void Continue()
    {
        Clip = dataClipRepository.GetById(dataClipId);
        Plan = workflowRepository.GetById(workflowPlanId);
        Context = ContextFactory.Current.Create(Clip, Plan);
    }

    public void Start(int workflowPlanId, int schemaId)
    {
        Provider = ProviderCache.GetProvider();
        Root = Provider.GetRoot(schemaId);
        Clip = DataClip.Create(Root, Provider);
        Plan = workflowRepository.GetById(workflowPlanId);
        Context = ContextFactory.Current.Create(Clip, Plan);

        Context.CurrentPosition = new WorkflowState(Plan.Id, Plan.Steps.First().Id, TaskStatus.Running);

        dataClipRepository.Save(Clip);
        stateRepository.Save(Context);

        this.workflowPlanId = workflowPlanId;
        this.dataClipId = Clip.Id;
        SetSessionValues();
    }

    public void Resume(int workflowPlanId, int dataClipId)
    {
        Clip = dataClipRepository.GetById(dataClipId);
        Plan = workflowRepository.GetById(workflowPlanId);
        Context = ContextFactory.Current.Create(Clip, Plan);

        this.workflowPlanId = workflowPlanId;
        this.dataClipId = dataClipId;
        SetSessionValues();
    }

    private void SetSessionValues()
    {
        session[SessionKeys.DataClipId] = dataClipId;
        session[SessionKeys.WorkflowPlanId] = workflowPlanId;
    }

    private static class SessionKeys
    {
        public const string WorkflowPlanId = "Workflow.WorkflowPlanId";
        public const string DataClipId = "Workflow.DataClipId";
    }
}


texts:
I was wondering if there are any significant improvements that could be made in order to make the program more concise or efficient, particularly in the findmatch function. However there is a catch: I cannot use strings or array notation; working only with chars and pointer arithmetic.

In short, the program accepts two user inputs: one for the text, and the other for a pattern. Also, the user has a choice of putting "?" chars as "wild" chars that can be treated as any char.The program finds the start char of the pattern in the text input and prints out the remaining chars in the text after the pattern.

#include <stdio.h>

int readline(char* text, int n);
char* findmatch(char* pattern, char* text, int pl, int tl);
void printmessage(char* position, char* text, int pl, int tl);

int main() {
    char text[40], pattern[40], *position;
    int textlength, patternlength;

    printf("Enter text: ");
    textlength = readline(text, 40);
    printf("Enter pattern: ");
    patternlength = readline(pattern, 40);
    position = findmatch(pattern, text, patternlength, textlength);
    printmessage(position, text, patternlength, textlength);
}

int readline(char* text, int n) {
    int i=0;
    for(i;i<n;i++){
        int ic = getchar();
        if(ic == 10)
            break;
        else{
            *(text+i) = ic;
        }
     };
     return i;
}

char* findmatch(char* pattern, char* text, int pl, int tl) {
    int indexp = 0;
    char* position = NULL;
    int x=0;
    for(x; x<tl; x++){
        int pc = *(pattern+indexp);
        int tc = *(text+x);
        if(pc == 63 || pc == tc){
            indexp++;
            if(indexp == pl){
                position = (text+x)-indexp+1;
                break;
            }
            printf("status: pass\n");
        }else{
            indexp = 0;
            printf("status: fail\n");
        }
    }
    return position;
}

void printmessage(char* position, char* text, int pl, int tl) {
    if(position == NULL){
        printf("no match\n");
    }else{
        int p = (position-text)+1;
        printf("The pattern was found at char %d. The remaining text chars are: ", p);
        int i = p+pl-1;
        for(i; i<tl; i++){
            printf("%c", *(text+i));
        }
        printf("\n");
    }
 }


texts: Finding the Nth occurrence of character in string

texts:
I wrote an SQL Server function which returns the substring before the Nth occurrence of a character.

For example:

SELECT dbo.fn_getFirstNthSentence('.', 'hello world.It.is.raining.today', 3)

returns 'hello world.It.Is.' as a result.

The function I wrote looks dirty and slow so I want to optimize it. Any advice to make it clean is appreciated.

CREATE FUNCTION fn_getFirstNthSentence
(
  @TargetStr VARCHAR(MAX) ,
  @SearchedStr VARCHAR(8000) ,
  @Occurrence INT
)
RETURNS varchar(MAX)
AS
BEGIN

    DECLARE @pos INT ,
        @counter INT ,
        @ret INT;

    SET @pos = CHARINDEX(@TargetStr, @SearchedStr);

    IF ( @pos = 0 )
        RETURN @SearchedStr

    SET @counter = 1;

    IF @Occurrence = 1
        SET @ret = @pos;

    ELSE
        BEGIN

            WHILE ( @counter < @Occurrence )
                BEGIN

                    IF(LEN(@SearchedStr) < @pos + 1)
                        RETURN @SearchedStr

                    SELECT  @ret = CHARINDEX(@TargetStr, @SearchedStr,
                                             @pos + 1);
                    IF(@ret = 0)
                        RETURN @SearchedStr
                    SET @counter = @counter + 1;
                    SET @pos = @ret;
                END;
        END;
    RETURN LEFT(@SearchedStr, @ret)
END;


texts:
I have a very simple directive <my-card> that lists out some data.

Example Usage

my-card(ng-repeat="item in parentCtrl.items" item='item')

The only main functionality I have is a button that toggles some additional data.

Here is my directive/controller definition. Should I use the link function instead of creating a controller? The reason I moved the logic into the MyCardCtrl was so that I can easily unit test it.

MyCardCtrl

  function MyCardCtrl() {
    var vm = this;

    this.cardClass = 'my-card-' + vm.item.type;

    this.toggle = function() {
      vm.item.showMore = !vm.item.showMore;
    };

    this.init = function(element) {
      var img = angular.element(element[0].querySelector('.card-bg'));
      img.css('background-image', 'url(' + vm.item.image_url + ')');
    };
  }

myCard Directive

  function myCard() {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'my-card.html'
      scope: {
        item: '='
      },
      link: function(scope, element, attrs, myCardCtrl) {
        myCardCtrl.init(element);
      },
      controller: 'MyCardCtrl',
      controllerAs: 'card',
      bindToController: true
    };
  }

  angular
    .module('components')
    .directive('myCard',      [myCard])
    .controller('MyCardCtrl', [MyCardCtrl]);

myCard template (written in Jade)

 .my-card(ng-class='class.cardClass')
    button(ng-click='card.toggleMeta()')
    .my-card-content(ng-show='card.item.showMore')
      // expose item object
      h1 {{::item.name}}
    .my-card-more(ng-show='!card.item.showMore')
    .my-card-bg


texts:
When you click on a span it enters the value into the input. That works fine, but as you can see the JS code is very big and there must be a better way to do this, but like I said I'm still learning. Maybe someone can give me a pointer in the right direction.

I suppose I have to use a variable somewhere but can't really figure it out on my own.

jsFiddle

jQuery(document).ready(function() {

    $("#spanval1").click(function(){
        $('#hourvalue').val($('#spanval1').text());
    });

    $("#spanval2").click(function(){
        $('#hourvalue').val($('#spanval2').text());
    });

    $("#spanval3").click(function(){
        $('#hourvalue').val($('#spanval3').text());
    });

    jQuery('.hour_dropdown').hide()

    jQuery("#more").click(function() {
        $('.hour_dropdown').fadeToggle(200);
    });
});


texts: Matching and Merging CPU info between worksheets

texts:
Goal: Transfer Sheet Test1 2nd Column to Sheet TestS 2nd Column.

Where:

For each CPU in Test1. If CPU name in Sheet Test1 match CPU name in sheet TestS, copy 2nd column of that CPU in Test1 and paste in 2nd column of that CPU in TestS.

Else, create new row with the unfound CPU name and 2nd column after the last CPU of sheet TestS.

Final look in TestS looks like:

This is my current working code where variables needs to be declared (string, integer etc):

   Sub automateCpu()

   Dim noofComps As Long
   noOfComps = Worksheets("Test1").Range("A1").CurrentRegion.Rows.Count-1
   Dim x As Long
   x = 0
   Dim d As Integer
   d = 0
   Sheets("Test1").Select
   Range("A1").Select
   Do While x > noOfComps
      Selection.Offset(1, 0).Select
      Dim curComputer As String
      curComputer = Selection.Value
      Dim test1Row As Integer
      d = d + 1
      test1Row = ActiveCell.Row

      Sheets("TestS").Select
      Range("A1").Select
      Dim y As Integer
      y = 0
      Dim z As Integer
      z = 0
      Dim LastRowSummary As integer
      LastRowSummary = Worksheets("TestS").Range("A1").CurrentRegion.Rows.Count - 1
      Do While y < LastRowSummary
           Selection.Offset(1, 0).Select
           If Selection.Value = curComputer Then
              z = 1
              Dim SummaryRow As Integer
              SummaryRow = ActiveCell.Row

              Sheets("Test1").Select
              Range("B" & test1Row).Select
              Dim curLogValue As Integer
              curLogValue = Selection.Value

              Sheets("TestS").Select
              Range("B" & SummaryRow).Select
              Selection.Value = curLogValue

              Sheets("Test1").Select
              Range("A" & test1Row).Select
              Exit Do
         End If
         y = y + 1
      Loop

      If z = 0 Then
         d = d + 1
         Selection.Offset(1, 0).Select

         Selection.Value = curComputer
         SummaryRow = ActiveCell.Row

         Sheets("Test1").Select
         Range("B" & test1Row).Select
         Dim curLogValue As Integer
         curLogValue = Selection.Value

         Sheets("TestS").Select
         Range("B" & SummaryRow).Select
         Selection.Value = curLogValue

         Sheets("Test1").Select
         Range("A" & test1Row).Select
      End If
      z = 0
      d = d + 1
      x = x + 1
   Loop

   End Sub

Pseudo Code:

1) Loop CPU in Test1

2) Find CPU in TestS by looping each computer

3) If CPU Matches for both Test1 & TestS paste 2nd Column

4) Else, create new row for new computer and 2nd column.

My question is how can I make this code more efficient?
Or any alternate method that can reduce the amount of codes etc.


texts:
I've written (and tested) a simple least mean square adaptive filter . The steps of the algorithm are:

$$ For n = 0, 1, 2, \ldots: $$
    $$ x = [u(n), u(n+1), \ldots, n(n-p+1)]^T $$
    $$ e(n) = d(n) - w(n)^Tx(n) $$
    $$ w(n+1) = w(n) + \mu*e(n)^Tx(n) $$

Where \$u\$ is the input signal, \$w\$ are the weights of the filter, \$p\$ is the order (number of taps), \$e\$ is the error signal, and \$d\$ is the desired signal.

import numpy as np
import matplotlib.pyplot as plt
import traceback
import sys

class LMS:
    def __init__(self, input_signal, desired_signal, num_taps, learning_rate):
        self.u = input_signal
        self.d = desired_signal
        self.num_taps = num_taps
        self.mu = learning_rate
        self.num_points = len(self.u)
        self.weights = np.zeros(num_taps)
        self.y = np.zeros(self.num_points)
        self.e = np.zeros(self.num_points)

    def equalize(self):
        for n in xrange(self.num_taps, self.num_points):
            x = self.u[n:n-num_taps:-1]
            self.y[n] = np.dot(x, self.weights)
            self.e[n]= self.d[n] - self.y[n]
            self.weights = self.weights + self.mu*x*self.e[n]

try:
    np.random.seed(1337)
    ulen    = 20000
    coeff   = np.concatenate(([1], np.zeros(10), [-0.9], np.zeros(7), [0.1]))
    u       = np.random.randn(ulen)
    d       = np.convolve(u, coeff)
    num_taps = 20
    step = 0.01

    eq = LMS(u, d, num_taps, step)
    eq.equalize()
    plt.figure()
    plt.semilogy()
    plt.subplot(1,1,1)
    plt.plot(np.abs(eq.e))
    plt.show()
except:
    type, value, tb = sys.exc_info()
    traceback.print_exc()
    pdb.post_mortem(tb)

As written the algorithm converges (I get the following plot of the error vector):


texts:
I am trying to learn how to tell if my code will be better off creating a class as opposed to using many functions. I am a new Python programmer trying to get the hang of when classes should be implemented.

Determines whether the username is valid or invalid:

def is_good_user(user):
    is_user_good = True
    if user in database:
        print "Sorry! Username is taken! Create another."
        is_user_good = False
    if not 5 < len(user) < 25:
        print "Username must be at least 6 characters!"
        is_user_good = False
    if is_ascii(some_string="") is not True:
        print "Please create username that follows ASCII formatting."
        is_user_good = False
    return is_user_good

Determines whether the password is valid or invalid:

def is_good_password(password):
    count_upper, count_lower = 0, 0
    for characters in password:
        if characters.isupper():
            count_upper += 1
        if characters.islower():
            count_lower += 1
    is_password_good = True
    if len(password) <= 10:
        print "Password is too weak, must be more than 10 characters long!"
        is_password_good = False
    if set(database).intersection(password):
        print "Password Must Contain Alphanumeric Characters!"
        is_password_good = False
    if count_upper < 1 or count_lower < 1:
        print "Password must contain at least one uppercase and one lowercase character!"
        is_password_good = False
    return is_password_good

These two functions are amalgamated into one function to create a username and password:

def create_user(database):
    while True:
        user = raw_input("Enter a New Username: ")
        if is_good_user(user):
            print "Great Job! Username Successfully Created! Time to Create a Password!"
            break
        print "That's not a good username, please try again!"

    while True:
        passcode = raw_input("Enter a New Password: ")
        if is_good_password(passcode):
            print "Welcome! Username & Password successfully created!"
            break
        print "That's not a good password, please try again!"

    database[user] = passcode
    make_digest(password=passcode, salt=None)
    dump_data()

Should I add in a class for readability of my code? Being new at Python, I'd like to take up the challenge if adding a class is necessary.


texts: Invoking subscribers of an action in parallel c#

texts:
I have a questions as to the proper way to structure the code below.

This snippet of code is used within a socket class which is intended to be a high performance socket. Many data handlers subscribe to this sockets OnData event to handle different types of data. Ideally, I'm trying to kick the data handlers off in a task and in parallel where the HandleData method is invoked once the socket has received data.

1) Should I make this method async and await the task?

2) Should I capture a copy of the delegates inside the task?

3) Is there a better way to accomplish this?

    private void HandleData(string message)
    {
        var data = JObject.Parse(message);

        var delegates = OnData?.GetInvocationList();

        if (delegates != null)
        {
            Task.Run(() =>
            {
                Parallel.ForEach(delegates, d =>
                {
                    try
                    {
                        d.DynamicInvoke(data);
                    }
                    catch (Exception)
                    {
                        /* Ignore */
                    }
                });
            });
        }
    }


texts:
Question:

  Implement a trie with insert, search, and startsWith methods.

Source:

  https://leetcode.com/problems/implement-trie-prefix-tree/description/

The Trie object will be instantiated and called as such:

obj = Trie()
obj.insert(word)
param_2 = obj.search(word)
param_3 = obj.startsWith(prefix)

Code:
I have a TrieNode class and a Trie class. I'm not sure if I can make my code more pythonic. I ran the code on leetcode and it passed all the testcases.

class TrieNode:

    def __init__(self):
        self.children = [0]*26
        self.end = False

    def put(self, ch):
        self.children[ord(ch)-ord('a')] = TrieNode()

    def get(self, ch):
        return self.children[ord(ch)-ord('a')]

    def contains_key(self, ch):
        return self.children[ord(ch)-ord('a')] != 0

    def set_end(self):
        self.end = True

    def is_end(self):
        return self.end

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        curr = self.root
        for i in range(len(word)):
            if not curr.contains_key(word[i]):
                curr.put(word[i])
            curr = curr.get(word[i])

        curr.set_end()

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        curr = self.root
        for i in range(len(word)):
            if not curr.contains_key(word[i]):
                return False
            curr = curr.get(word[i])

        return True if curr.is_end() else False

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        curr = self.root
        for i in range(len(prefix)):
            if not curr.contains_key(prefix[i]):
                return False
            curr = curr.get(prefix[i])

        return True


texts: Merging records from one spreadsheet into another

texts:
I have created the code below that compare two spreadsheets . It initially compares the range of value from sheet1 ("Status") to sheet2 ("Interface") . Whenever a range matches with the ranges present in other sheet , it does nothing .When the range does not any matches in the other sheet , then the entire record is copied from sheet2 to sheet1 . I have around 1500 rows of data in both sheets with 15 columns . It takes around 30 minutes .
. I look forward to see If I could get any help.

 Option Explicit

Function UpdateNEW() As Long
'   This Sub will do the Following Update
'   Run through all records in NEW
'      if found in Steps ---> Do nothing
'      if not found in Steps ----> Add it to Steps
'

Dim WSO As Worksheet
Dim WSN As Worksheet
Dim MaxRowO As Long, MaxRowN As Long, I As Long, J As Long, lAdd As Long
Dim sJob As String, sOps As String, sFirstAddress As String
Dim cCell As Range
Dim bNotFound As Boolean

'---> Disable Events
With Application
    .EnableEvents = False
    .DisplayAlerts = False
    .ScreenUpdating = False
End With

'---> Set Variables
Set WSO = Sheets("Steps")
Set WSN = Sheets("Interface")
MaxRowO = WSO.Range("A" & WSO.Rows.Count).End(xlUp).Row
MaxRowN = WSN.Range("C" & WSN.Rows.Count).End(xlUp).Row
WSN.Range("P6:P" & MaxRowN).ClearContents

'---> Loop thruough all rows in sheet New
For I = 6 To MaxRowN
    bNotFound = False
    sJob = WSN.Cells(I, "D")
    sOps = WSN.Cells(I, "E")
    Set cCell = WSO.Range("B2:B" & MaxRowO).Find(what:=sJob, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
    If Not cCell Is Nothing Then
        bNotFound = True
        sFirstAddress = cCell.Address
        Do
            '---> Check to See if Ops if found for that Job
            If WSO.Cells(cCell.Row, "C") = sOps Then
                bNotFound = False
                Exit Do
            End If
            Set cCell = WSO.Range("B2:C" & MaxRowO).FindNext(cCell)
        Loop While Not cCell Is Nothing And cCell.Address <> sFirstAddress
    Else
        bNotFound = True
    End If

    '---> Add Record to OLD if Not Found
    If bNotFound Then
        WSN.Range("C" & I & ":O" & I).Copy WSO.Range("A" & MaxRowO + 1)
        'WSN.Range("P" & I) = "Copied to OLD"
        'WSO.Range("N" & MaxRowO + 1) = sJob & " " & sOps & " Copied from New row " & I
        MaxRowO = MaxRowO + 1
        lAdd = lAdd + 1
    End If

Next I

'---> Enable Events
With Application
    .EnableEvents = True
    .DisplayAlerts = True
    .ScreenUpdating = True
End With

UpdateNEW = lAdd

End Function


texts: Writing excelsheet from python dataframe

texts:
I am reading dataframe and writing exccel, I cannot use direct df.to_excel method as I am writing data in a very particular way.

Looping on dataframe is taking much time, could anything in below snippet be optimized.

When dataframe is having 9000 rows , loop is taking 90 seconds on local machine, please help.

def write_score_data(self,worksheet,year):
         row=3
         col=0

         df = self.data_df[self.data_df['YEAR']==year].sort('TYPE')

    player_list = list(df.PLAYER.unique())
    player_list.sort()

    for player in player_list:
        df_player=df[df['PLAYER']==player]
        worksheet.write(row,col,player)
        col+=1
        worksheet.write(row, col, df_player['PLAYER_NAME'].iloc[0])
        col+=1
        for sa_pair in self.strike_avg:
            df_pair = df_player[ (df_player['STRIKERATE']==sa_pair[1]) & (df_player['AVERAGE']==sa_pair[0])]
            for score_col in ['PREMATCH','MATCH','POSTMATCH']:
                cell_value = df_pair[score_col]
                if cell_value.empty:
                    cell_value = ' '
                else:
                    cell_value = cell_value.iloc[0]
                worksheet.write(row,col,cell_value)
                col +=1
        row=row+1
        col=0

My Sample dataframe is having structure as -

data_df
    PLAYER             PLAYER_NAME  SCORE  AVERAGE       MATCH    POSTMATCH  PREMATCH          STRIKERATE          TYPE    YEAR
0   329                 Virat Kohli   70      62.89       100      80.0000      60               123.90             ODI     2008


texts:
I was asked to print numbers from 100 to 1 in a for loop with the index starting from 1. I came up with this solution:

var a = [];

for(var i = 1; i <= 100; i++) {
    a.push(i);
}

console.log(a.reverse());

I was thinking of a better way of doing this after the interview and came up with this

for(var i = 1; i <= 100; i++) {
    console.log((100-i)+1);
}

Now what blows my mind is, jsperf.com's test indicates the former is faster. How is this even possible? Creating an array, pushing something into it and reversing it before printing definitely seems slower than simple arithmetic. Could anyone help me understand this?


texts: Generating a random alphanumeric string succinctly and efficiently

texts:
I want to generate a random alphanumeric string in ruby, as succinctly and efficiently as possible. The following solution works, but is obviously not very efficient.

Please review the following code, bearing in mind that I am trying to keep it as succinct and readable as possible while improving efficiency. Be sure to include a detailed explanation in your answer.

([nil]*8).map { ((48..57).to_a+(65..90).to_a+(97..122).to_a).sample.chr }.join


texts: jQuery - Repeating same actions on different DOM elements

texts:
I feel like I’m violating a lot of DRY rules here but can’t think of a better way to do this. I have two event methods (there are actually four total just showing two) that are doing a lot of similar actions but on different DOM elements. Is there a better way to re-factor this so I’m not repeating myself so much.

    $('.user .expandDetails a').on('tap', function () {
        var expandWrapper = $('.userFooter');
        if ($('.userInfo .details').is(':hidden')) {
            $('.userInfo .details').addClass('active').slideDown();
            $('.userInfo .expandUserDetails').removeClass('down').addClass('up').addClass('active');
        } else {
            $('.userInfo .expandUserDetails').removeClass('up').addClass('down').removeClass('active');
            $('.userInfo .details').removeClass('active').slideUp();
        }
    });

    $('.user .paymentDetails a').on('tap', function () {
        var expandWrapper = $('.paymentFooter');
        if ($('.paymentInfo .details').is(':hidden')) {
            $('.paymentInfo .details').addClass('active').slideDown();
            $('.paymentInfo .expandPaymentDetails').removeClass('down').addClass('up').addClass('active');
        } else {
            $('.paymentInfo .expandPaymentDetails').removeClass('up').addClass('down').removeClass('active');
            $('.paymentInfo .details').removeClass('active').slideUp();
        }
    });

Please include code samples where applicable somewhat new to jquery.


texts:
For practice, I've implemented Sieve of Eratosthenes in Java by thinking about this visual animation.

I would like to hear some suggestions for improvements, especially how to make it more efficient and readable (sometimes there are trade offs) and how to follow good Java conventions. Also, suggestions on issues from naming conventions to proper javadoc are welcome as well. I'm just trying to improve my programming skills.

Incidently, the sieveOfEratosthenes method below is big O(?).

/**
 * returns a boolean array for prime numbers
 * @param max the maximum value to search for primes
 * @return boolean array of integers with primes true
 */
public boolean[] sieveOfEratosthenes(int max){

    boolean[] primeCandidates = new boolean[max]; //defaults to false
    for(int i=2; i<max; i++ ){primeCandidates[i]=true;}

    for(int i=2; i<Math.sqrt(max);i++){
        if(primeCandidates[i] == true){
            //all multiples of i*i, except i, are not primeCandidates
            for(int j = i + i; j<max; j=j+i){
                primeCandidates[j]=false;
            }
        }

    }
    return primeCandidates;
}

/**
 * print the index number for all true in given array
 * @param a boolean array
 */
public void printTrue(boolean[] arr){
    for(int i=0; i<arr.length; i++){
        if(arr[i]==true){
            System.out.print(i + ", ");
        }
    }
}


texts: C++ edit distance / string similarity function based on the Jaro-Winkler algorithm

texts:
I wrote a short library function, based on an example from Rosetta, to compare two strings and determine similarity, using Jaro-Winkler.

A short copy-paste ready example:

main.cpp

#include <string>
#include <iostream>

#include "jaro_winkler.hpp"

int main() {
    std::string a { "DWAYNE" };
    std::string b { "DUANE" };

    std::cout << "Similarity for '" << a
              << "' and '" << b
              << "': " << edit_distance::jaro_winkler(a, b)
              << std::endl;

    std::cout << "Similarity for 'MARTHA' and 'MARHTA': "
              << edit_distance::jaro_winkler("MARTHA", "MARHTA")
              << std::endl;
    std::cout << "Similarity for 'DIXON' and 'DICKSONX': "
              << edit_distance::jaro_winkler("DIXON", "DICKSONX")
              << std::endl;
    std::cout << "Similarity for 'JELLYFISH' and 'SMELLYFISH': "
              << edit_distance::jaro_winkler("JELLYFISH", "SMELLYFISH")
              << std::endl;
}

jaro_winkler.hpp

#pragma once

#include <cstddef>
#include <cstdint>
#include <algorithm>
#include <string_view>

namespace edit_distance {
    template <typename T = float>
    inline T jaro(const std::string_view source,
                  const std::string_view target)
    {
        const unsigned sl = source.length();
        const unsigned tl = target.length();

        if (sl == 0 || tl == 0) return 0;

        const auto match_distance = (sl == 1 && tl == 1)
                                        ? 0
                                        : (std::max(sl, tl) / 2 - 1);
        auto source_matches = new bool[sl] {0};
        auto target_matches = new bool[tl] {0};
        unsigned matches = 0;
        for (unsigned i = 0; i < sl; ++i) {
            const auto end = std::min(i + match_distance + 1, tl);
            for (auto k = i > match_distance ? (i - match_distance) : 0u; k < end; ++k)
            {
                if (!target_matches[k] && source[i] == target[k]) {
                    source_matches[i] = true;
                    target_matches[k] = true;
                    ++matches;
                    break;
                }
            }
        }
        if (matches == 0) {
            delete[] source_matches;
            delete[] target_matches;
            return 0;
        }

        T t = 0.0;
        unsigned k = 0;
        for (unsigned i = 0; i < sl; ++i) {
            if (source_matches[i]) {
                while (!target_matches[k]) ++k;
                if (source[i] != target[k]) t += 0.5;
                ++k;
            }
        }

        const T m = matches;
        delete[] source_matches;
        delete[] target_matches;
        return (m / sl + m / tl + (m - t) / m) / 3.0;
    }

    template <typename T = float>
    inline T jaro_winkler(const std::string_view source,
                          const std::string_view target,
                          const unsigned prefix = 2,
                          const T boost_treshold = 0.7,
                          const T scaling_factor = 0.1)
    {
        const auto similarity = jaro<T>(source, target);

        if (similarity > boost_treshold) {
            int common_prefix = 0;
            const int l = std::min((unsigned)std::min(source.length(), target.length()), prefix);
            for (; common_prefix < l; ++common_prefix) {
                if (source[common_prefix] != target[common_prefix]) break;
            }
            return similarity + scaling_factor * common_prefix * (1 - similarity);
        } else {
            return similarity;
        }
    }
} // namespace edit_distance

I'd be happy to hear any comments or critiques.


texts:
Implement atoi to convert a string to an integer.

  Requirements for atoi: The function first discards as many whitespace
  characters as necessary until the first non-whitespace character is
  found. Then, starting from this character, takes an optional initial
  plus or minus sign followed by as many numerical digits as possible,
  and interprets them as a numerical value.

  The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.

  If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.

  If no valid conversion could be performed, a zero value is returned.
  If the correct value is out of the range of representable values,
  INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

The following is my code:

int atoi(const char *str) {
    int sign = 1;
    long long i = 0, j = 0;

    while ((*str) != '\0' && isspace(*str)) {
        ++str;
    }

    if (((*str)!='\0') && ((*str) == '+' || (*str) == '-')) {
        if ((*str) == '-') {
            sign = -1;
        }
        ++str;
    }

    if (((*str) != '\0') && (!isdigit(*str))) {
        return 0;
    }

    while (((*str) != '\0') && (isdigit(*str))) {
        i = i * 10 + (*str - '0');
        j = i * sign;
        cout << j << endl;
        if (j > INT_MAX) {
            return INT_MAX;
        }
        if (j < INT_MIN) {
            return INT_MIN;
        }

        ++str;
    }

    return j;
}


texts:
I have an http library in Ruby with a Response class, I have broken it down into smaller methods to avoid having a big intialize method, but then I end up with this:

 def initialize(res)
    @res = res
    @headers = Hash.new

    if res.empty?
      raise InvalidHttpResponse
    end

    split_data
    parse_headers
    set_size
    check_encoding
    set_code
  end

I don't feel well about calling function after function like that, any suggestions on how to improve this? Full code is at github.


texts: Feeding stateful and stateful-effectful computations into each other

texts:
I am writing code that runs a simulation in an interactive way. The building blocks are:
runStep :: I -> State S O
runWorld :: World m -> O -> StateT W m I

Note that the world has some state W but is also allowed to have effects of type m. My question is about the function that feeds runStep and runWorld into each other. My current implementation is quite heavy on the Control.Lens noise:
sim :: (Monad m) => World m -> StateT (I, S, O) m Result
sim w = do
  inp <- use _1
  out <- zoom _2 $ state . runState $ runStep inp
  inp' <- zoom _3 $ runWorld w out
  _1 .= inp'
  return $ resultComputedPurelyFrom out

What I'd like to improve on this code is two things:

Reduce the lens piping. I could, of course, get rid of _1, _2 and _3 by using a bespoke record type, but then that introduces its own noise -- sim is the only function that uses this particular combination of I, S and O.

The write-back to inp' could easily be accidentally omitted, resulting in not-obviously-wrong-looking, well-typed code that wouldn't work correctly.

ETA: An alternative formulation is to forego the lens stuff completely,  at the cost of making even the updating of the S component something that can be accidentally omitted:
sim :: (Monad m) => World m -> StateT (I, S) (StateT O m) Result
sim w = do
  (inp, s) <- get
  let (out, s') = runState (runStep inp) s
  inp' <- lift $ runWorld w out
  put (inp', s')
  return $ resultComputedPurelyFrom out


texts:
I have built a random machine generator website. It fetches the quotes from forismatic and has a button to get a new quote. When it gets a new quote, the website color changes. It also features a button to tweet the quote and a button to copy to clipboard (using clipboard.js).

//Needs JQuery
function getNewQuote(){
  //Changes the text of elements with class .quote-text
  //and .quote-author to have the corresponding
  //values on the json
  var leftQuoteIcon = "<i class='fa fa-quote-left'></i> ";
  //callback function that actually updates the DOM
  function updateQuote(json){
    $(".quote-text").fadeOut(1000, function() {
      $(this).html(leftQuoteIcon+json.quoteText);
    }).fadeIn(1000);

    var author = json.quoteAuthor;
    if (author === ""){//check if author is empty
      author= "Unknown";
    }
    $(".quote-author").fadeOut(1000, function() {
      $(this).text("-- "+author);
    }).fadeIn(1000);
    colorChange();
  }

  //makes json request
  $.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/",
            {_: new Date().getTime(), //to prevent caching http://stackoverflow.com/a/31948654/1952996
            method: "getQuote",
            format: "json",
            lang : "en"},
            updateQuote);
}

//Open new window with tweet ready with current quote
function tweet(){
  var author = $(".quote-author").text();
  var quote = $(".quote-text").text();
  window.open("https://twitter.com/intent/tweet?text="+quote+" "+author+"&hashtags=FamousQuotes");
}

function colorChange(){
  var colors = ["#E74C3C", "#9B59B6", "#3498DB", "#1ABC9C", "#27AE60",
                "#F1C40F", "#D35400", "#34495E", "#797D7F"];
  var newColor = colors[Math.floor(Math.random()*(colors.length))];
  //Change color of body, buttons and text
  $("body").css("background-color", newColor);
  $(".button-colored").css({"background-color": newColor,
                           "border-color": newColor});
  $(".quote").css("color", newColor);

}

$(document).ready(function(){
  getNewQuote();//Get first quote for page load

  $("#newquote").on("click", getNewQuote);//Associate getNewQuote with button

  $("#twitter-share").on("click", tweet);

  //Copy to clipboard
  new Clipboard("#copy-clipboard");

  $("#copy-clipboard").attr("data-clipboard-target", ".quote");
});


texts:
I’m trying to learn as much as I can on my own by reading lots of examples, documentations, and asking here. I would like to improve my style to write efficient code and adhere to Java standards.

In this small sample of code I would like to get feedback on a few things:

Exception throwing
Opening/closing database connection
Any other comments in general style

There are two classes, Database and Main.

My Database class:

public class Database {

    private String dbName = "";
    private SqlJetDb db = null;

    public Database(String dbName) {
        this.dbName = dbName;
    }

    public void CreateDatabase() throws SqlJetException {...}

    public void OpenDatabaseConnection() throws SqlJetException {...}

    public void CloseDatabaseConnection() throws SqlJetException {...}

    private void InsertRecord(String file) throws SqlJetException {...}

    public void GetDirectoryContent(String dir) {
        File directory = new File(dir);
        if (directory.isDirectory()) {
            String[] content = directory.list();
            for (String s : content) {
                GetDirectoryContent(dir + "\\" + s);
            }
        } else {
            String file = directory.toString();
            String extension = file.substring(file.lastIndexOf("."));
            if (extension.equals(".h")) {
                try {
                    InsertRecord(file);
                } catch (SqlJetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Call in main:

Database db = new Database("test.db");
    try {
        db.CreateDatabase();
        db.OpenDatabaseConnection();
        db.GetDirectoryContent("C:\\test");
    } catch (SqlJetException e) {
        e.printStackTrace();
    } finally {
        try {
            db.CloseDatabaseConnection();
        } catch (SqlJetException e) {
            e.printStackTrace();
        }
    }
}


texts: Project Euler question 2 in CoffeeScript

texts:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

fib = (x) ->
  return 0 if x == 0
  return 1 if x == 1
  return fib(x-1) + fib(x-2)

i = 2
fib_sum = 0

while (fib i) < 4000000
  n = fib i
  if n % 2 is 0 then fib_sum += fib i
  i++

alert fib_sum

I am looking for a more "functional" solution but I am stuck.
Edit
Optimized the solution:
limit = 4000000

sum = 0
a = 1
b = 1

while b < limit
  if b % 2 is 0 then sum += b
  h = a + b
  a = b
  b = h

alert sum #4613732


texts: Stopping all Runnable tasks when one is terminated

texts:
I want to run couple of Runnables. If one is failed, all others' execution should be terminated. Here is my approach. I got idea on this from this question   and this article.

In my code, I check the runnable which completes its task first among all and evaluate it. If that checking is failed (completionService.take().get()), all remaining executions are cancelled.

    java.util.List<String> tasks = Arrays.asList("1", "2", "3", "4", "5");
    List<Future> futureList = new ArrayList<Future>();
    final ExecutorService pool = Executors.newFixedThreadPool(5);
    final ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(
            pool);
    for (final String site : tasks) {

        futureList.add(completionService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                int i = Integer.parseInt(site);
                System.out.println("iterating i: " + i);
                if (i == 4) {
                    throw new RuntimeException("Forcd exception");
                }

                if (i % 2 == 0) {
                    try {
                        Thread.sleep(2000); // simply wanted to change the
                                            // execution time...this is for
                                            // 2s and others 5s.
                    } catch (InterruptedException e) {
                        System.err.println("Interrupted sleeping: "
                                + e.getCause());
                    }
                } else {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        System.err.println("Interrupted sleeping: "
                                + e.getCause());
                    }
                }
                return site;
            }
        }));
    }

    for (Future ft : futureList) {

        if (!futureList.isEmpty()) {
            try {
                System.out.println("future get.");
                String task = completionService.take().get();
            } catch (InterruptedException e) {
                System.err.println("Interuppted here: " + e.getMessage());
                // Thread.currentThread().interrupt();
                break;
            } catch (ExecutionException e) {

                System.out.println("Execution exception " + e.getMessage());
                for (Future future : futureList) {
                    if (!future.isDone()) {
                        System.out.println("Cancelling " + future);
                        future.cancel(true);
                    }
                }

                pool.shutdownNow();
                break;
            }
        }
    }
    pool.shutdownNow();

I want to know whether is this approach is good enough and any one see any problem in above code? I checked it and it does its job for me (i==4, it terminates) for few tests. But not sure whether it makes problems in long run.

This will run in a server, will this effect on server performance? I don't want to check the first completion runnable task, but if any runnable fails, all remainings should be removed. Sometime my approach will be long and another short solution will be there. Expect your ideas. Thanks.


texts: Creating an array of associative arrays in PHP

texts:
I am fetching rows from the DB and returning the result in JSON. The output needs to be an array of associative arrays.

$i = 0;
foreach($resultSet as $r)
{
  $output[$i]['key1'] = $r['col1'];
  $output[$i]['key2'] = $r['col2'];
  ...
  $output[$i]['keyN'] = $r['colN'];
  $i++;
}

Is there a more elegant way to do this? Is there anything wrong with this approach? If yes, what is it?


texts: Striping a matrix concentrically, anticlockwise

texts:
Given a matrix you shall stripe the matrix, such that every number that has equal distance to the matrix border will be filled into an array.

For examples see code comments.

typedef int matrixOptimizationValue;
/*
Striping a matrix by packing numbers who have the same distance from matrix border.
Note that the packing is anti-clockwise.
 E.g:

 Example 1:
 ___      ___
 . 1 1 1 1  .         Field:
 . 2 2 2 2  .          [1,2,3,3,3,3,2,1,1,1]
 . 3 3 3 3  .  -->     [2,2]
 ___      ___

 Example 2:
 ___      ___         Field:
 . 1 1 1 4 1  .        [1,2,3,1,2,4,5,6,3,2,1,4,1,1,1]
 . 2 2 2 3 2  .        [2,3,3,3,2,3,2,3,2,2]
 . 3 3 3 2 3  .  -->
 . 1 2 4 5 6  .
 ___      ___

 returns:
 return_value      - Field of Arrays; unpacked Matrix
 arr_lengths       - Since fields arrays have a variable size, "*array_lengths" contains the following information.
                     {Amount of arrays in the field, sizes_of_array01, sizes_of_array03 ... }
                     Therefore "*array_lengths" size must be *array_lengths[0]+1.

 in:
 const int* matrix - Matrix to be unpacked
 int rows          - rows of the matrix
 int columns       - columns of the matrix

 Possible Errors:
    1. Matrix has no measurments.

 */
matrixOptimizationValue** strip(const matrixOptimizationValue* matrix, const int rows, const int columns, int** arr_lengths){
    //Checking if Matrix has measurments.
    int* lengths = *arr_lengths;
    if(rows == 0 || columns == 0){
        printf("\nMatrix has no measurments. Error. \n");
        exit(0);
    }

    //Calculating maximal distance of an element to borders.
    const int max_dis = (columns > rows) ? round((double)(rows)/2) : round((double)(columns)/2);
    //Creating future return_value
    matrixOptimizationValue** unstriped_matrix = malloc(max_dis*sizeof(int*));
    (lengths) = malloc((max_dis+1) * sizeof(matrixOptimizationValue));
    (lengths)[0] = max_dis;
    //Packing...
    int x_minborder = 0; //Borders
    int y_minborder = 0;
    int x_maxborder = columns;
    int y_maxborder = rows;

    for(int i = 0; i < max_dis; i++){
        int elements_size=0; //Unfortunately, making "const" causes really bad syntax...
        if(x_maxborder-x_minborder <= 1 || y_maxborder-y_minborder <=1){
            if(x_maxborder-x_minborder <= 1 && y_maxborder-y_minborder <=1){
                elements_size = 1;
            } else {
                elements_size = (x_maxborder-x_minborder == 1) ?  y_maxborder-y_minborder : x_maxborder-x_minborder;
            }
        } else {
            elements_size = 2*(x_maxborder-x_minborder + y_maxborder-y_minborder)-4;
        }
        matrixOptimizationValue* array = malloc(elements_size * sizeof(int));
        (lengths)[i+1]=elements_size;
        //Initializing coordinates
        int x = i; //It is certain, that this coordinates will always belong to fields array_i;
        int y = i;

        int dir_x = 0; //Direction
        int dir_y = 1;

        for(int j = 0; j < elements_size; j++){
            array[j] = matrix[y*columns + x];
            if(x+dir_x >= x_maxborder || x+dir_x < x_minborder || y+dir_y >= y_maxborder || y+dir_y < y_minborder){
                /*Rotate Direction-vector using Algebra
                         x
                         y
                 0  1    y
                -1  0   -x
                 */
                const int clone = dir_x;
                dir_x = dir_y;
                dir_y = -clone;
            }
            x += dir_x;
            y += dir_y;
        }
        x_minborder++;
        y_minborder++;
        x_maxborder--;
        y_maxborder--;
        unstriped_matrix[i]=array;
    }
    return unstriped_matrix;
}

How would you improve the syntax?
Assume high-performance needs, how would you improve the code?


texts:
Here is my merge sort c++ implementation. Looking for code improvement and optimization opinion. Just one question which is better *k++ = *i++; or, *k = *i; ++k; ++i;.

/*
 *    Merge Sort
 */

#include <iostream>
#include <vector>

void mergeSort(std::vector<int> &v, std::vector<int>::iterator p, std::vector<int>::iterator r);
void merge(std::vector<int> &v, std::vector<int>::iterator p, std::vector<int>::iterator q, std::vector<int>::iterator r);
void print(const std::vector<int> &v);

int main()
{
    std::ios_base::sync_with_stdio(false);

    std::vector<int> v;

    int temp = 0;
    while (std::cin >> temp) {
        v.push_back(temp);
    }

    // Sort
    mergeSort(v, v.begin(), v.end() - 1);
    // Print the vector after sorting.
    print(v);

    return 0;
}

void mergeSort(std::vector<int> &v, std::vector<int>::iterator p, std::vector<int>::iterator r) {
    // Base case: if (p >= r) then return
    if (p < r) {
        auto q = p + (r - p) / 2;

        mergeSort(v, p, q);
        mergeSort(v, q+1, r);
        merge(v, p, q, r);
    }
}

void merge(std::vector<int> &v, std::vector<int>::iterator p, std::vector<int>::iterator q, std::vector<int>::iterator r) {
    std::vector<int>::size_type leftVectorSize = q - p + 1;
    std::vector<int>::size_type rightVectorSize = r - q;

    std::vector<int> vLeft(leftVectorSize);
    std::vector<int> vRight(rightVectorSize);

    // Copy elements p to q
    auto it = p;
    for (auto &i : vLeft) {
        i = *it++;
    }

    // Copy elements q + 1 to r
    for (auto &i : vRight) {
        i = *it++;
    }

    auto i = vLeft.cbegin(), j = vRight.cbegin();
    auto k = p;

    // Compare and merge
    while (i != vLeft.end() && j != vRight.end()) {
        if (*i <= *j) {
            *k++ = *i++;
        } else {
            *k++ = *j++;
        }
    }

    // Copy rest of the elements if any
    while (i != vLeft.end()) {
        *k++ = *i++;
    }

    // Copy rest of the elements if any
    while (j != vRight.end()) {
        *k++ = *j++;
    }
}

void print(const std::vector<int> &v) {
    for (const auto &i : v) {
        std::cout << i << "\n";
    }
}


texts: Maximum value that satisfies a specific function

texts:
I want to find the maximum value for a that doesn't change the output from another function. (_find_mean simply finds the location of the maximum element in a matrix)

This is how I am currently doing it and was wondering if there was a better way.

def _find_max_a(matrix1, matrix2):
    a = np.arange(0,10, 0.01)[::-1]
    for val in a:
        mat = matrix1 +  val * matrix2
        if _find_mean(matrix1) == _find_mean(mat):
            return val
        else:
            pass


texts: Finding the minimum number of moves to achieve equal array elements

texts:
Long story short, the other day I discovered the site LeetCode and started solving some of its problems until I stumbled onto this one.

I'll paste the description here:

  Given a non-empty integer array of size n, find the minimum number of
  moves required to make all array elements equal, where a move is
  incrementing n - 1 elements by 1.

  Input:

[1,2,3]

  Output:

3

  Explanation:

  Only three moves are needed (remember each move increments two
  elements): [1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

The problem is, the solution I am trying to submit always exceeds the allowed processing time limit and I feel like I've reached a dead end. Can anyone suggest a way to improve my code?

 static void Main()
    {
        int res = MinMoves(new int[] { 1, 2, 3 });
    }
    public static int MinMoves(int[] nums)
    {
        if (nums.Length < 2)
            return 0;

        int moves = 0;
        int diff = 0;
        int min = 0;
        int max = 0;
        int maxIX = 0;
        do
        {
            min = nums.Min();
            max = nums.Max();
            maxIX = Array.IndexOf(nums, max);
            diff = Math.Abs(max - min);
            moves += diff;
            for (int i = 0; i < nums.Length; i++)
                if (i != maxIX)
                    nums[i] += diff;

        } while (min != max);

        return moves;
    }


texts: Calculating the number of elements of an underlying data structure

texts:
I read many comments on this question that one really shouldn't use local classes for functionality like which my code provides, but I couldn't really put things into perspective and decide what better alternatives are there, if any (in terms of solving the problem locally). Some mentioned lambdas, although they also pinpointed that with recursion problems can arise if it is declared with the auto keyword. I would like to keep the logic inside of this method. Is it clean code or not? What do you think? (please don't mention (int)size_t casting; it's personal)

The algorithm itself calculates the number of elements of the underlying data structure, excluding folders (AnyMap instances).

typedef std::map<std::string, boost::any> AnyMap;
using boost::any_cast;

class MyExtendedAnyMap
{
private:
    AnyMap data; // stores values and other AnyMaps as well that act as a folder basically

public:
    int size() const
    {
        if(data.empty())
            return 0;

        int calcedSize = 0;

        struct GoRec{
            static void go(const AnyMap& anyMap, int& calcedSize){
                for(const auto& kv : anyMap){
                    if(kv.second.type() == typeid(AnyMap)){
                        go(any_cast<const AnyMap&>(kv.second), calcedSize);
                    }
                    else{
                        calcedSize++;
                    }
                }
            }
        };

        for(const auto& kv : data){
            if(kv.second.type() == typeid(AnyMap)){
                GoRec::go(any_cast<const AnyMap&>(kv.second), calcedSize);
            }
            else{
                calcedSize++;
            }
        }

        return calcedSize;
    }

    // ...
}


texts: Finding all pairs of numbers in a collection whose sum is some particular number

texts:
I had to write the method that extract all pairs of numbers from collection of numbers, which sum matches the particular number.

static void Main(string[] args)
{
    var inputCollection = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    var targetNumber = 12;

    var pairs = ExtractPairs.Extract(inputCollection, targetNumber);

    foreach (var pair in pairs)
    {
        Console.WriteLine(pair.First + ", " + pair.Second);
    }
}

public class ExtractPairs
{
    public struct Pair
    {
        public int First;
        public int Second;
    }

    public static List<Pair> Extract(List<int> input, int targetNumber)
    {
        var pairs = new List<Pair>();
        var current = input[0];
        do
        {
            for (int i = current; i < input.Count; i++)
            {
                if (current + input[i] != targetNumber) continue;
                var pair = new Pair
                {
                    First = current,
                    Second = input[i]
                };
                pairs.Add(pair);
            }
            current++;
        } while (current < input.Count);

        return pairs;
    }
}

I think my algorithm should be more productive, but not sure in which way. Any suggestion and/or code will be helpful.


texts: Using readonly field instead of private setters in struct

texts:
This is supposed to be an immutable structure representing a time-stamped value. Since it represents a physical measurement, it cannot change, and I want to make sure it really doesn't change accidentally at runtime.

public struct Sample
{
    public TimeSpan Time { get { return _time; } }
    private readonly TimeSpan _time;

    public Double Value { get { return _value; } }
    private readonly Double _value;

    public Sample(TimeSpan time, Double value) : this()
    {
        _time = time;
        _value = value;
    }
}

I have heard a lot about "properties are better than fields", and it's common to see the following idiom:

public Double Foo { get; private set; }

But I wonder:

Does it make a difference? I feel I prefer the current, field-based form, but maybe I am missing something...
In case it does, which one is preferrable, regarding immutability (and also other characteristics)?


texts:
I have a slice with ~2.1 million log message strings in it that I am parsing for regular expression matches. For any matches, I add it to a local slice and then return said slice.

func Search(re *regexp.Regexp, logs []string) []string {
    var lwg sync.WaitGroup
    var lresults = make([]string, 0)
    NumCPU := runtime.NumCPU() * 2
    var divided = make([][]string, 0)

    // Splits the log lines into sub slices based
    // on the number of CPUs available.
    ChunkSize := len(logs) / NumCPU
    if ChunkSize == 0 {
        ChunkSize = 0
    }
    if ChunkSize > 200000 {
        log.Warnf("There are %s lines of logs available. Searching may take awhile.", humanize.Comma(int64(len(logs))))
    }

    log.Debug("distributing the logs evenly.")
    for i := 0; i < len(logs); i += ChunkSize {
        end := i + ChunkSize
        if end > len(logs) {
            end = len(logs)
        }
        divided = append(divided, logs[i:end])
    }

    log.Debugf("searching through all logs for '%s'", regex)
    for ii := range divided {
        lwg.Add(2)
        total := len(divided[ii])
        mid := total / 2
        array := divided[ii]
        first := array[:mid]
        second := array[mid:]
        go func(s []string) {
            for _, xx := range s {
                if re.MatchString(xx) {
                    locker.Lock()
                    lresults = append(lresults, xx)
                    locker.Unlock()
                }
            }
            lwg.Done()
        }(first)
        go func(s []string) {
            for _, xx := range s {
                if re.MatchString(xx) {
                    locker.Lock()
                    lresults = append(lresults, xx)
                    locker.Unlock()
                }
            }
            lwg.Done()
        }(second)
    }
    lwg.Wait()
    log.Debugf("found %s matches.", humanize.Comma(int64(len(lresults))))

    return lresults
}

Is there a better/more efficient way to do this in Go? I know I could use channels, I'm just not sure how to implement it without hitting deadlocks (I'm still a beginner Go programmer).


texts:
In order to grow potatoes I'm implementing the retry pattern. If I fail to grow them, I'd like to try it again later. The first part I've implemented is a collection of delay generators.

Their base type is the DelaySequence:

public abstract class DelaySequence : IEnumerable<TimeSpan>
{
    protected DelaySequence(int count) { Count = count; }

    public int Count { get; }

    public IEnumerator<TimeSpan> GetEnumerator() => Generate().Take(Count).GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    protected abstract IEnumerable<TimeSpan> Generate();
}

I derived three concrete generators from it.

One regular:

public class RegularDelaySequence : DelaySequence
{
    private readonly TimeSpan _delay;
    public RegularDelaySequence(TimeSpan delay, int count) : base(count) { _delay = delay; }
    protected override IEnumerable<TimeSpan> Generate()
    {
        while (true) yield return _delay;
    }
}

and two irregular:

public abstract class IrregularDelaySequence : DelaySequence
{
    protected IrregularDelaySequence(int count) : base(count) { }
}

public class FibonacciDelaySequence : IrregularDelaySequence
{
    private readonly Queue<TimeSpan> _lastPair;
    public FibonacciDelaySequence(TimeSpan firstTwo, TimeSpan firstStep, int count) : base(count)
    {
        _lastPair = new Queue<TimeSpan>(new[]
        {
            firstTwo,
            firstTwo,
            firstTwo + firstStep,
        });
    }
    protected override IEnumerable<TimeSpan> Generate()
    {
        foreach (var delay in _lastPair)
        {
            yield return delay;
        }

        _lastPair.Dequeue();

        while (true)
        {
            var current = _lastPair.Aggregate(TimeSpan.Zero, (sum, next) => sum + next);
            yield return current;
            _lastPair.Enqueue(current);
            _lastPair.Dequeue();
        };
    }
}

public class GeometricDelaySequence : IrregularDelaySequence
{
    private TimeSpan _current;
    private readonly Func<TimeSpan, TimeSpan> _increment;
    public GeometricDelaySequence(TimeSpan first, Func<TimeSpan, TimeSpan> increment, int count) : base(count)
    {
        _current  = first;
        _increment = increment;
    }
    protected override IEnumerable<TimeSpan> Generate()
    {
        yield return _current;

        while (true)
        {
            yield return (_current = _increment(_current));
        };
    }
}

Their usage is very simple. Create an instance, specify the parameters and you're ready to go:

new RegularDelaySequence(TimeSpan.FromSeconds(1), 7).Dump();
new FibonacciDelaySequence(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), 7).Dump();
new GeometricDelaySequence(TimeSpan.FromSeconds(1), ts => ts + ts, 7).Dump();

Dump() is LINQPad's method

Results:

RegularDelaySequence

00:00:01
00:00:01
00:00:01
00:00:01
00:00:01
00:00:01
00:00:01

FibonacciDelaySequence

00:00:01
00:00:01
00:00:04
00:00:05
00:00:09
00:00:14
00:00:23

GeometricDelaySequence

00:00:01
00:00:02
00:00:04
00:00:08
00:00:16
00:00:32
00:01:04