texts: Reverse Polish Notation Calculator in Java

texts:
I created a highly effective Reverse Polish Notation calculator using Java 8, but am uncertain if there are any better ways to handle the problem. Feedback on any evident taboos and bugs is greatly appreciated!

public final class RPN {

    /**
     * Removes all characters that are not operators, whitespace, or digits
     *
     * @param expr the expression to parse
     * @return the parsed expression
     */
    private static String parseExpression(String expr) {
        String parsedExpr = expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", "");
        String trimmedExpr = parsedExpr.replaceAll("\\s+", " ");
        return trimmedExpr;
    }

    /**
     * Computes the outcome of a given expression in Reverse Polish Notation
     *
     * @param expr the expression to compute
     */
    public static void compute(String expr) throws
            ArithmeticException,
            EmptyStackException {
        String validExpr = parseExpression(expr);
        Stack<Double> stack = new Stack<>();

        System.out.println(validExpr);
        System.out.println("Input\tOperation\tStack after");

        for (String token : validExpr.split("\\s")) {
            System.out.print(token + "\t");

            double secondOperand = 0.0;
            double firstOperand = 0.0;

            switch (token) {
                case "+":
                    System.out.print("Operate\t\t");

                    secondOperand = stack.pop();
                    firstOperand = stack.pop();

                    stack.push(firstOperand + secondOperand);
                    break;
                case "-":
                    System.out.print("Operate\t\t");

                    secondOperand = stack.pop();
                    firstOperand = stack.pop();

                    stack.push(firstOperand - secondOperand);
                    break;
                case "*":
                    System.out.print("Operate\t\t");

                    secondOperand = stack.pop();
                    firstOperand = stack.pop();

                    stack.push(firstOperand * secondOperand);
                    break;
                case "/":
                    System.out.print("Operate\t\t");

                    secondOperand = stack.pop();
                    firstOperand = stack.pop();

                    if (secondOperand == 0.0) {
                        throw new ArithmeticException("Cannot divide by zero!");
                    }

                    stack.push(firstOperand / secondOperand);
                    break;
                case "^":
                    System.out.print("Operate\t\t");

                    secondOperand = stack.pop();
                    firstOperand = stack.pop();

                    stack.push(Math.pow(firstOperand, secondOperand));
                    break;
                default:
                    System.out.print("Push\t\t");
                    stack.push(Double.parseDouble(token));
                    break;
            }

            System.out.println(stack);
        }

        System.out.println("Final Answer: " + stack.pop());
    }

    /**
     * What runs the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            String expr = Arrays.toString(args);
            System.out.println(expr);
            compute(expr);
        } catch (Throwable err) {
            System.out.println(err.getMessage());
        }
    }
}


texts:
Looking for a general review.

pub struct BitVector {
    bits: Vec<u8>,
    size: usize,
}

impl BitVector {
    pub fn new() -> BitVector {
        BitVector {
            bits: Vec::new(),
            size: 0,
        }
    }

    pub fn push(&mut self, bit: bool) {
        let leftover = self.size % 8;
        if leftover == 0 {
            self.bits.push(0);
        }
        let last_byte = self.bits
            .last_mut()
            .expect("Assertion error");

        *last_byte |= (bit as u8) << leftover;
        self.size += 1;
    }

    pub fn push_all(&mut self, bits: &[bool]) {
        for bit in bits {
            self.push(*bit);
        }
    }

    pub fn append(&mut self, other: &mut BitVector) {
        let leftover = self.size % 8;
        let empty_bits = 8 - leftover;
        let len = self.bits.len();

        self.bits.append(&mut other.bits);
        self.size += other.size;

        if leftover == 0 {
            return;
        }
        for i in len..self.bits.len() {
            self.move_bits(empty_bits, i);
        }
        if (self.size - 1) / 8 != self.bits.len() - 1 {
            self.bits.pop();
        }
    }

    fn check(&self, i: usize) {
        assert!(i < self.size,
                format!("Index out of bounds.
                Index: {} >= len: {}", i, self.size));
    }
    pub fn get(&self, i: usize) -> bool {
        self.check(i);
        (1 & (self.bits[i / 8] >> (i % 8))) != 0
    }

    pub fn put(&mut self, i: usize, bit: bool) {
        self.check(i);
        let (byte, bit_pos) = (i / 8, i % 8);
        self.bits[byte] &= !(1 << bit_pos);
        self.bits[byte] |= (bit as u8) << bit_pos;
    }

    fn move_bits(&mut self, bits: usize, i: usize) {
        let leftover = 8 - bits;
        let (from, to) = (self.bits[i], self.bits[i - 1]);
        self.bits[i - 1] = to ^ (from << leftover);
        self.bits[i] = from >> bits;
    }

    pub fn iter<'a>(&'a self) -> BitVectorIter<'a> {
        let itr = self.bits
            .iter()
            .flat_map(|byte| (0..8usize)
                .map(move |i| ((byte >> i) & 1) != 0))
            .take(self.size);

        BitVectorIter { iter: Box::new(itr) }
    }
}

pub struct BitVectorIter<'a> {
    iter: Box<std::iter::Iterator<Item = bool> + 'a>,
}
impl<'a> IntoIterator for &'a BitVector {
    type Item = bool;
    type IntoIter = BitVectorIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
impl<'a> Iterator for BitVectorIter<'a> {
    type Item = bool;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}


texts: In Memory Database in Unit tests, isolate the tests

texts:
I have stumbled across these unit tests in a code review that are using in memory db:

private DatabaseContext _context;
private Fixture _fixture;

[SetUp]
public void Setup()
{

    _fixture = new Fixture();
    _fixture.Customize(new AutoNSubstituteCustomization());

    var options = new DbContextOptionsBuilder<DatabaseContext>()
    .UseInMemoryDatabase(databaseName: "testdb")
    .Options;
    _context = new DatabaseContext(options);
}

[TearDown]
public void CleanUp()
{
    var context = _context;
    if (context == null || context.Database.ProviderName != "Microsoft.EntityFrameworkCore.InMemory")
    {
        return;
    }

    context.Database.EnsureDeleted();
    _context = null;
}

#region EmptyDB
[Test]
public void Test1()
{
    // Setup
    var logger = _fixture.Freeze<ILogger<UserRepository>>();

    var userRepo = new UserRepository(_context, logger);

    var userViews = new List<UserView>();
    userViews.AddRange(_fixture.CreateMany<UserView>(10));

    // ACT
    userRepo.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();

    // ASSERT
    Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}

[Test]
public void Test2()
{
    // Setup
    var logger = _fixture.Freeze<ILogger<UserRepository>>();

    var userRepo = new UserRepository(_context, logger);

    var identityViews = new List<IdentityView>();
    _fixture.Register<IEnumerable<UserView>>(() =>
    {
        return new UserView[] { new UserView("fish") };
    });
    userViews.AddRange(_fixture.CreateMany<UserView>(10));

    // ACT
    userRep.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();

    // ASSERT
    Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}

As you can see, the tests are using the same in memory db, which I really don't like. I also don't like the new UserRepository(_context, logger). Is it a bad practice to use the new-keyword like this?

I would prefer something like this instead:

[Test]
public void Test1()
{
    // Setup
    var provider = RegisterServices();
    var logger = _fixture.Freeze<ILogger<UserRepository>>();
    var userRepo = provider.GetRequiredService<IUserRepository>();

    var userViews = new List<UserView>();
    userViews.AddRange(_fixture.CreateMany<UserView>(10));

    // ACT
    userRepo.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();

    // ASSERT
    Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}

private ServiceProvider RegisterServices([CallerMemberName] string memberName = "")
{
    var services = new ServiceCollection();

    services.AddDbContext<IDatabaseContext, DatabaseContext>(options =>
        options.UseInMemoryDatabase(memberName));

    services.AddPersistence("https://localhost");

    return services.BuildServiceProvider();
}

As you can see, I have added a RegisterService method that takes the calling test as a parameter, and then uses this to create the inmemorydb. I really like this because you are isolating your tests more this way. I also think it's cleaner to read.

How would you guys do in this case? Is the first approach the way to go, or is my approach the more "right" way to do it? Or is it another better and more best practice way to do it?

I just want to know your opinions about this and about the two approaches above.


texts:
I did a little function which is listening to hashchanges.

What do you think about?

var onhashchange = function(code) {
    var checkHash = function(oldHash, code) {
        var hash = window.location.hash;
        var hashObject = hash.replace('#/','').split('/');

        if (hash !== oldHash)
            code(hashObject);

        setTimeout(function(){checkHash(hash, code);},100);
    }

    var oldHash = window.location.hash;

    setTimeout(function(){checkHash(oldHash, code);},100);
}

onhashchange(function(evt) {
    console.log(evt[0]); // Pagename after #/ - subcategories evt[1]... after slashes /
});


texts:
I have a solution to the HackerRank Circular Array Rotation challenge.  It passes 7 test cases out of 15. The rest of them are getting timed out. I think it's because of the huge data set that has been given as the input.

  Input Format

  The first line contains 3 space-separated integers, n (the length of the array), k (the number of right circular rotations), and q (the number of queries).
  The second line contains n space-separated integers a0, a1, a2, …, an-1.
  Each of the q subsequent lines contains a single integer denoting m.  For each of those queries, output am of the rotated array.

  Constraints

  1 ≤ n ≤ 105
  1 ≤ ai ≤ 105
  1 ≤ k ≤ 105
  1 ≤ q ≤ 500

Can you point me out how can I improve this code in order to avoid those time out of test cases?

public class CircularArrayRotation {

    public static int[] circularArray(int[] beforeArray){
            int[] afterArray = new int[beforeArray.length];
            afterArray[0] = beforeArray[beforeArray.length-1];
            System.arraycopy(beforeArray,0,afterArray,1,beforeArray.length-1);
            return afterArray;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int k = sc.nextInt();
        int q = sc.nextInt();
        sc.nextLine();
        int[] source = new int[n];
        String[] elements = sc.nextLine().split(" ");
        for (int i=0;i<elements.length;i++){
            source[i] = Integer.parseInt(elements[i]);
        }
        source = repeatCirculating(source,k);
        int[] ques = new int[q];
        for (int i=0;i<q;i++){
            int position = Integer.parseInt(sc.nextLine().trim());
            ques[i] = position;
        }
        for (int ask:ques) {
            System.out.println(source[ask]);
        }

    }

    public static int[] repeatCirculating(int[] source, int times){
        for (int i =0; i<times; i++){
            source = circularArray(source);
        }
        return  source;
    }
}


texts: URL resolver for Users, Lessons, and Series

texts:
My Resolver.resolve class returns a hash of objects and I would like to return a specific object if it exists. Is there a more concise way to write this?

def resolve_url(url)
    # Resolver library now returns a hash of objects
    # Using this helper method to preserve the old functionality of returning a single object
    # Order of old return types is Lesson -> Series -> User
    objects = Resolver.resolve(url, :only => [User, Lesson, Series])
    if objects[Lesson]
      objects[Lesson]
    elsif objects[Series]
      objects[Series]
    elsif objects[User]
      objects[User]
    else
      nil
    end
  end
end


texts: Logs 'Fizz' for multiples of three, 'Buzz', for multiples of 5, and 'Fizz Buzz' for multiples of 3 & 5

texts:
I'm new to coding and have been directed here from Stack Overflow. As I'm new to coding, I'm not entirely sure if my program works completely, but I think it does. I'm looking for suggestions on how to improve my code, particularly the format, as well as the code itself please.
Rather than output FizzBuzz for the first 100 numbers, i.e., 1 - 100, I wanted to write a program that could output FizzBuzz for any positive whole number range.
const fizzBuzz = (num) => {
  let fizzBuzzNumbers = [];

  const populateArray = num => {
    for (let i = 1; i < num + 1; i++) {
      fizzBuzzNumbers.push(i);
    }
  };

  populateArray(num)

  for (let i = 0; i < fizzBuzzNumbers.length; i++) {
    if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 === 0) {
      console.log('FizzBuzz');
    } else if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 !== 0) {
      console.log('Fizz');
    } else if (fizzBuzzNumbers[i] % 3 !== 0 && fizzBuzzNumbers[i] % 5 === 0) {
      console.log('Buzz');
    } else {
      console.log(fizzBuzzNumbers[i]);
    }
  }
};

Any feedback or suggestions will be greatly appreciated.


texts: How to think smarter when you need diff args in functions

texts:
I have this code, and the point is I want to dynamically change the mongo connecter to change between ssl, not ssl and with and without username in the same connecter function.

if auth_required:
    if config.getboolean(component, 'ssl', fallback=False):
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            ssl=True,
            ssl_ca_certs=config.get(component, 'ssl_path'),
            serverSelectionTimeoutMS=timeout,
            username=username,
            password=password,
            authSource=auth_source,
            authMechanism=auth_mechanism
        )
    else:
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            serverSelectionTimeoutMS=timeout,
            username=username,
            password=password,
            authSource=auth_source,
            authMechanism=auth_mechanism
        )
else:
    if config.getboolean(component, 'ssl', fallback=False):
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            ssl=True,
            ssl_ca_certs=config.get(component, 'ssl_path'),
            serverSelectionTimeoutMS=timeout
        )
    else:
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            serverSelectionTimeoutMS=timeout
        )


texts:
This might be a simple issue that I am overcomplicating, but I've spent quite some time reading about polygon scaling and I've come to the conclusion that it is not precisely what I need.

Given a set of (x, y) coordinates for N points (shown in blue) I need the new set of coordinates that result after zooming in/out a given scale factor (shown in red).

I've come up with the simple method shown below, but I wonder if there might be another approach and/or more reasonable zooming methods.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

N = 5
xy = [np.random.uniform(0., 1000., 2) for _ in range(N)]
x, y = zip(*xy)

# Center of xy points, defined as the center of the minimal rectangle that
# contains all points.
xy_center = ((min(x) + max(x)) * .5, (min(y) + max(y)) * .5)

# Difference between the center coordinates and the xy points.
delta_x, delta_y = xy_center[0] - x, xy_center[1] - y

# Zoom scale (0. < scale)
scale = 1.5

# Scaled xy points.
x_scale = xy_center[0] - scale * delta_x
y_scale = xy_center[1] - scale * delta_y

ax = plt.subplot(111)
# Original xy points.
ax.scatter(x, y, c='b')
# Defined center.
ax.scatter(*xy_center, marker='x', c='g')
# Zoomed points.
ax.scatter(x_scale, y_scale, c='r')
# Square: bottom left corner, width, height
ax.add_patch(
    patches.Rectangle(
        (min(x), min(y)), (max(x) - min(x)), (max(y) - min(y)), fill=False))
plt.show()


texts:
I've got this Collection in my Backbone application:

var AnswersCollection = Backbone.Collection.extend({
    model: Answer,

    initialize: function() {
        console.log('Hello from new answers collection');
    },

    getCorrect: function() {
        return this.where({correct: true});
    },

    getWrong: function() {
        return this.where({correct: false});
    },

    randomSet: function(correct, wrong) {
        arr1 = _.sample(this.getCorrect(), correct);
        arr2 = _.sample(this.getWrong(), wrong);
        result = _.shuffle(arr1.concat(arr2));
        coll = new AnswersCollection(result)
        return coll;
    }

});

This works, and randomSet is called by a View when config have certain options or user click on 'rerender' button, but I'm wondering that maybe I can improve this code ?
The flow looks like this

Get randomly selected X correct answers
Get randomly selected Y wrong answers
Shuffle all answers
Create array of answers, that can be passed to new Collection

This code doesn't look to cool, maybe you will have some ideas how to make It cooler?:)


texts:
I have JSON object response returned from the server which is similar to this one:

{
    "id": 123,
    "from_id": 234,
    "attachments": [
        {
            "type": "audio",
            "audio": {
                "artist": "Van Halen",
                "title": "Eruption"
            }
        },
        {
            "type": "photo",
            "photo": {
                "id": 123,
                "url": "http://someurl.com"
            }
        }
    ]
}

and I want to unmarshal it to the following structure:

type Response struct {
    Id          int `json:"id"`
    FromId      int `json:"from_id"`
    Attachments []Attachment
}

where Attachment is described like this

type Attachment struct {
    Type   string
    Fields map[string]interface{}
}

and Fields field is map that contains fields from "photo" or "audio" object of attachment in JSON.

Here is the code I've written to accomplish my task:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "reflect"
    "strings"
    "unicode"
)

type Response struct {
    Id          int `json:"id"`
    FromId      int `json:"from_id"`
    Attachments []Attachment
}

type Attachment struct {
    Type   string
    Fields map[string]interface{}
}

func (this *Attachment) UnmarshalJSON(b []byte) (err error) {
    type innerAttachment struct {
        Type  string
        Audio map[string]interface{}
        Photo map[string]interface{}
    }

    inAt := innerAttachment{}
    *this = Attachment{}

    if err = json.Unmarshal(b, &inAt); err == nil {
        this.Type = inAt.Type

        a := []rune(inAt.Type)
        a[0] = unicode.ToUpper(a[0])

        v := reflect.ValueOf(inAt)

        m := v.FieldByName(string(a)).Interface()
        this.Fields = m.(map[string]interface{})
    }

    return
}

func main() {
    encoded := `
    {
        "id": 123,
        "from_id": 234,
        "attachments": [
            {
                "type": "audio",
                "audio": {
                    "artist": "Van Halen",
                    "title": "Eruption"
                }
            },
            {
                "type": "photo",
                "photo": {
                    "id": 123,
                    "url": "http://someurl.com"
                }
            }
        ]
    }
    `

    response := &Response{}
    reader := strings.NewReader(encoded)
    err := json.NewDecoder(reader).Decode(&response)
    if err != nil {
        log.Fatal(err)
    }

    for _, v := range response.Attachments {
        fmt.Println(v.Type)
        for key, value := range v.Fields {
            fmt.Printf("%s => %s\n", key, value)
        }
        fmt.Println("")
    }
}

Is my code OK or maybe there's more Go'ish way to unmarshal JSON provided above?


texts:
I have only been coding for a short time and I have written these two functions and am looking to optimise them. If anyone could point out things that could be done better it would be much appreciated.
Please Note:
This code has been reviewed/improved using the suggestions below, take a look:
# Python 3.4.1
# Function to check if a number is prime

# Takes integer, returns the factors
def findFactors(num):
    # Create variable to hold the factors and add 1 and itself (all numbers have these factors)
    factors = [1, num]

    # For each possible factor
    for i in range(2, int(num/4) + 3):
        # Check that it is a factor and that the factor and its corresponding factor are not already in the list
        if num % i == 0 and i not in factors and int(num/i) not in factors:
            # Add it and its corresponding factor to the list
            factors.append(i)
            factors.append(int(num/i))

    return factors

# Takes an integer, returns true or false
def isPrime(number):
    number = int(number)

    # Check if the only factors are 1 and itself and it is greater than 1
    if len(findFactors(number)) == 2 and number > 1:
        return True

    return False


texts:
A modified review request has been made here.

Can I please have someone review this simple database design below and tell me if this is the correct way to achieve what I want to do?

What I am trying to do:

When a cardID is deleted this cascades and deletes the surveyID
    associated row.
When a trackID is deleted this cascades and deletes the cardID
    associated  row and its associated surveyID row.

ENTITY RELATIONSHIP DIAGRAM

MYSQL CODE

CREATE TABLE `Card` (
 `cardID` int(11) NOT NULL AUTO_INCREMENT,
 `trackID` int(11) NOT NULL,
 `fName` varchar(21) NOT NULL,
 `mName` varchar(1) DEFAULT NULL,
 `lName` varchar(21) DEFAULT NULL,
 `email` varchar(40) NOT NULL,
 `isMember` int(1) NOT NULL,
 PRIMARY KEY (`cardID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

CREATE TABLE `Survey` (
 `surveyID` int(11) NOT NULL AUTO_INCREMENT,
 `cardID` int(11) NOT NULL,
 `trackID` int(11) NOT NULL,
 `q0` int(1) NOT NULL,
 `q1` int(1) DEFAULT NULL,
 `q2` int(1) DEFAULT NULL,
 `q3` int(1) DEFAULT NULL,
 `q4` int(1) DEFAULT NULL,
 `q5` int(1) DEFAULT NULL,
 PRIMARY KEY (`surveyID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`)  ON UPDATE CASCADE,
 FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`)ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

CREATE TABLE `Tracker` (
 `trackID` int(11) NOT NULL AUTO_INCREMENT,
 `tName` varchar(21) DEFAULT NULL,
 `tDesc` varchar(50) DEFAULT NULL,
 PRIMARY KEY (`trackID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


texts:
I have a flow where if a certain condition is true then I should take another approach. That condition can be triggered by different scenarios. But each condition test must be done only if the last one failed. Once a condition is true there is no further logical tests to do. My question is how to do that in an elegant way, the way I'm doing it right now requires an indentation for each condition.

    StatusCode statusCode = null;
    boolean invokeService = true;
    CardPort cardPort = findCardPort(card, port);
    if (cardPort == null) {
        statusCode = StatusCode.CARD_PORT_NOT_FOUND;
    } else {
        Sim sim = cardPort.getSim();
        if (sim == null) {
            statusCode = StatusCode.CARD_WITHOUT_SIM;
        } else {
            User user = sim.getUser();
            if (user == null) {
                statusCode = StatusCode.SIM_WITHOUT_USER;
            }
        }
    }

    if (statusCode != null) {
        invokeService = false;
    }


texts: Design Pattern for initializing Properties of a ViewModel which only serves a display purpose

texts:
It's a question which lies me for years on the tongue.

Given a LoginViewModel:

public class LoginViewModel : ViewModelBase
{
    public string Email { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
    public string ReturnUrl { get; set; }

    public IEnumerable<AuthenticationScheme> AuthenticationSchemes { get; set; }
}

Typically in Mvc, you need this ViewModel in a GET Request, and (if the request failed) in a POST request.

So here we have a simple LoginController:

public class LoginController : Controller
{
    private readonly ConmaniaSignInManager _signInManager;

    public LoginController(ConmaniaSignInManager signInManager)
    {
        _signInManager = signInManager;
    }

    [HttpGet]
    public async Task<IActionResult> Index(string returnUrl = null)
    {
        var model = new LoginViewModel
        {
            ReturnUrl = returnUrl,
            AuthenticationSchemes = await _signInManager.GetExternalAuthenticationSchemesAsync() //call 1
        };
        return View(model);
    }

    [HttpPost]
    public async Task<IActionResult> Index(LoginViewModel model)
    {
        if (!ModelState.IsValid)
        {
            model.AuthenticationSchemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); //call 2
            return View(model);
        }
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, true);
        if (result.Succeeded)
        {
            return LocalRedirect(Url.GetLocalUrl(Url.GetLocalUrl(model.ReturnUrl)));
        }

        //... Removed for readability

        model.AuthenticationSchemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); //call 3
        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return View(model);
    }
}

The first 4 properties of the view model doesn't matter, since they are fields which are getting populated on Post by the ModelBinder.

However the property AuthenticationSchemes gets populated 3 times, even in this simple Login case. Other ViewModels in a typical application can have many more such properties.

In previous Versions of Mvc I have cheated by retrieving the data in the ViewModel by using the getter. That was ofcorse bad design.

So my concern is, is there any Design Pattern to make my controller less painfull (DRY etc)?

I thought about making a Method void PopulateLoginViewModel(LoginViewModel model), and calling this 3 times* instead, but I am not sure if this would be correct.

I also thought about a Service which is injected into the View which has a GetExternalAuthenticationSchemesAsync() method, so the ViewModel does not need to know it. But from what I have read, that is also bad practise.

* I do not want to populate the ViewModel if the user will get redirected anyway.


texts:
Problem

I need to read custom text input of a sample document object model (DOM) represented in a json format from a file and store it in a struct I've defined as DomNode. I need help on properly navigating these DOM elements from the input file and keeping track of the child node pointers at each level of the dom tree.

The read_dom_hierarchy has a block comment that shows the contents of dom.txt.

I can not use any 3rd party libraries for this problem. Assume dom.txt will always have exactly 18 lines and it's content will not change.

Source

#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>

struct DomNode
{
    int level;
    std::string tag;
    std::string id;
    std::vector<DomNode*>child;
};

static void read_dom_hierarchy(std::string* dom)
{
    // reading custom input on my local machine, that follows this structure
    /*
        {
            "tag": "div",
            "id": "first",
            "children":
            [
                {
                    "tag": "span",
                    "id": "second",
                    "children":
                    [
                        {
                            "tag": "span",
                            "id": "third"
                        }
                    ]
                }
            ]
        }
    */
    std::ifstream file_stream("dom.txt");
    std::string line;
    int i = 0;
    while (getline(file_stream, line))
    {
        dom[i] = line;
        i++;
    }
}

static void parse_element_data(std::string& s)
{
    s = s.substr(s.find(":") + 2);
    s.erase(s.find(","));
    s.erase(s.find("\""));
}

static void construct_dom_from_text(std::string* dom, DomNode* node, std::stack<std::string> token)
{
    DomNode* current = node;

    int level = 1;
    for (int i = 0; i < 18; i++)
    {
        std::string line = dom[i];
        if (line.find("{") != std::string::npos)
        {
            token.push(line);
        }
        else if(line.find("}") != std::string::npos)
        {
            if (token.top() == "{") {
                token.pop();
                return;
            }
            else {
                token.push(line);
            }
        }
        if (line.find("[") != std::string::npos)
        {
            token.push(line);
            ++level;
        }
        else if (line.find("]") != std::string::npos)
        {
            if (token.top() == "[") {
                token.pop();
                --level;
            }
            else {
                token.push(line);
            }
        }

        if (level == 0) { return; }

        // store dom current data
        if (line.find("tag") != std::string::npos) {
            parse_element_data(line);
            current->tag = line;
        }
        else if (line.find("id") != std::string::npos) {
            parse_element_data(line);
            current->id = line;
        }
        else if (line.find("children") != std::string::npos) {
            current->level = level;
            DomNode* c = new DomNode();
            current->child.push_back(c);
        }
    }
}

int main()
{
    std::string dom[18];
    read_dom_hierarchy(dom);

    DomNode* root = new DomNode();
    std::stack<std::string> token;
    construct_dom_from_text(dom, root, token);
}


texts:
I wrote the code that would scrap Finviz for tickers and href that attach to the ticker. I tested with multi-page as well as one page. I'm new to python programming and therefore believe my code is terrible. I'm hoping someone would help me review it and point out ways to improve it. My goal is to have the code more scalable than what I have now.

import bs4 as bs
import requests

class finviz_crawler():
    def requesting(self,type):
        items=1
        baseurl='https://finviz.com/screener.ashx?v=111'
        if type == 'sp500':
            firstpage=baseurl+'&f=idx_sp500&o=ticker'
        elif type == "China":
            firstpage=baseurl+'&f=cap_largeover,geo_china'
        finalurl=firstpage
        headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
        resp=requests.get(finalurl,headers=headers)
        soup = bs.BeautifulSoup(resp.text,"lxml")
        table=soup.findAll('td',{'class':'screener-body-table-nw'})
        maxpage_a_tag=[]
        maxpage_td=soup.findAll('td',{'class':'body-table'},bgcolor="#ffffff",valign="top",width="100%")
        tickerdict={}
        for tags in maxpage_td[0].findAll('a'):
             maxpage_a_tag.append(tags)
        if not maxpage_a_tag:
            maxpage=1
        elif (maxpage_a_tag[-1].text=="next"):
            maxpage=maxpage_a_tag[-2].text
        else:
            maxpage=maxpage_a_tag[-1].text
        for page in range(int(maxpage)):
            resp=requests.get(finalurl,headers=headers)
            soup = bs.BeautifulSoup(resp.text,"lxml")
            table=soup.findAll('td',{'class':'screener-body-table-nw'})
            for row in table:
                 ticker_rows=row.findAll('a',{'class':'screener-link-primary'},href=True)
                 for tickers in ticker_rows:
                     tickerdict[tickers.text]=tickers['href']
            items+=20
            finalurl="{}{}{}".format(firstpage,"&r=",str(items))
        print(tickerdict)

Call the class using finviz_crawler().requesting('China')


texts:
A few days ago I asked this question and I've got an answer to work with interfaces. I've tweaked around with this to get myself a INI parser class.

<?php

<?php

require "Parser.php";

class IniParser implements Parser
{

    private $data = [];

    /**
     * Parses the data from a configuration file and stores it into a array.
     *
     * @param $file string The file where the configuration / credentials / settings exist.
     * @param string $section The section within the configuration file, this is optional
     * @throws Exception
     */
    public function parse ($file, $section = "") {
        if (!$this->isValidated('file', $file)) {
            throw new Exception("File seems not to work..");
        }
        $credentials = parse_ini_file($file, true);
        foreach ($credentials as $key => $values) {
            if (!$this->isValidated('values', $credentials, $section)) {
                throw new Exception("Values or section doesn't exist");
            } elseif ($key !== $section) {
                continue;
            }
            $this->data = $values;
        }
    }

    /**
     * This function returns the value from a key inside a array.
     *
     * @param $key mixed Key of the array
     *
     * @throws Exception
     * @return mixed Value of the selected key by the parameter
     */
    public function get ($key) {
        if (!isset($this->data[$key])) {
            throw new Exception("Value doesn't exist in key: " . $key);
        }
        return $this->data[$key];
    }

    /**
     * @param $type
     * @param $data
     * @param string $section
     * @return bool
     *
     * note: when validating the values, were validating an array.
     */
    public function isValidated ($type, $data, $section = "") {
        switch ($type) {
            case "file":
                return file_exists($data) || is_file($data);
            case "values":
                //1. Check if $data is an array
                //2. Section is set
                return is_array($data) || isset($data[$section]);
        }
        return false;
    }
}

When calling the parse() method in this class you  get a specific .ini file (first argument) and parses the values within a specific section.

When calling the get() method in this class, you get the value of the chosen key.

This are the required methods for it:

<?php

interface Parser
{
    public function parse($file, $section);

    public function get($key);

}

For my connection, I use this class:

<?php
class Connection
{
    private $state;
    private $credentials;

    public function __construct(Parser $credentials) {
        $this->credentials = $credentials;
    }

    public function initialize() {
        if ($this->isInitialized()) {
            throw new PDOException("Database connection seems already to be open");
        }
        $this->state = new PDO($this->credentials->get('engine') . ":host=" . $this->credentials->get('host') . ";dbname=" . $this->credentials->get('dbname'), $this->credentials->get('username'), $this->credentials->get('password'));
    }

    public function terminate() {
        if (!$this->isInitialized()) {
            throw new PDOException("Connection doesn't seem to be open");
        }
        $this->state = null;
    }

    public function isInitialized() {
        return $this->state instanceof PDO;
    }
}

To create a new connection, I use this piece of code:

<?php
/**
 * User: Bas
 * Date: 6-10-2014
 * Time: 21:24
 */

require "INIParser.php";
require "Connection.php";

$credentials = new IniParser();
$credentials->parse("configuration.ini", "Connection");

try {
    $con = new Connection($credentials);
    $con->initialize();

} catch (Exception $e) {
    echo $e->getMessage();
}


texts: Are these try/catch blocks cluttering the code?

texts:
The following program reads a stream and creates a two dimensional std::vector.

I'm trying to find an elegant way to handle the errors and recover from them as much as possible while still reporting the problems encountered.

It feels as though my nice clean functions are getting more and more cluttered as I add the error handling.

Is this the best way?

#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <stdexcept>

namespace {

    using Grid_row = std::vector<int>;
    using Grid = std::vector<Grid_row>;

    class Partial_value : public std::runtime_error {
    public:
        Partial_value(std::string text, int val) : std::runtime_error{text}, val{val} {}
        int val{};
    };

    int convert(const std::string& text)
    {
        int val{};
        try {
            val = std::stoi(text);
        }
        catch(const std::exception& e) {
            throw Partial_value{"Due to error: \"" + std::string{e.what()} +"\"; Could not convert " + text + " to integer. Value was converted to 0.", val};
        }
        std::ostringstream oss{};
        oss << val;
        if(oss.str() != text)
            throw Partial_value{"Could not fully convert " + text + " to integer. Value was converted to " + oss.str() + ".", val};
        return val;
    }

    std::istream& operator >> (std::istream& is, Grid_row& grid_row)
    {
        std::string term{};
        while(is >> term) {
            int val{};
            try {
                val = convert(term);
            }
            catch(const Partial_value& e) {
                val = e.val;
                std::cerr << e.what() << '\n';
            }
            grid_row.push_back(val);
        }
        return is;
    }

    std::istream& operator >> (std::istream& is, Grid& grid)
    {
        std::string line{};
        while(std::getline(is, line)) {
            std::istringstream is_line{line};
            Grid_row grid_row{};
            is_line >> grid_row;
            grid.push_back(grid_row);
        }
        return is;
    }

    std::ostream& operator << (std::ostream& os, const Grid& grid)
    {
        for(const auto& i : grid) {
            for(const auto& j : i) {
                os << std::setw(5) << j;
            }
            os << '\n';
        }
        return os;
    }
}

auto input_text{
R"(3 -1 -3 -1 -4
40 7.5 3 1 1
10 -2 -Z 1 1
10 0 1 0 -1
)"};

int main() {
    std::istringstream is{input_text};
    Grid grid{};
    is >> grid;
    std::cout << grid;
    return 0;
}

Produces:

Could not fully convert 7.5 to integer. Value was converted to 7.
Due to error: "invalid stoi argument"; Could not convert -Z to integer. Value was converted to 0.
    3   -1   -3   -1   -4
   40    7    3    1    1
   10   -2    0    1    1
   10    0    1    0   -1


texts: How to convert my classes to Dependency injection?

texts:
I am still learning to develop my skills in OOP.

It uses a combination of the factory and its real singletons?

As I did more research, I have realized this design pattern is bad because of global state and it is hard to test.

I can't figure how how to convert this OOP to Dependency injection?

Section Class

class Section
{
    // Array contains of instantiations of Section
    protected static $instance;

    // Validation  instance of validation
    public $validation;

    public $something;

    // instance method returns a new section instance.
    public static function instance($name = "default")
    {
        if ($exist = static::getInstance($name)) {
            return $exist;
        }

        static::$instance[$name] = new static($name);
        return static::$instance[$name];
    }

    // Return a specific instance
    public static function getInstance($instanceKey = null)
    {
        if (!isset(static::$instance[$instanceKey])) {
            return false;
        }
        return static::$instance[$instanceKey];
    }

    // Get Validation instance or create it
    public function validation()
    {
        if ($this->validation instanceof Validation) {
            return $this->validation;
        }

        if (empty($this->validation)) {
            $this->validation = Validation::instance($this);
        }

        return $this->validation;
    }

    public function add($something)
    {
        $this->something = $something;
    }

}

Validation Class (Just a random name for now)

class Validation
{
    // Related section instance
    public $section;

    protected function __construct($section)
    {
        $this->section = $section;
    }

    public static function instance($section = "default")
    {

        if (is_string($section)) {
            $section = Section::instance($section);
        }

        return new static($section);
    }

    public static function getInstance($instanceKey = null)
    {
        $temp = Section::getInstance($instanceKey);
        if (!$temp) {
            return false;
        }

        return $temp->validation();
    }

    // Alias for $this->section->add()
    public function add($name) {
        $this->section->add($name);
        return $this->section->something;
    }
}

Testing:

$section = Section::instance("Monkey");
$validation = $section->validation();
echo $validation->add("This is just a test");


texts: Unit testing for a blog post model on Google App Engine

texts:
It is my second day into software testing and I am currently testing my database, handlers, and functions. I am wondering if I am taking the right approach as this is the first time testing my web app. I'd love to get some advice or feedback to improve my tests!

Below is the code for data model.

class Post(ndb.Model):
    content = ndb.StringProperty(required = True)
    user_key = ndb.KeyProperty(User)
    created = ndb.DateTimeProperty(auto_now_add = True)
    last_modified = ndb.DateTimeProperty(auto_now = True)
    user = ndb.StringProperty(required = True)
    city = ndb.StringProperty()
    coords = ndb.GeoPtProperty()

    def render(self):
        self._render_text = self.content.replace('\n', '<br>')
        params = dict(p = self)

        return render_str("post.html", **params)

    def as_dict(self):
        time_fmt = '%c'
        if self.coords is None:
            coords = "None"
        else:
            coords = self.coords.lat, self.coords.lon
            lat, lon = coords[0], coords[1]
            coords = {'latitude': lat, 'longitude': lon}

        d = {'user': self.user,
             'content': self.content,
             'city': self.city,
             'coords': coords,
             'created': self.created.strftime(time_fmt),
             'last_modified': self.last_modified.strftime(time_fmt)}
        return d

Here's the function.

def make_secure_val(val):
    return '%s|%s' % (val, hmac.new(secret, val).hexdigest())

Here's my tests

def test__PostModel(self):
    post_content = "test content"
    user = "testUser"
    city = "test city"
    u_key = ndb.Key('User', int("123"), parent=users_key())

    test_model = Post
    p = test_model(parent=post_key(), content=post_content, user=user, user_key=u_key, city=city)
    key = p.put()

    p2 = key.get()

    self.assertEqual('test content', p2.content)
    self.assertEqual(u_key, p2.user_key)
    self.assertEqual('testUser', p2.user)
    self.assertEqual('test city', p2.city)

    try:
        p = test_model()
        key = p.put()
        result = True
    except:
        result = False

    self.assertFalse(result)

def test__get_coords(self):
    coords = "43.653226,-79.383184"
    lat, lon = coords.split(",")
    coords = {"latitude": lat, "longitude": lon}
    coords = json.dumps(coords)
    return coords

    assertIs({"latitude": "43.653226", "longitude": "-79.383184"}, coords)

def test__make_secure_val(self):
    val = "test"
    secret ="testsecret"
    test_result = '%s|%s' % (val, hmac.new(secret, val).hexdigest())

    self.assertEqual("test|e91f3aaeb48b71fc68bddc8ea34dda24", test_result)


texts:
I've written the following piece of code to sort my list, which is the data source to my GridView, depending on the column to be sorted on. It seems to me that there is quite a bit of redundancy, and the below code may be optimized. Also, I wanted to apply the strategy pattern (note that I'm just starting out with design patterns), but it seems to me like it would be overkill. Please suggest how the following may be better written.

User is my class with several properties, including but not limited to Role, Policy, and Name. The other properties may also be included in this method, so it might grow. SortingOrder is an enum with 2 values, Ascending and Descending. SortExpression contains the value based on which the data is to be sorted.

    private void SortUsers(ref List<User> userList)
    {
        if (SortOrder == SortingOrder.Ascending)
        {
            switch (SortExpression)
            {
                case "Role":
                    userList = userList.OrderBy(user => user.Role).ToList();
                    break;
                case "Policy":
                    userList = userList.OrderBy(user => user.Policy).ToList();
                    break;
                default:
                    userList = userList.OrderBy(user => user.Name).ToList();
                    break;
            }
        }
        else
        {
            switch (SortExpression)
            {
                case "Role":
                    userList = userList.OrderByDescending(user => user.Role).ToList();
                    break;
                case "Policy":
                    userList = userList.OrderByDescending(user => user.Policy).ToList();
                    break;
                default:
                    userList = userList.OrderByDescending(user => user.Name).ToList();
                    break;
            }
        }
    }


texts: Small function and level of abstraction - clean code - refactor further

texts:
In the book Clean Code from Robert C. Martin are given many recommendations. Two of them are

to keep functions small and
within a function to only have one level of abstraction.

I already cleaned the following method up a bit by extracting a few methods (RemoveFontColor(), RemoveTextHighlight()). But i am not sure if the few-liners (font-style, font-weight, etc.) should be extracted into a method as well. The advise from the author is to not mix different-levels of abstraction within a function because this could lead to other details creeping in. This would mean that even the two liners will be extracted into their own methods.

The partly refactored code example

private string Fix(FixPreferences preferences,string value)
{
    if (preferences.IsRemoveBold) {
        value = value.Replace("font-weight:bold", "font-weight:normal");
        value = value.Replace("font-weight: bold", "font-weight:normal");
    }
    if (preferences.IsRemoveItalics) {
        value = value.Replace("font-style:italic;", "font-style:normal;");
        value = value.Replace("font-style: italic;", "font-style:normal;");
    }
    if (preferences.IsRemoveFontColor) {
        value = RemoveFontColor(value);
    }
    if (preferences.IsRemoveTextHighlight) {
        value = RemoveTextHighlight(value);
    }
    if (preferences.IsRemoveStrikethrough){
       value =
        value.Replace("text-decoration: line-through;", "text-decoration:none;");
       value =
        value.Replace("text-decoration:line-through;", "text-decoration:none;");
    }
    if (preferences.IsRemoveUnderline)
    {
      value =
       value.Replace("text-decoration: underline;", "text-decoration:none;");
      value =
       value.Replace("text-decoration:underline;", "text-decoration:none;");
    }
    return value;
}

Update

I changed to extract even the few lines - but it still looks not pretty.

    private string Fix(ChangeLogFixOperationPreferences preferences,string value)
    {
        if (preferences.IsRemoveBold)
                value = RemoveBold(value);

        if (preferences.IsRemoveItalics)
                value = RemoveItalics(value);

        if (preferences.IsRemoveFontColor)
                value = RemoveFontColor(value);

        if (preferences.IsRemoveTextHighlight)
                value = RemoveTextHighlight(value);

        if (preferences.IsRemoveStrikethrough)
                value = RemoveStrikethrough(value);

        if (preferences.IsRemoveUnderline)
                value = RemoveUnderline(value);

        if (preferences.IsResetFontSize)
                value = ResetFontSize(value);

        return value;
    }

Is there a better way - for example to put the preferences and the methods into a dictionary and for each preference that is set to true the function from the dictionary is called within a loop?

My question

How would you refactor the code above?
Are there any ways to group the different font-* or text-decoration:* togehter in one function? Would that be wise since it violates the single responsibility pattern (SRI)?
Update: Would you recommend calling a function from a dictionary

store functions in a dictionary or may be
call method dynamically or
from Jon Skeet storing functions in a dictionary by using Action


texts:
I was trying to solve the problem where given a larger string and an array/list of smaller string, we need to make the determination whether the larger string contains each of the smaller strings. I realized one way to do it would be to create a suffix tree for the larger string and then look for each of the smaller strings within the suffix tree.

My SuffixTree is essentially a Node which contains a value and a Map of <Character,Node> for its children.

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class SuffixTree{
 class Node{
   private final char currentValue;
   private Map<Character,Node> children;
   Node(){
     this.currentValue = '*';
     this.children = new HashMap<Character,Node>();
   }
   Node(char currentValue){
     this.currentValue = currentValue;
     this.children = new HashMap<Character,Node>();
   }

   char getValue(){
     return this.currentValue;
   }

   void addChild(Node c){
    this.children.put(c.getValue(),c);
   }

   boolean hasChild(Node c){
    return this.children.containsKey(c.getValue());
   }

   Node getChild(Node c){
     return this.children.get(c.getValue());
   }

  public String toString(){
    char currentValue = this.getValue();
    StringBuffer keys = new StringBuffer();
    for(char key:this.children.keySet()){
      keys.append("Current key:"+key+"\n");
    }
     return "Current value:"+currentValue+"\n"+
        "Keys:"+keys.toString();
   }
  }

  private Node root;

  private void log(Object l){
     System.out.println(l);
  }
  /*
   * Helper method that initializes the suffix tree
   */
  private Node createSuffixTree(String source,Node root){
    for(int i=0;i<source.length();i++){
      Node parent = new Node(source.charAt(i));
      if(root.hasChild(parent)){
        parent = root.getChild(parent);
      }
      Node current = parent;
      for(int j=i+1;j<source.length();j++){
        Node temp = new Node(source.charAt(j));
    if(current.hasChild(temp)){
      temp = current.getChild(temp);
    }else{
      current.addChild(temp);
    }
        current = temp;
      }
      root.addChild(parent);
    }
    return root;
  }

  /*
   Creates the suffix tree from the given string
   */
  public SuffixTree(String source){
    this.root = createSuffixTree(source,new Node());
  }

  void printMap(Map<Character,Node> map){
     for(char c:map.keySet()){
      System.out.println("Current node has child"+c);
    }
  }

  boolean search(String target){
    Map<Character,Node> rootChildren = this.root.children;
   for(char c:target.toCharArray()){
      if(rootChildren.containsKey(c)){
        rootChildren = rootChildren.get(c).children;
      }else{
        return false;
      }
    }
    return true;
  }

   public static void main(String[] args){
    SuffixTree sTree = new SuffixTree("bananas");
    List<String> input = new ArrayList<String>(){{
                 add("ba");
                 add("ban");
                 add("ana");
                 add("anas");
                 add("nan");
                 add("anans");
                 add("ananas");
                 add("n");
                 add("s");
                 add("as");
                 add("naab");
                 add("baan");
                 add("aan");
                }};
    for(String i:input){
      String exists = "exists";
      if(!sTree.search(i)){
        exists = "doesn't exist";
      }
      System.out.println("Input:"+i+" "+exists);
    }
   }
}


texts: Obfuscation of email and phone using JavaScript

texts:
I'm creating a new website, so I am thinking about how to protect my email address and phone number against crawlers, I actually mean email harvesters (most of which I suppose don't have JavaScript enabled, but I don't have any proof of it). What I do now is definitely security by obscurity or obfuscation (I might be confusing the two terms), as I want the email address to be normally visible and clickable by the user.

I started with resurrecting my 10+ years old code and editing it a little. The basics remain the same as 10+ years ago when I first coded this principle.

My question for Code Review SE - as I already posted Is this a valid option? in Security SE question - is rather clear. Primarily, I am interested in a review of this piece of code:

HTML part

test [a.t] example [d.o.t] com
+444 444 6[eight]6 6[eight][eight]

JavaScript part

function fix_m_link()
{
    var item1 = '@'; var item2 = '.'; var m_clear_text = 'test' + item1 + 'example' + item2 + 'com';
    document.getElementById('m_link').innerHTML = '' + m_clear_text + '';
}

function fix_t_link()
{
    var item8 = '8'; var t_with_spaces = '444 6' + item8 + '6 6' + item8 + item8; var t = t_with_spaces.replace(/\s+/g, '');
    document.getElementById('t_link').innerHTML = '' + '+444 ' + t_with_spaces + '';
}

These functions I then call in the body's onload.


texts: SSL Mutual Authentication, with one specific Root Certificate

texts:
For a new server application we are developing; I implemented a method to verify SSL certificates.
The use of this method is Mutual Authentication: to prove that the server and client are who they say they are, using a Root Certificate and Intermediate Certificate that I've created myself.

The SslStream is created as such (server-side):

this.stream = new SslStream(tcpClient.GetStream(), false, SSLVerification.VerifyCertificate, null);
var certificate = new X509Certificate2(Config.Instance.CertificatePath, Config.Instance.CertificatePassword);
stream.AuthenticateAsServer(certificate, true, SslProtocols.Tls, false);

And Client side (almost) the same:

SslStream stream = new SslStream(client.GetStream(), false, SSLVerification.VerifyCertificate, null);
X509Certificate2 certificate = new X509Certificate2(Config.Instance.CertificatePath, Config.Instance.CertificatePassword);
stream.AuthenticateAsClient("our.server.name", new X509Certificate2Collection(certificate), System.Security.Authentication.SslProtocols.Tls, false);

Both snippets make use of the same library, in which the SslVerification.VerifyCertificate() can be found.

The implementation of that method is as follows:

public static bool VerifyCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
  chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

  var rootCert = new X509Certificate2(X509Certificate.CreateFromCertFile(rootCertificate));
  var interCert = new X509Certificate2(X509Certificate.CreateFromCertFile(intermediateCertificate));

  chain.ChainPolicy.ExtraStore.Add(interCert);
  chain.ChainPolicy.ExtraStore.Add(rootCert);

  var isChainValid = chain.Build(new X509Certificate2(certificate));

  return isChainValid && chain.ChainElements.OfType<X509ChainElement>().Any(c => c.Certificate.Thumbprint == rootCert.Thumbprint);
}

After the SslStream has been set-up, we run a check (server-side) on the common-name to verify exactly which client we are talking to. We just simply look up the Common Name (Certificate.Subject) in a database table.

My questions are:

Is this the correct way to ensure that the certificate has been signed by our specific Root Certificate, and not any other signing certificate?
Is there any way to fool this implementation?
Maybe any other pitfalls in the implementation above?


texts: Implementation of iterator pattern for any array of elements

texts:
I have implemented Iterator pattern:

The interface Container.java:

public interface Container<T> {

    Iterator<T> getIterator();
}

Interface Iterator.java:

public interface Iterator<T>{

    boolean hasNext();

    T next();
}

Class ResourceContainer.java:

public class ResourceContainer<T extends Serializable> implements Container<T>{

    private T names [];

    public ResourceContainer(T [] names){
        this.names = names;
    }

    @Override
    public Iterator<T> getIterator() {
        return new ResourceIterator<T>(this.names);
    }

}

Class ResourceIterator.java:

public class ResourceIterator<T extends Serializable> implements Iterator<T>{

    private T [] names;
    private int index;

    public ResourceIterator(T [] names){
        this.names = names;
    }

    @Override
    public boolean hasNext() {
        boolean flag = false;

        if(this.index < this.names.length){
            flag = true;
        }

        return flag;
    }

    @Override
    public T next() {
        return this.names[index++];
    }

}

An EmployeeVO class:

import java.io.Serializable;

public class EmployeeVO implements Serializable{

    private String name;
    private Integer id;
    private String departmentName;

    public EmployeeVO(Integer id, String name, String departmentName){
        this.name = name;
        this.id = id;
        this.departmentName = departmentName;
    }

    @Override
    public String toString(){
        StringBuffer strb = new StringBuffer();

        strb.append(" Id \"").append(this.id).append("\"")
            .append(" Name \"").append(this.name).append("\"")
            .append(" Department \"").append(this.departmentName).append("\"");

        return strb.toString();
    }
}

Main class:

public class MainClass {

    public static void main(String [] args){

        Integer [] nums = new Integer[]{12,23,100,1};

        Container<Integer> container01 = new ResourceContainer<Integer>(nums);
        Iterator<Integer> itr01 = container01.getIterator();

        while(itr01.hasNext()){
            System.out.println(itr01.next());
        }

        String [] names = new String[]{ "Alan", "Jim", "Nicholas" };

        Container<String> container02 = new ResourceContainer<String>(names);
        Iterator<String> itr02 = container02.getIterator();

        while(itr02.hasNext()){
            System.out.println(itr02.next());
        }

        EmployeeVO [] employees = new EmployeeVO[] {
        new EmployeeVO(23, "Alan Turing", "Computer Science"),
        new EmployeeVO(45, "Jim Klaus", "Mechanical Engineering"),
        new EmployeeVO(76, "Nicholas Johanson", "Electrical Engineering")
        };

        Container<EmployeeVO> container03 = new ResourceContainer<EmployeeVO>(employees);
        Iterator<EmployeeVO> itr03 = container03.getIterator();

        while(itr03.hasNext()){
            System.out.println(itr03.next());
        }
    }
}

The output of when I run MainClass from the command line:

12
23
100
1
Alan
Jim
Nicholas
Id "23" Name "Alan Turing" Department "Computer Science"
Id "45" Name "Jim Klaus" Department "Mechanical Engineering"
Id "76" Name "Nicholas Johanson" Department "Electrical Engineering"

By following the code, please review and let me know whether I implemented the iterator pattern properly. Is the usage of generics proper? Can the implementation be further improved?


texts:
I just wrote a basic DTMC algorithm focused on generating names, though it could be used to generate lots of other things. It's designed to be run from the command line, so input is taken from a file, with a couple of options specified on the command line.

I'm specifically looking for these things, though any other advice is also of course welcome:

Ways to make it faster or more memory-efficient
Ways to make it more idiomatic for Ruby

I'm perfectly fine with changing the input format, though I'd prefer if it stayed the same. I'm also fine with making the code a bit more unreadable if it helps make it more efficient or shorter, as long as it's still somewhat understandable and easy to maintain.

This is my full code (version with -h help available here):

#Constants!
LINE_PART_DELIMITER = '|'
LINK_DELIMITER = ';'
LINK_HALF_MARK = ','
DEFAULT_NAME_COUNT = 10

# End with the standard error message format -- makes it easy to stay consistent
def error(code, message)
  puts "Error #{code}: #{message}"
  puts 'Run this script with -e to see a list of error codes.'
  abort "name_gen.rb: Error #{code}: #{message}"
end

# Keys are candidates, values are probabilities
def weighted_random_choice(picking_from)
  current = 0
  max = picking_from.values.inject :+
  r_val = rand max
  picking_from.each { |candidate, probability|
    current += probability
    return candidate if r_val < current
  }
  raise "r_val>max? #{r_val>max}. Error while picking a weighted random value from #{picking_from}"
end

#Parsing the commandline arguments and suchlike
syllable_separator = (/-d./ === ARGV[-1]) ? ARGV.pop[2..-1] : ''
name_count = (/\d+/ === ARGV[-1]) ? ARGV.pop.to_i : DEFAULT_NAME_COUNT
file = ARGV.join ' '

#Parsing the file
syllables = Hash.new false
start = Hash.new 0
begin
  IO.foreach(file) { |line|
    name, start_prob, end_prob, links = line.split LINE_PART_DELIMITER
    error 2, "`#{line}`" if links.nil? || end_prob.nil? || start_prob.nil? || name.nil?
    links = links.split(LINK_DELIMITER).inject(Hash.new 0) { |memo, current_pair|
      syl, prob = current_pair.split LINK_HALF_MARK
      (prob = Integer prob) rescue error 3, "`#{name}`: `#{syl}`, `#{prob}`"
      memo[syl.to_sym] += prob
      memo
    }
    links[false] = end_prob.to_i
    syllables[name.to_sym] = links
    start[name.to_sym] += start_prob.to_i
  }
rescue Exception => message
  puts message
  error 1, "`#{file}`"
end

#Validate that all syllables referenced actually exist!
syllables.each { |syllable, links|
  links.each { |link, _|
    error(4, "`#{link}` in `#{syllable}`") if !!link && syllables[link.to_sym].nil?
  }
}

#Generating and printing the names
name_count.times {
  current_syllable = weighted_random_choice start
  name_so_far = [current_syllable.to_s]
  while (current_syllable = weighted_random_choice syllables[current_syllable.to_sym])
    name_so_far << current_syllable.to_s
  end
  puts name_so_far.join syllable_separator
}

And this is an example 'dictionary' file:

a|1|1|b,2;c,2
b|0|3|a,0;c,2
c|0|0|a,1;b,1

And here's a sample of ten names it can generate (with the above dictionary file):

ab
acb
acabcacacb
abca
acacaca
abcacacb
acb
a
acbcacb
a


texts:
I have 3 methods(* BindingSource are bindingsources, context is data context, cache* -are some List for cache operations):

 private void AddUpdateRowDocuments()
        {
            try
            {
                tRANSMITDOCDOCUMENTSRELATIONSBindingSource.EndEdit();
                var t = tRANSMITDOCDOCUMENTSRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_DOCUMENTS_RELATIONS;
                if (t.TRANSMIT_DOC_ID == 0)
                {
                    if (!cachetddrList.Contains(t))
                    {
                        cachetddrList.Add(t);
                    }
                    return;
                }
                context.UpdateObject(t);
            }
            catch (Exception ex)
            {
                logger.ErrorException(string.Empty, ex);
            }
        }
private void AddUpdateRowOrganizations()
    {
        try
        {
            tRANSMITDOCORGANIZATIONRELATIONSBindingSource.EndEdit();
            var t = tRANSMITDOCORGANIZATIONRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_ORGANIZATION_RELATIONS;
            if (t.TRANSMIT_DOC_ID == 0)
            {
                if (!cachetdorList.Contains(t))
                {
                    cachetdorList.Add(t);
                }
                return;
            }
            context.UpdateObject(t);
        }
        catch (Exception ex)
        {
            logger.ErrorException(string.Empty, ex);
        }
    }
private void AddUpdateRowPartators()
        {
            try
            {
                tRANSMITDOCPARTATORRELATIONSBindingSource.EndEdit();
                var t = tRANSMITDOCPARTATORRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_PARTATOR_RELATIONS;
                if (t.TRANSMIT_DOC_ID == 0)
                {
                    if (!cachetdprList.Contains(t))
                    {
                        cachetdprList.Add(t);
                    }
                    return;
                }
                context.UpdateObject(t);
            }
            catch (Exception ex)
            {
                logger.ErrorException(string.Empty, ex);
            }
        }

Any thoughts on how to improve them? My inner sense says that they can be turned into one generic method, but i have little experience with generics, so cant say if i am right.


texts:
I was given this problem in an interview.

  Given two words source and target, and a list of words words, find the
  length of the shortest series of edits that transforms source to
  target. Each edit must change exactly one letter at a time, and each
  intermediate word (and the final target word) must exist in words.

  If the task is impossible, return -1.

  Examples:

source = "bit"
target = "dog"
words = ["but", "put", "big", "pot", "pog", "dog", "lot"]

  Output: 5

  Explanation: bit -> but -> put -> pot -> pog -> dog has 5
  transitions.

source = "no"
target = "go"
words = ["to"]

  Output: -1

def one_letter_difference(current_word, next_word):
      count = 0
      for i in range(len(current_word) -1):

        if current_word[i] != next_word[i]:
          count += 1;
      if count == 1:
        return True
      else:
        return False

    def shortestWordEditPath(source, target, words):
      """
        @param source: str
        @param target: str
        @param words: str[]
        @return: int

      Input: source = "bit", target = "dog"
      words = ["but", "put", "big", "pot", "pog", "dog", "lot"]

      Output: 5
      explanation:
                 1  ->  1   ->   1  ->    1  ->     1
      (source) bit -> but -> put -> pot -> pog -> dog (target)
      has minimum of 5 transitions
        """
      graph = {}

      for i in range(-1, len(words)):
        if i == -1:
          current_word = source
        else:
          current_word = words[i]
        graph[current_word] = []
        for word in range(len(words)):
          next_word = words[word]
          if one_letter_difference(current_word, next_word):
            graph[current_word].append(next_word)

      #perform BFS
      queue = collections.deque()
      seen = set() # visited words
      queue.append([source, 1])
      seen.add(source)

      while len(queue) > 0:
        current, distance = queue.popleft()
        if current == target: return distance
        for neighbor in graph[current]:
          if neighbor not in seen:
            queue.append([neighbor, distance +1])
            seen.add(neighbor)
      return -1

    source = "bit"
    target = "dog"
    words = ["but", "put", "big", "pot", "pog", "dog", "lot"]
    test = shortestWordEditPath(source, target,words)
    print(test)


texts: Finding the year using strtotime vs calculating manually

texts:
I need to calculate at which year a school class has started, given the year they currently are in. For example a class of 2nd graders have started school in 2013, if I pass 2 to the function it should return 2013.

So, I need to take x years and 6 months out of a date, I was wondering which is the better way to do it.

Using strtotime():

function school_started1($years){
    return date('Y', strtotime('now - '.$years.' year - 6 month'));
}

Or calculating it manually:

function school_started2($years){
    $seconds_in_half_a_year = 365.25 * 43200;
    return date('Y', time() - $years * 365.25 * 86400 - $seconds_in_half_a_year);
}

I'm thinking the second method would be better because it doesn't have to do any parsing and stuff ( not quite a fan of parsing ).  I can do the math myself, are there any benefits/downsides to using strtotime?  What do you think?


texts:
I realised that what I was doing wasn't particularly smart, so I switched to a different approach.  This costs more dynamic allocations but has a much simpler implementation:

#pragma once

#include <boost/utility.hpp>
#include <set>
#include <map>

//! A map of types to values.
//!
//! Associative container which allows mapping of types to values of that
//! type.
class TypeMap : boost::noncopyable {
    typedef void (*destruct_func)(void*);
    class TypeMapStaticInstance : boost::noncopyable {
        destruct_func destroy_;
        std::map<TypeMap const*, void*> map_;

      public:
        TypeMapStaticInstance(destruct_func f)
          : destroy_(f) {}

        void*& get(TypeMap const* tm) {
            return map_[tm];
        }

        void const* cget(TypeMap const* tm) const {
            auto element = map_.find(tm);
            if (element != map_.end())
                return element->second;
            return nullptr;
        }

        void remove(TypeMap const* tm) {
            auto element = map_.find(tm);
            destroy_(element->second);
            map_.erase(element);
        }
    };

    template<typename T>
    class TypeMapDetail {
        TypeMapDetail() = delete;

        static void destroy_impl(void* p) {
            delete static_cast<T*>(p);
        }

      public:
        static TypeMapStaticInstance map_;

        static T& get(TypeMap const* p) {
            auto& element = map_.get(p);
            if (!element)
                element = new T();
            return *static_cast<T*>(element);
        }

        static T const* cget(TypeMap const* p) {
            return static_cast<T const*>(map_.cget(p));
        }
    };

    std::set<TypeMapStaticInstance*> members_;
  public:
    //! Retrieve the data associated with the given type.
    template<typename T>
    T& get() {
        members_.insert(&TypeMapDetail<T>::map_);
        return TypeMapDetail<T>::get(this);
    }

    template<typename T>
    T const* cget() const {
        return TypeMapDetail<T>::cget(this);
    }

    ~TypeMap() {
        for (auto m : members_) {
            m->remove(this);
        }
    }
};

template<typename T>
TypeMap::TypeMapStaticInstance TypeMap::TypeMapDetail<T>::map_(TypeMap::TypeMapDetail<T>::destroy_impl);

Comments:

One of the reasons I think this approach may be better is that I don't see any undefined behaviour being invoked.  Am I correct about this?
Now that standard containers can have stateful allocators, would having each contain destruct_func (and probably construct_func) make sense?

Other issues as always welcome.


texts: Calculating the change of a vending machine

texts:
I would like to know if this function is correct (I know that it works, but I have not got enough knowledge so as to demonstrate that it is correct).

  Indication: a colleccio is defined as a vector< int > always of size 12, so I can represent the number of banknotes and/or coins of value 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 € in positions 0..11.

  Example: if I want to store 5 x 50€ + 2 x 20€ + 0 x 10€ + 1 x 5€ +... et cetera, I would type: colleccio v(12); v[0]=5; v[1]=2; v[2]=0; and so on.

Pre:

No money exchange has been done before the function.
machine is a valid colleccio: it is the content of the machine (how many banknotes and/or coins has inside).
paid is another valid colleccio but, in this case, it is what the user has paid.
possible_change is an empty colleccio.
numeric_change is a valid currency (X.XX€, two decimals, positive value). Its value is the price of the product - what the customer has paid. Its value is valid before computing the function.

Description and post: i_have_change checks if, given machine and paid, exists a possible_change to be returned to the user lately. If it is possible, in possible_change there will be a valid colleccio in which it is stored the most optimum change (that is: the less "currency" items (banknotes/coins), the better). machine should be correctly modified (it doesn't matter if it changes even though I cannot give change).

Code:

bool i_have_change (colleccio& machine, const colleccio& paid,
                    colleccio& possible_change, double numeric_change) {
  vector<double> p(12); //the values of the currency are stored in p.
  p[0] = 50.; p[1]  = 20.;  p[2]  = 10.;
  p[3] =  5.; p[4]  =  2.;  p[5]  =  1.;
  p[6] = .50; p[7]  = .20;  p[8]  = .10;
  p[9] = .05; p[10] = .02; p[11]  = .01;

  //Add `paid` to `machine`
  for (int i = 0; i < paid.size(); ++i)
    machine[i] += paid[i];

  //I start with `numeric_change` (> 0) and I keep on subtracting all $$$
  //as much as I can (they are always <= `numeric_change`)
  for (int i = 0; i < machine.size() and numeric_change > 0; ++i) {
    while (p[i] <= numeric_change and machine[i] >= 1) {
      numeric_change -= p[i];
      ++possible_change[i];
      --machine[i];
    }
  }

  //If I still have `numeric_change`, I have not physical change!
  if (numeric_change != 0) return false;

  //Else, everything is correct and I've got change.
  return true;
}


texts: Auto-complete using Tries in Python with OOP

texts:
I am working on a problem to develop auto-complete functionality to practice different applications of Tries. The auto-complete function will return all the possible words in the wordlist given a prefix. I came up with the following solution which returns the result as expected. I need some help to review my code, in order to enhance the OOP structure and improve the code quality over all.

Please let me know your thoughts, any feedback is welcome.

class Trie():
    def __init__(self):
        self.children = {}
        self.flag = False # Flag to represent that a word ends at this node

    def insert(self, word):
        for char in word:
            if char not in self.children:
               self.children[char]= Trie()

            self = self.children[char]
        self.flag = True

    def all_suffixes(self, prefix):
        results = set()

        if self.flag:
            results.add(prefix)

        if not self.children:
            return results

        return reduce(lambda a, b: a | b,  [node.all_suffixes(prefix + char) for (char, node) in self.children.items()])

    def autocomplete(self, prefix):
        node = self
        for char in prefix:
            if char not in node.children:
                return None
            node = node.children[char]
        return list(node.all_suffixes(prefix))

if __name__=="__main__":
    word_list = ['aardvark','ark', 'altimeter','altitude', 'apotactic', 'bagonet', 'boatlip',
    'carburant', 'chyliferous', 'consonance', 'cyclospondylic',
    'dictyostele', 'echelon', 'estadal', 'flaunty', 'gesneriaceous',
    'hygienic', 'infracentral', 'jipijapa', 'lipoceratous', 'melanthaceae']

    c = Trie()

    for word in word_list:
        c.insert(word)
    print c.autocomplete('a')

Output - ['aardvark', 'ark', 'altimeter', 'altitude', 'apotactic']

I was thinking on the lines of having two classes one as Trie() and the other as Autocomplete(). The __init__(self,word_list) for Autocomplete()  can then have the for loop code snippet to create the Trie from the word list.


texts:
I have some questions about best practices to apply in JavaScript. I would like to ask about my code and how I could improve.

Starting with an example, I have 2 functions with different ways of handling promises

Here I have a route to add a user:

 addUsers(req,res,next) {
    try {
        const {name,email,login} = req.body;
        User.existLogin(req.body.login)
        .then(async result => {
            if(!result){
                const password = await bcrypt.hashSync(req.body.password, 10);
                User.create({
                    name, email, login, password }).then(result => {
                    res.status(201).json({Results: result.dataValues})
                })
            }else{
                return res.status(409).json({message: 'Login already exists'});
            }
        })
    } catch (error) {
        res.status(500).json({error: error})
    }
}

And here I have another function to login:

async login(req,res){
    const  user  = await User.existLogin(req.body.login);
    if (!user) { return res.status(400).json({result: 'Login is wrong '});}
    const isPassword = await User.isPassword(user.dataValues.password, req.body.password);
    if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); }
    const jwt = auth.signjwt(auth.payload(user));
    console.log(jwt);
    res.status(200);
    res.json(jwt);
}

Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).

I have an auth folder, where I export functions, such as my payload, my sign, my middleware to validate my jwt, but I don't know if this is a correct decision.

const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');

module.exports = {
    signjwt (payload) {
        return jwt.sign(payload,
            config.secretToken
                   )
    },
    payload (usuario) {
        return {
            sub: usuario.id,
            name: usuario.nome,
            email: usuario.email,
            login: usuario.username,
            admin: true,
            iat: Math.floor(moment.now()/1000), // Timestamp de hoje
            exp: moment().add(10, 'minutes').unix() // Validade de 2 dias
        }
    },
    async auth(req,res,next){
        const token = req.header('Authorization');
        console.log(token);
        if(!token) return res.status(401).json('Unauthorized');
        try{
            const decoded = jwt.verify(token,config.secretToken);
            const user = await User.findByPk(decoded.sub);
            console.log(user);
            if(!user){
                return res.status(404).json('User not Found');
            }
            res.json(user);
            next();
        }catch(error){
            console.error(error);
            res.status(400).json('Invalid Token');
        }
    }
}


texts: A large number of math type equations and functions in a python module

texts:
I have roughly 40 or 50 functions that are similar to the one provided by the code below.

I kept all the common calculations between multiple functions separate such as service_coverage_area . I then kept all the specific calculations that are not repeated or needed by any other functions in the function that needs those calculations such as calculating f_sc.

My question is: Am I doing this right? as in is this the best practice to code utility functions? should I be separating all the mini calculations into separate functions but then have to deal with 200 functions instead of the current 50?

Note that the self is there cause this code is part of a class. I just copy and pasted 2 functions into this paste

import bisect

def service_coverage_area(self, mode):
  #simplified for codereview
  return 1

def some_calc(self, mode, street_type, grade, elderly_proportion, f_px):
    """ where:
          r = r_0 * f_sc * f_s * f_pop * f_px

          r_0 = ideal transit stop service radius
            400m for bus and 800m for rail / express bus and commuter
            needed variable: mode

          f_sc = street connectivity factor
            {'grid':1, 'hybrid':0.85, 'cul_de_sac':0.45}
            needed variable: street connectivity tye

          f_s = grade fator
            0.00 to 0.05 -> 1.00
            0.06 to 0.08 -> 0.95
            0.09 to 0.11 -> 0.80
            0.12 to 0.15 -> 0.65
            needed variable: grade

          f_pop population factor
            1 for normal population
            0.85 of 20% is elderly population
            needed variable:elderly_proportion

          f_px pedestrian crossing factor
            provided by another calculation
    """
    #calculate r_0
    r_0 = self.service_coverage_area(mode)

    #calculate f_sc
    if street_type == 'grid':
      f_sc = 1
    elif street_type == 'hybrid':
      f_sc = 0.85
    elif street_type == 'cul_de_sac':
      f_sc = 0.45

    #calculate f_s
    grades = [0.05, 0.08, 0.11]
    f_s_values = [1.00, 0.85, 0.80, 0.65]
    f_s_score = bisect.bisect(grades, grade)
    f_s = f_s_values[f_s_score]

    #calculate f_pop
    if elderly_proportion <= 0.2:
      f_pop = 1
    else:
      f_pop = 0.85

    return r_0 * f_sc * f_s * f_pop * f_px


texts: Iterative solution for generating all permutations of a string

texts:
I know the runtime for generating all permutations is supposed to be \$O(n!)\$. I'm not sure if the code I wrote for it runs in \$O(n!)\$ though. I'm having trouble analyzing its runtime.

The for(char c: cArray) part is in \$O(n)\$. What about for (String s: currResults) and for (int i = 0; i < s.length() + 1; i++)?

public static Set<String> getPermutations(String str) {
        char[] cArray = str.toCharArray();
        Set<String> realRes = new HashSet<String>();
        Set<String> results = new HashSet<String>();
        for (char c : cArray) {
            Set<String> currResults = new HashSet<String>(results);
            String charToAdd = String.valueOf(c);
            results.add(charToAdd);
            for (String s : currResults) {
                for (int i = 0; i < s.length() + 1; i++) {
                    String newWord = s.substring(0, i) + charToAdd + s.substring(i);
                    if (newWord.length() == str.length()) {
                        realRes.add(newWord);
                    }
                    else {
                        results.add(newWord);
                    }
                }
            }
        }
        return realRes;
    }


texts: Deeply extract all used symbols from a hash of nested symbols in an array

texts:
I have a nested hash of symbols like this:

{
  a: {
    b: :c,
    d: {
      e: :f
    }
  },
  g: :h
}

I want to build an array that contains all symbols used in the hash, both keys and values, in any order. For the example above:

[:a, :b, :c, :d, :e, :f, :g, :h]

Is there any simple, fast and ruby-friendly way to do this?

I'm doing this with a recursive function that sums hash.keys with hash.values, and finally applies flatten to the result.

def all_keys(hash)
  hash.keys + hash.values.map { |e| e.is_a?(Hash) ? all_keys(e) : e }
end


texts: Moving to other game states with ScreenManager

texts:
I'm creating a game in C#, and I've created a ScreenManager so I can call

ScreenManager.MoveToScreen(typeof(ScreenClassHere))

to move to other game states. However, I feel that my method of creating an instance of the class is... not very optimal. See for yourself.

    public static void MoveToScreen(Type s)
    {
        if (currentscreen != null) currentscreen.Remove();

        currentscreen = (Screen)s.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        currentscreen.Init();
    }

Does anyone know if there's a better way to create an instance of a certain class from a Type?


texts: Wrapper class for system dialog to allow for dependency injection

texts:
The following class is a wrapper for Microsoft.Win32.SaveFileDialog. I've implemented the usage of Microsoft.Win32.SaveFileDialog this way because I'm using the ISaveFileDialog interface as a dependency throughout my code base.

public class SaveFileDialog : ISaveFileDialog
{
    public bool Save(string content, string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null)
    {
        string filter = "All Files|*.*";

        if (suggestedFileExtension != null)
        {
            filter = $"{suggestedFileExtensionName ?? string.Empty}|*{suggestedFileExtension}|" + filter;
        }

        Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
        {
            FileName = suggestedFileName ?? string.Empty,
            DefaultExt = suggestedFileExtension ?? string.Empty,
            Filter = filter
        };

        switch (dlg.ShowDialog())
        {
            case true:
                return WriteFile(dlg.FileName, content);
            default:
                return false;
        }
    }

    private bool WriteFile(string filePath, string content)
    {
        try
        {
            File.WriteAllText(filePath, content);
            return true;
        }
        catch (PathTooLongException)
        {
            return false;
        }
        catch (DirectoryNotFoundException)
        {
            return false;
        }
        catch (IOException)
        {
            return false;
        }
        catch (UnauthorizedAccessException)
        {
            return false;
        }
        catch (System.Security.SecurityException)
        {
            return false;
        }
    }
}

While this works, I'm struggling to refactor this class to allow for unit testing as currently there's no way to mock/stub the Microsoft.Win32.SaveFileDialog - have I missed a trick here? Or is there genuinely no nice way to unit test this and I should be relying on integration tests?

I know that I could refactor the catch blocks to either be

catch (Exception)
{
    return false;
}

Or even to be

catch (Exception ex) when (ex is PathTooLongException
                        || ex is DirectoryNotFoundException
                        ........ )
{
    return false;
}

But I would like to keep them the way that they are because I would like to avoid catching all exceptions and I'm using a Visual Studio plugin to help me manage exceptions and it complains when using the second option.

Thanks for any help!


texts:
I have started learning Java recently and was looking into some easy algorithms. I found the Binary Search Algorithm here

I am trying to get better at writing good code for my solutions. I have used MergeSort for sorting the unsorted array first.Please give me your suggestions.

    import java.util.Scanner;

    public class binarysearch {

        public static void main(String[] args) {

            Scanner keyboard = new Scanner(System.in);
            int size = keyboard.nextInt();
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = keyboard.nextInt();
            }
            // sort the array using mergesort
            mergeSort (array);
            System.out.println("Enter the element to search");
            int searchkey = keyboard.nextInt();
            // call the function to do the binary search
            binarySearch (array, searchkey);

        }

        private static void binarySearch(int[] array, int searchkey) {

            int low = 0; // lowest index
            int high = array.length - 1; // highest index
            int guess = (low + high) / 2;

            while (low <= high) {
                if (array[guess] == searchkey) {
                    System.out.println("The element " + searchkey
                            + " is found at the index " + guess);
                    break;
                } else if (array[guess] < searchkey) {
                    low = guess + 1;
                } else
                    high = guess - 1;
                guess = (low + high) / 2;

            }
            if (low > high) {
                System.out.println("The element " + searchkey + " is not found");
            }

        }

        private static int[] mergeSort(int[] a) {

            if (a.length <= 1) {
                return a;
            }

            // split the array into two halves

            int[] first = new int[a.length / 2];
            int[] second = new int[a.length - first.length];

            System.arraycopy(a, 0, first, 0, first.length);
            System.arraycopy(a, first.length, second, 0, second.length);

            mergeSort (first);
            mergeSort (second);

            merge (first, second, a);

            return a;

        }

        private static void merge(int[] first, int[] second, int[] a) {
            int i = 0;
            int j = 0;
            int k = 0;

            while (i < first.length && j < second.length) {
                if (first[i] <= second[j]) {
                    a[k] = first[i];
                    i++;
                    k++;
                } else {
                    a[k] = second[j];
                    j++;
                    k++;
                }

            }

            while (i < first.length) {
                a[k++] = first[i++];
            }
            while (j < second.length) {
                a[k++] = second[j++];
            }

        }

    }


texts: Extracting parts of filenames from an array

texts:
I am very new to perl. So far I love it, my new favorite interpreted language. I am quickly learning that perl has MANY 'tricks' to it. The following code extracts file names out of one array and into another using a simple regex. Is there a shorter way of doing this?

It feels like there's a way to remove the for loop.

my @configs = glob("m4/config.*.m4");
my @outputs;

foreach(@configs)
{
    $_ =~ m/m4\/(config\..*)\.m4/;
    push @outputs, $1;
}

print join(' ',@configs) . "\n";
# m4/config.a2.m4 m4/config.mk.m4 m4/config.php.m4

print join(' ',@outputs) . "\n";
# config.a2 config.mk config.php

exit;


texts: Python Dataframe column value updates in for loop

texts:
I have a dataset on which I need to do entity resolution. Hence in this dataset some records have links some records have address. I need to build a logic for it to identify each record and put the acronym as a unique identifier.

Example  Dataset

ID   LINK    acronym    address

1   google      NAN        a

2   google      NAN        a

3   NAN         NAN        a

4   google      NAN        b

5   google      NAN        b

6   NAN         NAN        b

Output

 ID   LINK     acronym       address

    1   google      google        a

    2   google      google        a

    3   NAN         google        a

    4   google      google        b

    5   google      google        b

    6   NAN         google        b

Algorithm

I have a list of unique links/urls and I split it using . as a delimeter and assign this to acronym. As an example, www.google.com would convert into google.
Update dataframe acronym column where a unique link exists.
Find all unique addresses corresponding to the unique link and update the acronym with these addresses I found.

Now I think my code needs some optimization.

Code

 for link in list_of_unique_links:
        if( len(link.split('.')) >1):
            acronym = link.split('.')[-2]
        else :
            acronym = link
        print(acronym)
        test_df.loc[test_df['links'] == link ,'acronyms'] =acronym
        #Get all associated address with this link and also add
        for address in test_df[test_df['links'] == link  ].address.values:
            test_df.loc[test_df['address'] == address ,'acronyms'] =acronym


texts: Insert contact information from form fields into MySQL database when button is clicked

texts:
I am just a beginner trying to do my due diligence and research things properly. I am trying to go about the correct way of adding data into a database. I have read articles on the following:

Not showing ConnectionString in plaintext. I currently store it in App.Config and I am still trying to figure out how to encrypt it.
using keyword to deal with disposable items.
catch try finally to deal with exceptions.
parameterized SQL statements to deal with SQL Injection.

I am looking for any advise to make my code better. I have revised it several times taking into account all the articles I have read about the topics above.

private void Btn_InsertData_Click(object sender, EventArgs e)
{
    if (TextboxesAreNullorEmpty() == true)
    {
        MessageBox.Show("Please fill out all fields!");
        return;
    }
    else
    {
        try
        {
            using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.MySQLDBConnection))
            using (MySqlCommand cmd = new MySqlCommand())
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO `sites` (`ContractNumber`, `SiteName`, `SitePhoneNumber`, `SiteAddLine1`, `SiteAddLine2`, `SiteAddCity`, `SiteAddCounty`, `SiteAddPostcode`, `SiteAddCountry`) VALUES (@contract_name, @site_name, @site_phone_number, @site_add_line1, @site_add_line2, @site_add_city, @site_add_county, @site_add_postcode, @site_add_country)";
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@contract_name", this.txtBox_ContractNumber.Text);
                cmd.Parameters.AddWithValue("@site_name", this.txtBox_SiteName.Text);
                cmd.Parameters.AddWithValue("@site_phone_number", this.txtBox_SitePhoneNumber.Text);
                cmd.Parameters.AddWithValue("@site_add_line1", this.txtBox_SiteAddLine1.Text);
                cmd.Parameters.AddWithValue("@site_add_line2", this.txtBox_SiteAddLine2.Text);
                cmd.Parameters.AddWithValue("@site_add_city", this.txtBox_SiteAddCity.Text);
                cmd.Parameters.AddWithValue("@site_add_county", this.txtBox_SiteAddCounty.Text);
                cmd.Parameters.AddWithValue("@site_add_postcode", this.txtBox_SiteAddPostcode.Text);
                cmd.Parameters.AddWithValue("@site_add_country", this.txtBox_SiteAddCountry.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Site Details Added");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(string.Format("An error occurred {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
           ClearAllTextBoxes();
        }
    }

}


texts:
This is a scraper written in CoffeeScript for NodeJS. It is run in an interval (set to 5 seconds here to dramtically show the leak). Somewhere this code leaks memory. I already tried nulling a few things for manually deleting references. Where is the reference kept that produces the leak?

request = require 'request'
jsdom   = require 'jsdom'
util    = require 'util'

scrapeURL   = 'http://kwlpls.adiwidjaja.com/index.php'
jqueryUrl   = 'http://code.jquery.com/jquery-1.6.1.min.js'
scrapeDivId = "cc-m-externalsource-container-m8a3ae44c30fa9708"

scrapeDelay = 5 * 1000 # 5 seconds
data = []

fetch = (callback) ->
    request { uri: scrapeURL }, (error, response, body) ->
        if error and response and response.statusCode isnt 200
            util.log 'Error when contacting #{scrapeURL}'

        # Fake Browser
        jsdom.env
            html: body,
            scripts: [jqueryUrl],
            (err, window) ->
                processPage(window, (result) ->
                    callback(err, result)
                )

processPage = (window, callback) ->
    # cleanup
    result           = {}
    result.cities    = []
    result.parkings  = []

    $    = window.jQuery
    rows = $('table').children()
    num  = $(rows).size()

    rows.each (i, row) ->
        if i > 0 and i isnt num - 1 # cut off header and footer
            processRow($, row, (item, city) ->
                result.parkings.push(item) if item?
                result.cities.push(city) if city?
                item = null
                city = null
                callback(result) if i is num - 2
            )

processRow = ($, row, callback) ->
    elements  = $(row).children('td')
    item      = {}
    city      = null
    nameStr   = elements?.eq(0).html()
    nameStr  ?= ""
    item.kind = nameStr.substring 0, 2
    item.name = nameStr.substring 3

    if elements.size() > 2
        free           = elements?.eq(2).html()
        spaces         = elements?.eq(1).html()
        item.free      = free
        item.spaces    = spaces
        item.status    = "open"
    else if elements.size() > 0
        item.status    = "closed"
    else
        header      = $(row).children().first().html()
        currentCity = header.split(' ')[1]
        city        = {}
        city.name   = currentCity

    item.city = currentCity
    if item.name is "" or not item.name? then item = null

    # cleanup
    elements = null
    $ = null

    callback(item, city)

cacheJson = () ->
    fetch(
        (err, result) ->
            util.log err if err?
            data = result ? []
            util.log 'Fetched ' + data?.parkings?.length + ' entries'
    )

scrapeIntervalId = setInterval cacheJson, scrapeDelay