texts:
I am using preg_replace_callback(), and I am concerned that I might have some sort of security risk.  I am hoping to get a review of the below substitute() function.  The purpose of the function is to parse a user provided template with user provided data.  A quick description on how it is used is shown below.

The user posts data to the server, which is saved in a database (escaped for SQL injection of course). Note that the application will limit which array indexes are allowed (i.e. firstname, lastname, and phone only in this example).

$userProvidedString='Hello {?firstname?} {?lastname?}, Our database shows that your phone number is {?phone?}.';

$userProvidedArray=array(
    0 => array('firstname'=>'John','lastname'=>'Doe','phone'=>'(555) 222-1212'),
    1 => array('firstname'=>'Jane','lastname'=>'Doe','phone'=>'(555) 333-1212'),
    2 => array('firstname'=>'Mike','lastname'=>'Moe','phone'=>'(444) 222-1212'),
);

Later the data is pulled from the database, and parsed as follows:

foreach($userProvidedArray AS $contact)
{
    $customMessage=substitute($userProvidedString,$contact);
}

My question relates to the substitute() function.  Specifically, does my use of preg_replace_callback() pose any security issues?  Previously, I was using

$template_new= preg_replace('/\{\?(\w+)\?\}/e', '$contact["$1"]', $userProvidedString);

which uses the /e flag which I assume can be dangerous.

Does that danger still remain? Any other recommendations for it?  I am currently using PHP 5.3.18, but will hopefully upgrade to 5.4 soon.

function substitute($template, $values, $deliminator='{??}') {
    //Replaces occurrences of {?name?} with $values['name] if it exists in $values.  Deliminators can be changed
    $deliminator="\\".implode("\\",str_split($deliminator));
    $half = (int) ( (strlen($deliminator) / 2) );
    $pattern = '/'.substr($deliminator, 0, $half).'(\w+)'.substr($deliminator, $half).'/';
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($values) {
            if (isset($values[$matches[1]])) {
                return $values[$matches[1]];
            }
            return $matches[0];
        },
        $template);
}


texts: Is this way of handling events in a Xamarin project memory safe?

texts:
I inherited a Xamarin project and I'm trying to find my way. The first task I completed involved creating a new reusable view and adding it to an existing screen. This was iOS specific, so I went and created a new .xib file to add in the relevant storyboard. I had some trouble figuring out how to attach the outlets correctly and I didn't see my view so I added it programmatically, but in the end I got it working. However I ended up using the following code that concerns me a bit:
    // TableviewSearchbarHeader.designer.cs
    [Register ("TableviewSearchbarHeader")]
    partial class TableviewSearchbarHeader
    {
        [Outlet]
        UIKit.UIButton ClearSelectionButton { get; set; }
    }

    // TableviewSearchbarHeader.cs
    public void SetOnClearSelectionButtonPressed(EventHandler OnClearSelectionButtonPressed)
    {
        ClearSelectionButton.TouchUpInside += OnClearSelectionButtonPressed;
    }

    // MyViewController.cs
    public override void ViewDidLoad()
    {
        TableviewSearchbarHeader.SetOnClearSelectionButtonPressed(OnClearSelectionButtonPressed);
    }
    private void OnClearSelectionButtonPressed(object sender, EventArgs e)
    {
        Presenter.ResetFilter(this);
    }

The outlet is not accessible from the VC. So I had to create an entry point for the VC to assign its delegate implementation. But how can I be sure this will not cause a memory leak? This just seems like a code smell, but I couldn't figure out a better way and the docs aren't helpful.
What can I improve?


texts: Populating a class whose data is stored in an external application

texts:
Im currently working on a system that will communicate with other systems via webservice (or some sort of communication). I have a system that stores all user data already and don't want to duplicate data in this new system so I have come up with a way of accessing the data when needed.

In my current system I am planning to just store the user ID from the user system and fetch the data when required. My question is, is the following code considered acceptable/understood or would you suggest an alternative way of achieving this?

public class Person
{
    private string id;
    [Transient]
    private string name;
    [Transient]
    private bool isPopulated;

    public Person(string id){
       this.id = id;
    }

    public string Id{get;set;}

    public string Name{
        get{
            init();
            return this.name;
        }
        set{
            this.name = value;
        }
    }

    private void init(){
        if(!isPopulated){
            TempPerson tempPerson = UserService.getPerson(this.id);
            this.name = tempPerson.Name;
            this.isPopulated = true;
        }
    }
}

Is there a better way to do this and are there any problem with this way?


texts:
I have a thread as part of a class that access the class's data members. The class has a move constructor that moves some of the old class's data members into the new object being constructed. Before moving the class members of the old object, I need to shutdown its thread. I do this by calling thread_shutdown in the move constructor. I would like to know if this is the most elegant way to achieve thread-safety.

#include <chrono>
#include <iostream>
#include <memory>
#include <thread>

class B {
public:
  int x;
};

class A {
  std::unique_ptr<B> b_ptr;
  volatile bool thread_shutdown = false;
  std::thread t;
  void run() {
    while (!thread_shutdown) {
      int x = b_ptr->x;
    }
  }

public:
  A() : b_ptr(std::make_unique<B>()), t(std::thread(&A::run, this)) {}
  // A(A &&a) : b_ptr(std::move(a.b_ptr)), t(std::thread(&A::run, this)) {}
  A(A && a) {
    a.shutdown_thread();
    b_ptr = std::move(a.b_ptr);
    t = std::thread(&A::run, this);
  }
  ~A() { shutdown_thread(); }
  void shutdown_thread() {
    thread_shutdown = true;
    if (t.joinable()) {
      t.join();
    }
  }
};

int main() {
  std::unique_ptr<A> a_ptr = std::make_unique<A>();
  a_ptr = std::make_unique<A>(std::move(*a_ptr));
}

If I replace the move constructor definition by the commented line in the code, I get a segmentation fault in the second line of main because the old thread is trying to access b_ptr->x, but b_ptr is NULL as it has been moved to the new object's b_ptr. Thus, I cannot rely on the destructor of class A to shutdown the thread.

So, the question is: What is the best way to handle thread shutdown before some of the objects accessed by it are moved? I don't like having to call shutdown_thread in the move constructor.


texts: Control Signin Class - Remove Dependencies

texts:
<?php

/**
 *      Module  :       Control
 *      Name    :       ControlSigin
 *      Input   :       Text Array
 *      Output  :       Pass or Fail(w/responseText)
 *      Notes   :
 *      Call    :
                        $instanceControlSignIn = new ControlSignIn();
                        $instanceControlSiginIn->invoke();

 */

class ControlSignIn extends Post
{
    private $databaseObject;
    private $textObject;
    private $messageObject;

    public function __construct()
    {
        parent::__construct();

        $this->databaseObject = new Database();
        $this->textObject = new Text($this->_postProtected);
        $this->messageObject = new Message();
    }

    public function invoke()
    {
        if(Constant::VALIDATE_ON==true)
        {
            $continue = $this->checkInput();
        }
        else
        {
            $continue = true;
        }

        if($continue==true)
        {
            if($this->validatePass())
            {
                $this->setSessionVariables();
                Control::send(Mark::pass);
            }
            else
            {
                $this->messageObject->display('validate');
                return false;
            }
        }
    }

    private function checkInput()
    {
        if(!$this->textObject->checkEmpty())
        {
            $this->messageObject->display('empty');
            return true;
        }
        if(!$this->textObject->checkPattern('email'))
        {
            $this->messageObject->display('email');
            return false;
        }
        if(!$this->textObject->checkPattern('pass'))
        {
            $this->messageObject->display('pass');
            return false;
        }
    return true;
    }

    private function validatePass()
    {
        $result=$this->databaseObject->_pdoQuery('single', 'signin_pass',array($this->_postProtected['email']));
        $pass=crypt($this->_postProtected['pass'], $result['pass']);
        $result=$this->databaseObject->_pdoQuery('single', 'signin_validate',array($this->_postProtected['email'], $pass));
        return (count($result)==2) ? true : false;
    }

    private function setSessionVariables()
    {
        $result=$this->databaseObject->_pdoQuery('single', 'pull_session',array($this->_postProtected['email']));
        Session::activate($result['picture'],$result['id'],$result['name'],'bookmarks');
    }
}


texts: Optimizing nested "Select Distinct" query

texts:
I am using the following query which is causing issues. Note following points:

I am using 4 tables in this query:

message_share
messages
myusertable
friends

What I am trying to do in this query is to display messages, and share messages of users who are friend with each other.

This is similar to Facebook wall where they display friends' wall data.

The problem is only myusertable is causing the issue. It increase the load too much,  even to where the query can timeout.

When I remove myusertable from this query then it works fine, the use of myusertable is to fetch user full name. Everything else we are doing with userid and does not need  myusertable. For the sole purpose of getting user full name are we using myusertable.

The query is

(SELECT DISTINCT M.msg_id, M.uid_fk, M.message, S.created, M.like_count,M.comment_count,M.share_count, U.username,M.uploads, S.uid_fk AS share_uid,S.ouid_fk AS share_ouid
FROM friends F
LEFT JOIN message_share S ON S.ouid_fk <> F.friend_two
LEFT JOIN messages M ON M.msg_id = S.msg_id_fk AND M.uid_fk = S.ouid_fk
LEFT JOIN myusertable U ON U.uid = M.uid_fk AND U.status1='1'
WHERE F.friend_one='199095' AND F.role='fri'
GROUP BY msg_id
ORDER BY created DESC LIMIT 10)
UNION
(SELECT DISTINCT M.msg_id, M.uid_fk, M.message, M.created, M.like_count,M.comment_count,M.share_count, U.username,M.uploads, '0' AS share_uid, '0' AS share_ouid
FROM friends F
LEFT JOIN messages M ON M.uid_fk = F.friend_two
LEFT JOIN myusertable U ON U.uid = M.uid_fk AND U.status1='1'
WHERE F.friend_one='199095'
GROUP BY msg_id
ORDER BY created DESC LIMIT 10)

Is there anything that I can do with myusertable to make this query faster?


texts:
I have implemented a basic, but seemingly working, persistent (as in immutable), heterogenous list type in Rust.

Here's the code:

#[derive(Debug)]
pub enum ConsCell<'a> {
    Char(char),
    Number(u64),
    String(&'a str),
}

pub struct PersistentList<'a, T: 'a> {
    first: Option<&'a T>,
    rest: Option<&'a PersistentList<'a, T>>,
    count: u64,
}

impl<'a, T> PersistentList<'a, T> {
    pub fn new() -> PersistentList<'a, T> {
        PersistentList {
            first: None,
            rest: None,
            count: 0,
        }
    }

    pub fn first(&self) -> &T {
        self.first.unwrap()
    }

    pub fn next(&self) -> Option<&PersistentList<T>> {
        if self.count == 1 {
            return None;
        }

        self.rest
    }

    pub fn cons(&'a self, x: &'a T) -> PersistentList<'a, T> {
        PersistentList {
            first: Some(x),
            rest: Some(&self),
            count: self.count + 1
        }
    }

    pub fn count(&self) -> u64 {
        self.count
    }
}

This can be used like so:

fn main() {
    let list = PersistentList::new();
    let cell = &ConsCell::Number(42);
    let list = list.cons(cell);
    let cell = &ConsCell::String(&"foo");
    let list = list.cons(cell);
    match list.first() {
        ConsCell::Char(c) => println!("{}", c),
        ConsCell::Number(n) => println!("{}", n),
        ConsCell::String(s) => println!("{}", s),
    }
}

The ergonomics of this are not fantastic, however it does seem to work. Is there a more idiomatic way of doing something similar with Rust?


texts: Frequency form to case form - unexpected values in table

texts:
I'm taking count data on voting preferences by race and entering it into a table in frequency form, then expanding out to case form and using CrossTable to look at adjusted residuals. Here's my script:

### create table in frequency form
vnames <- c("Race", "Party", "freq")
a <- c("White","Dem", 871)
b <- c("White","Ind", 444)
c <- c("White","Rep", 873)
d <- c("Black","Dem", 302)
e <- c("Black","Ind", 80)
f <- c("Black","Rep", 43)

rtable <- rbind(a,b,c,d,e,f)
colnames(rtable) <- vnames

###check table - looks fine
head(rtable)

###expand to case form
rtablecase <- expand.dft(rtable, freq = "freq")

###check table - *here's where it gets weird*.
head(rtablecase)

The first two rows hold the value of "1" in the race column rather than "White". Everything else is as expected. Why? I eventually just manually replaced the values (see below) so I could run CrossTable and it looks fine, but can someone please tell me where these two 1s are coming from?*

### replace 1s in Race column
rtablecase[1,1] <- "White"
rtablecase[2,1] <- "White"

###convert to data frame
rtcasedf <- data.frame(rtablecase)
head(rtcasedf)

###Crosstabulation with adjusted residuals
CrossTable(rtcasedf$Race, rtcasedf$Party, format="SPSS", asresid=TRUE, chisq=TRUE)


texts: Entering and authorizing Twitter credentials

texts:
I'm fairly new to Ruby, and I've been refactoring this code (it's a silly app, but it's helping me learn) as I learn more and more best practices and features new to Ruby 1.9 (e.g., hashrocket alternative). I figure having more experienced Rubyists give feedback on the short program will help me learn faster. So, with that in mind, is there anything in this code that isn't a best practice, or anything not so clean about it?

#!/usr/bin/env ruby

require 'twitter'

# Enter your creds
creds = {username:       'YourUsername',
         consum_key:     'SomeLongKeyBlahBlah',
         consum_secret:  'AnotherLongKeyButASecretOneThisTime',
         oauth_token:    'OAuthTokenKeyBlahBlah',
         oauth_secret:   'OAuthSecretTokenOfSecrets'}

# Twitter auth
def twitterAuth(creds)
  Twitter.configure do |config|
      config.consumer_key       = creds[:consum_key]
      config.consumer_secret    = creds[:consum_secret]
      config.oauth_token        = creds[:oauth_token]
      config.oauth_token_secret = creds[:oauth_secret]
  end
end

def sendTweet(creds)
  # Make string
  msg = '@' + creds[:username] + ' ' + ARGV.join(' ')
  # Send!
  Twitter.update(msg)
  # Return tweet
  puts 'Your tweet: ' + msg
end

if __FILE__ == $0
  twitterAuth(creds)
  sendTweet(creds)
end


texts: Optimizing PowerShell string hasher method

texts:
I am building a PowerShell class based tool that works with XML files of as much as a few hundred Kb size, and as many as a hundred of these files. I have extensive validation code that is time consuming, so I want to validate the XML and if it is valid hash it and write that hash as an attribute to the root element. My code can then hash on load, compare with that value and skip validation when possible. This is a pretty major speed improvement.
To that end, I have this static method of my xml class.
static [String] GetHash ([Xml.XmlDocument]$xmlDocument) {
    $stringBuilder = [Text.StringBuilder]::new()

    $hashBuilder = [Security.Cryptography.MD5CryptoServiceProvider]::new() #[Security.Cryptography.SHA384CryptoServiceProvider]
    $encoding = [Text.Encoding]::UTF8
    $xmlToHash = [Xml.XmlDocument]::new()
    $xmlToHash.AppendChild($xmlToHash.ImportNode($xmlDocument.DocumentElement, $true))
    $string = [pxXML]::ToString($xmlToHash)
    $hashIntermediate = $hashBuilder.ComputeHash($encoding.GetBytes($string))
    foreach ($intermediate in $hashIntermediate) {
        $stringBuilder.Append($intermediate.ToString('x2'))
    }

    return $stringBuilder.ToString()
}

As well as this static .ToString() method that is used by the hasher and also used for writing results to the console in testing.
static [String] ToString ([Xml]$Xml) {
    $toString = [System.Collections.Generic.List[String]]::new()

    $stringWriter = [IO.StringWriter]::new()
    $xmlWriter = [Xml.XmlTextWriter]::new($stringWriter)
    $xmlWriter.Formatting = "indented"
    $xmlWriter.Indentation = 4
    $Xml.WriteTo($xmlWriter)
    $xmlWriter.Flush()
    $stringWriter.Flush()
    $toString.Add($stringWriter.ToString())
    $toString.Add("`r" * 2)

    return [string]::Join("`n", $toString)
}

As you might notice from the commented part of the $hashBuilder line, I have tested this with different algorithms, and there is little difference in performance. Which is a bit of a surprise. So I wonder if there is something else her that I am missing, that is the the/an actual bottleneck? Or is this code actually reasonable close to optimal performance already? Given that I am totally new to classes and digging this deep into .NET, I suspect there is a bit to learn here beyond just optimizing this code.


texts: Configurable synchronization approach in Java

texts:
I am interested in the community opinion about the following approach for the synchronization.
Generally it is based on the idea to have a configurable way to apply locking on some logic parts.

Any comments and review is appreciated :) .

lock.properties keeps configuration:

foo=true
bar=false

SynFactory.java produces locks:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SyncFactory {
  private static HashMap<String, Object> locks = null;

  public static synchronized Object getLock(String key) {
    init();
    return locks.containsKey(key) ? locks.get(key) : new Object();
  }

  private static void init() {
    if (locks == null) {
      try {
        locks = new HashMap<String, Object>();

        Properties properties = new Properties();
        properties.load(SyncFactory.class.getClassLoader().getResourceAsStream("lock.properties"));

        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
          // key=true  => locking with ine object
          // key=false => lock object should always be new
          if (Boolean.parseBoolean(String.valueOf(entry.getValue()))) {
            locks.put((String) entry.getKey(), new Object());
          }
        }

      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

}

Service.java actual usage:

public class Service {

  public void foo() {
    synchronized (SyncFactory.getLock("foo")) {
      // do some logic
    }
  }

  public void bar() {
    synchronized (SyncFactory.getLock("bar")) {
      // do some logic
    }
  }
}


texts: Prompting for two integers and dividing, using exceptions to handle divide-by-zero errors

texts:
I'm trying to learn exception handling in C++.

I wanted to read two integers and divide them and print them.

The code should throw an exception when the second integer is zero, ask the user to re-enter the second integer, and then complete the divide operation.

I coded something like this:

#include <iostream>
#include <stdexcept>

using std::cin;
using std::cout;
using std::endl;

int main() {
    int i1, i2;
    cout << "Give two integers" << endl;
    cin >> i1;
    try {
        first:
        cin >> i2;
        if (i2 == 0)
            throw 0;
        else
            cout << i1 / i2 << endl;
    }
    catch (...) {
        cout << "Second integer cannot be zero , please enter a valid integer" << endl;
        goto first;
    }
    system("pause");
    return 0;
}

However, I was advised not to use goto at all costs.

Can anyone give me some alternative way?


texts: Excel VBA animation runs slowly after editing worksheet

texts:
My VBA macro displays an animation based on a row-by-row time step simulation in the worksheet. The user enters the desired inputs and the worksheet calculates the evolution of the simulation in a 1000 row table. The user then runs the macro to display the results in an animation. The macro loops through the rows in the simulation. For each row, the macro extracts four values and applies them as positions to four shapes in the worksheet.

The macro runs fast when I open the workbook and run the macro without doing else first. If I do an edit to the worksheet that causes it to recalculate the simulation, then the macro runs about 1/3 as fast.

The Task Manager shows some interesting things about the memory usage. When the macro is run without an edit, the usage jumps 66,000 K every run. When the macro is run after an edit, the usage jumps only 2,000 K every run. I've checked the values of ScreenUpdating, EnableEvents, Calculation and DisplayPageBreaks, and they don't change if the worksheet is edited.

Is there something I can do to prevent this other than saving and reopening the workbook after I make an edit?

Sub playfast()
Dim arrRangeValues() As Variant
Dim j As Long
Dim vpos As Double
Dim hpos As Double
Dim calcflag As Boolean
Dim chartflag As Boolean
Dim eventflag As Boolean

If iVal = 0 Then iVal = 1
If iVal = 1000 Then iVal = 1
If iVal = 1001 Then iVal = 1
isCancelled = False
calcflag = ActiveSheet.Cells(8, 12).Value
chartflag = ActiveSheet.Cells(9, 12).Value
eventflag = ActiveSheet.Cells(10, 12).Value

ActiveSheet.Cells(7, 15).Value = "PLAYING"
vpos = ActiveSheet.Cells(6, 12).Value
hpos = ActiveSheet.Cells(7, 12).Value

arrRangeValues = Range("a41:q1041").Value

For j = iVal To 1001 Step ActiveSheet.Cells(24, 12).Value
    iVal = j
    show hpos, vpos, vpos - arrRangeValues(j, 4) * 2, vpos - arrRangeValues(j, 17) * 2, vpos - arrRangeValues(j, 5) * 2
    ActiveSheet.Cells(17, 10).Value = arrRangeValues(j, 1)  'Write time into worksheet
    If eventflag Then DoEvents    'Yield to operating system.
    If calcflag Then ActiveSheet.Calculate   'May be necessary for animation to move after worksheet is changed

    If chartflag Then
        ActiveSheet.ChartObjects("uprchart").Activate
        ActiveSheet.ChartObjects("uprchart").Chart.Refresh
        ActiveSheet.ChartObjects("lwrchart").Activate
        ActiveSheet.ChartObjects("lwrchart").Chart.Refresh
    End If

    If isCancelled Then GoTo EarlyExit

Next j
EarlyExit:
isCancelled = False
ActiveSheet.Cells(7, 15).Value = "STOPPED"

End Sub`
Sub show(leftedge As Double, groundtop As Double, bodytop As Double, wheelstop As Double, passengerstop As Double)

ActiveSheet.Shapes("ground").Left = leftedge
ActiveSheet.Shapes("ground").Top = groundtop

ActiveSheet.Shapes("body").Left = leftedge
ActiveSheet.Shapes("body").Top = bodytop

ActiveSheet.Shapes("wheels").Left = leftedge
ActiveSheet.Shapes("wheels").Top = wheelstop

ActiveSheet.Shapes("passengers").Left = leftedge
ActiveSheet.Shapes("passengers").Top = passengerstop

End Sub


texts: Sufficient implementation of subset sum for 45 min interview

texts:
I am preparing for interviews, and have implemented a solution to this problem from Geeks for Geeks:

  Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.

I don't fully have my head wrapped around the dynamic programming approach.  If I provided the implementation below in an interview, and explained that there was a dynamic solution that could speed the solution up for a small N and S would my technique be acceptable? What would your thoughts be as the interviewer?

FWIW I now that there would be duplicate processing at the leafs of my recursive descent. If asked I would say the complexity of my algorithm would be: \$\Theta(2^N + 1 + (N + 2(N-1) + ...))=\Theta(2^N)\$

Given a set of size 2: (1, 2) The calls would be (1, 2) -> ((1), (2))
Given a set of size 3: (1, 2, 3) The calls would be

                                 (1, 2, 3)
                         (1)(2, 3)       (1, 2)(3)
                            (2)(3)       (1)(2)

Looking at this pattern I would state there are \$2^N + 1\$ calls.

#include <iostream>
#include <iterator>
#include <vector>

void subset_sum(
    std::vector<int>::iterator begin, std::vector<int>::iterator end,
    const std::size_t sum, bool &found)
{
    std::size_t local_sum = 0;
    for (auto it = begin; it != end && !found; ++it) {
        local_sum += (*it);
    }

    if (sum == local_sum) {
        found = true;
    } else if (local_sum < sum) {
        found = false;
        return;
    }

    for (auto it = begin + 1; it < end && !found; ++it) {
        if (!found) {
          subset_sum(begin, it, sum, found);
        }
        if (!found) {
          subset_sum(it, end, sum, found);
        }
    }
}

int main()
{
    std::vector<int> set = {2, 3, 4};
    bool found = false;
    subset_sum(set.begin(), set.end(), 100, found);
    return (!found);
}


texts: Advent of Code 2017, Day 1: Sum of digits matching the next digit (circular list)

texts:
I haven't used C++ for quite a while and wanted to practice a bit, so I decided to start simple and work through the Advent of Code 2017.

This is my solution to Part 1 of the Day 1 exercise "Inverse Captcha":

  The captcha requires you to review a sequence of digits (your puzzle
  input) and find the sum of all digits that match the next digit in the
  list. The list is circular, so the digit after the last digit is the
  first digit in the list.

  For example:

  1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth
  digit.
  1111 produces 4 because each digit (all 1) matches the next.
  1234 produces 0 because no digit matches the next.
  91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

My program works as follows:

Read one line from stdin
Convert the line character-wise to a vector of decimal digits
Calculate the sum of matching digits
Write the result to stdout

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

// Convert the first line of the input stream to a vector of digits.
std::vector<int> read_digits(std::istream& input) {
    std::string line;
    std::getline(input, line);

    std::vector<int> digits(line.size());
    std::transform(
        std::cbegin(line), std::cend(line), std::begin(digits),
        [](char c) { return c - '0'; }
    );
    return digits;
}

// Return the sum of all digits in the list that match the next digit
// (the first digit is the "next" digit of the last digit).
int reverse_captcha(const std::vector<int>& digits) {
    int sum = 0;
    for (auto p = std::begin(digits); p != std::end(digits); p++) {
        auto next_p =
            (std::next(p) == std::end(digits)) ?
            std::begin(digits) : std::next(p);
        if (*p == *next_p) sum += *p;
    }
    return sum;
}

int main() {
    std::cout << reverse_captcha(read_digits(std::cin)) << '\n';
}

I'm compiling it with clang++-4.0 -std=c++14. I'm not sure if I actually use features of the newest standard, but I don't want to restrict myself to older versions.

Here are a few things I'm particularly curious about:

How can I separate iterating over the pairs of digits from calculating their sum if the pairs are equal? If I were using Python I would write one or two small generator functions, but I don't know yet if there is an equally simple way to do this in C++, or if this would become overkill.
Is there an elegant way to avoid the extra step of constructing a string line before creating the vector of digits?
Using - '0' for converting char → int feels like a hack to me, is there really no purpose-built function for this? (I'm used to int('5') → 5 from Python)


texts: Palindromes that are sum of consecutive squares

texts:
I have been working on a Project Euler: 125, which took me ages to solve. The problem and source are cited below

  The palindromic number 595 is interesting because it can be written as
  the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 +
  12^2.

  There are exactly eleven palindromes below one-thousand that can be
  written as consecutive square sums, and the sum of these palindromes
  is 4164. Note that 1 = 0^2 + 1^2 has not been included as this problem
  is concerned with the squares of positive integers.

  Find the sum of all the numbers less than 10^8 that are both
  palindromic and can be written as the sum of consecutive squares.

I firstly tried to figure out if there were some pattern in the square sums, however i found none. My solution ended sadly up being brute force one.

1) Generate all possible palindromes
2) Generate all possible values
of square numbers

1) Is fairly fast however 2) takes (understandably) ages. The code works and gives the correct answer, but it takes ages. I think the problem is memory.

Is there any faster way of checking whether a palindrome can be written as a sum of consecutive squares?

Any other suggestions for my code are also welcome. Python 2.7

from math import floor
from itertools import count

def palindromic_square_summable(limit):
    """
        Finds all numbers p, such that
            p = n^2 + (n+1)^2 + ... + m^2
        and p is a palindrome. Eg 595 or 55.
    """
    dic = get_quadratic_sums(limit)
    pal = all_palindromes(2, limit)
    total = 0
    for key in pal:
        try:
            dic[key]
            total += key
        except:
            pass
    return total

def get_palindrome():
    """
        Generator for palindromes.
        Generates palindromes, starting with 0.
        A palindrome is a number which reads the same in both directions.
    """
    yield 0
    for digits in count(1):
        first = 10 ** ((digits - 1) // 2)
        for s in map(str, range(first, 10 * first)):
            yield int(s + s[-(digits % 2)-1::-1])

def all_palindromes(minP, maxP):
    """Get a sorted list of all palindromes in intervall [minP, maxP]."""
    palindrom_generator = get_palindrome()
    palindrome_dict = dict()
    for palindrome in palindrom_generator:
        if palindrome > maxP:
            break
        if palindrome < minP:
            continue
        palindrome_dict[palindrome] = 1
    return palindrome_dict

def get_quadratic_sums(limit):
    """Get a list of all possible square sums"""
    max_square = int(floor( limit**0.5))
    partial_sums = [0]*(max_square+1)
    dic = dict()

    for i in range(1, max_square+1):
        partial_sums[i] = partial_sums[i - 1] + i**2
        for partial in partial_sums[0:i-1]:
            val = partial_sums[i] - partial
            dic[val] = 1
    return dic

if __name__ == '__main__':
    limit = 10**3
    print palindromic_square_summable(limit)


texts:
This is my solution for the Credit problem on CS50's (Introduction to CS course) Pset1. It involves using Luhn's Algorithm to test the validity of the Credit Card Number entered and based on a few conditions attempts to identify the Credit Card Company.

check_length attempts to find the length of the number entered. check_company attempts to ID the company. check_luhn validates the number based on Luhn's Algorithm.

Lunh's Algorithm:

The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This number must pass the following test:

From the rightmost digit and moving left, double the value of every second digit.  If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the result (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same final result can be found by subtracting 9 from that result (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
Take the sum of all the digits.
If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; otherwise it is not valid.
I am not very comfortable with the so many if-else conditions. I'd like to know if they can be eliminated. Any other changes are also welcome.

#include <stdio.h>
#include <cs50.h>
#include <stdbool.h>

int check_length(long);
void check_company(int,long);
bool check_luhn(long,int);
int length;

int main(void)
{
    long c = get_long("Enter Credit Card Number: ");
    check_length(c);
    check_luhn(c,length);
    if(check_luhn(c,length)==true)
    {
            check_company(length,c);
    }
    else printf("INVALID\n");

}

int check_length(long w)
{
    for(int i=12;i<16;i++)
    {
            long power = 1;
            for (int k=1;k<i+1;k++)
            {
                    power = power * 10;
            }
            int scale = w/power;
            if (scale<10 && scale>0)
            {
                    length = i+1;
            }
   }
   return length;
 }

 void check_company(int x,long z)
 {
    if(x == 15)
    {
            int y = z/10000000000000;           //z/10^13
            if(y==34||y==37)
            {
                    printf("AMEX\n");
            }
            else
            {
            printf("INVALID\n");
            }
    }
    else if(x==13)
    {
            int y = z/100000000000;                 //z/10^11
            if(y==4)
            {
                   printf("VISA\n");
            }
     }
     else if(x==16)
     {
             int q = z/1000000000000000;
             int y = z/100000000000000;
             if(y==51||y==52||y==53||y==54||y==55)
             {
                     printf("MASTERCARD\n");
             }
             else
             if(q==4)
             {
                     printf("VISA\n");
             }
             else printf("INVALID\n");
     }
     else printf("INVALID\n");
  }

  bool check_luhn(long a,int b)
  {
     int f = 0;
     int j=0;
     for(int d=1;d<b+1;d++)
     {
             int e = a%10;
             a = a/10;
             if(d%2==1)
             {
                    f = f+e;
             }
             else
             {
                     int m = 2*e;
                     int g = m%10;
                     int h = m/10;
                     j = j+g+h;
              }

      }
      int l = j + f;
      if(l%10==0)
      {
             return true;
      }
      else return false;
    }


texts: Expand hostnames from a string of hostnames and/or regex

texts:
This code will be passed a string which will contain one or more hostnames.

A hostname can be

dotted-decimal
plain name (like my_host)
FQDN or even partially qualified
A string containing regex (my_hos[tes])

target_list is an array of known hosts to match any regex against.

Any suggestions on cleaning this up?

sub expand_names {
    my $host = shift;

    my @raw_hosts = split(' ', $host);
    my @hosts;

    my %host_hash;
    foreach my $raw_name (@raw_hosts) {
        $host_hash{$raw_name} = {};
        #if the name might contain regex, let's see what it matched
        if ($raw_name !~ m/^[a-zA-Z0-9-]+$/) {
            foreach my $target (@target_list) {
                if ($target =~ m/^$raw_name$/) {
                    $host_hash{$raw_name}->{$target} = 1;
                }
            }
            #if we didn't match anything, then just use the name
            if (not keys %{$host_hash{$raw_name}} ) {
                $host_hash{$raw_name}->{$raw_name} = 1;
            }
        }
        else {
            # Regular host name or dotted-decimal
            $host_hash{$raw_name}->{$raw_name} = 1;
        }
    }
    # Gather all the hosts we found
    foreach $raw_name  (keys %host_hash) {
        @hosts = (@hosts, (keys %{$host_hash{$raw_name}}));
    }
    return sort @hosts;
}


texts: Python random number generator between 1 and 9

texts:
I created this code and it works fine, but I think it's ugly. Could you show me a better way to create a list of three different random numbers from 1 to 9?

class Baseball_Engine(object):
    def __init__(self):
        self.count = 0
        self.random_number_list = [0, 0, 0]
        while self.count < 3:
            random_number = random.randint(1, 9)
            self.random_number_list[self.count] = random_number
                if self.random_number_list[self.count - 1] != random_number and self.random_number_list[self.count - 2] != random_number:
                self.count += 1
        print self.random_number_list


texts:
We have a round table of n knights, where n is some positive
  integer. These have failed to satisfy the expectations of the mad king
  and are sentenced to death. However as an act of mercy he goes around
  the table killing every other knight (starting with the second)
  until only one knight remains.

  The question is: which seat do you need to pick to survive?

I wrote the primitive code below to tackle this problem:

while True:
    temp_num = input("Enter the number of knights: ")
    try:
        temp_num = int(temp_num)
        if temp_num <= 0:  # if not a positive int print message and ask for input again
            print("Sorry, the number of knights must be a positive integer, try again")
        else:
            knights_num = temp_num
            break
    except ValueError:
        print("That's not an integer!")
# else all is good, val is >=  0 and an integer

# Create a table of knights and a temp table
knights_table = [i for i in range(1,knights_num+1)]
knights_temp_table = list(knights_table)

i = 1
while len(knights_temp_table)>1:
# print("Knights =",knights_temp_table , "(",knights_temp_table[i],")")
    knights_temp_table.pop(i)
    i = (i+1)%len(knights_temp_table)
print( "The knight who survived was no.",knights_temp_table[0] )

The code runs fine and outputs the expected values n=60> 57 and n=16 > 1
However from the code it is not clear why it works. So i had some questions below

Could the table of knights be made using a generator?
Is a code using try knights_temp_table[i+1] and knights_temp_table[i+2] and then iterating over the list for the exceptions clearer?
Could one implement a linked list to make the code clearer instead of modulo?

I know the code is very simple and the problem I solved almost trivial. However any suggestions is much appreaciated since I am a semi-begginer / novice at python.
 * Are there any other general suggestions to improve the code, or running speed?


texts: Find out whether a given text contains any of the prohibited words

texts:
We have been given a list of strings which are blacklisted. The goal is to identify if a given text contains any of these blacklisted strings. The restriction here is that the blacklisted string needs to match on the word boundary e.g. consider a blacklist string "abc" and text "abc pqr", the text in this case is unsafe (i.e. it contains a blacklisted string). On the other hand if the text is "abcoqr", then the text is safe since the string "abc" is not on the word boundary. Also the relative ordering of words in a blacklisted string needs to be checked e.g. if a blacklisted string is "abc pqr", then the text "pqr abc" is safe since the ordering of the words in the text does not match that of the blacklisted string.

Here is my solution using a modified Trie data structure. https://gist.github.com/hgadre/d4e9ec576932167f01fd33970002a882

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SafeText {
    static class Tuple {
       int span = 0; // the length of previous words which should have been matched if end = true.
       boolean end; // marks the identification of a blacklisted string.
       Set<String> nextWords = new HashSet<>(); // next set of words to search for matching blacklisted strings.

       public void setEnd(boolean end, int span) {
          this.span = span;
          this.end = end;
       }

       public boolean isEnd(int span) {
           return end && span == this.span;
       }

       public void addNextWord (String word) {
           this.nextWords.add(word);
       }

       public boolean containsWord(String word) {
           return this.nextWords.contains(word);
       }
    }

    private final Map<String, Tuple> m = new HashMap<>();

    public SafeText(List<String> blackList) {
        Collections.sort(blackList);
        for (String str : blackList) {
           String[] tokens = str.split("\\s");
           int i = 0;
           for (; i < tokens.length - 1; i++) {
              m.computeIfAbsent(tokens[i], x -> new Tuple()).addNextWord(tokens[i+1]);
           }
           m.computeIfAbsent(tokens[i], x -> new Tuple()).setEnd(true, tokens.length-1);
       }
    }

    public boolean isSafe(String text) {
        String[] tokens = text.split("\\s");
        for (int i = 0; i < tokens.length; i++) {
        String key = tokens[i];
        int j = i;
        while (j < tokens.length && m.containsKey(key)) {
            Tuple t = m.get(key);
            if (t.isEnd(j-i)) {
               return false;
            } else if ((j+1) < tokens.length && t.containsWord(tokens[j+1])) {
               key = tokens[j+1];
               j++;
            } else {
               break;
            }
         }
      }
      return true;
    }
 }

Is this an optimal solution? Or is there any better approach to solve this problem?


texts:
I got the solution for the question asked here, but I don't like how the code is written.

This part of the code rotates the screen if it's in landscape and sets the size to match the screen. I don't like the if and the 7x else if. Can you suggest something more readable? Something like (appOrientation - fromInterfaceOrientation) == 2 than angle (M_PI / 2.0)?

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{

    UIInterfaceOrientation appOrientation = [UIApplication sharedApplication].statusBarOrientation;
    float width = self.view.bounds.size.width;
    float height = self.view.bounds.size.height;
    //NSLog(@"width %3.0f, height: %3.0f", width, height);

//    UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
//    UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
//    UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,
//    UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft

    CGFloat angle = 0;

    // rotate from Portait
    if((fromInterfaceOrientation == UIInterfaceOrientationPortrait) && (appOrientation == UIInterfaceOrientationLandscapeLeft)){
        angle = -(M_PI / 2.0);
    }
    else if((fromInterfaceOrientation == UIInterfaceOrientationPortrait) && (appOrientation == UIInterfaceOrientationLandscapeRight)){
        angle = (M_PI / 2.0);
    }
    // rotate from PortraitUpsideDown
    else if((fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) && (appOrientation == UIInterfaceOrientationLandscapeLeft)){
        angle = (M_PI / 2.0);
    }
    else if((fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) && (appOrientation == UIInterfaceOrientationLandscapeRight)){
        angle = -(M_PI / 2.0);
    }

    //rotate from Landscape:
    else if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) && (appOrientation == UIInterfaceOrientationPortrait)){
        // search for exactly the inverse...
    }
    // must be something more elgant code

    CGAffineTransform transform = self.view.transform;
    transform = CGAffineTransformRotate(transform, angle);
    self.view.transform = transform;

    [self.view setBounds:CGRectMake(0, 0, height, width)];


texts:
I have the following manager class that handles access and caching attributes from classes. I am a bit worried about the caching mechanism.

Is there a better way of handling it?

public static class AttributeManager
    {
        private static Dictionary<Type, Attribute> _cache = new Dictionary<Type, Attribute>();

        public static AttributeType GetAttribute<AttributeType>(Type type)
            where AttributeType : Attribute
        {

            if (_cache.ContainsKey(type))
            {
                return (AttributeType)_cache[type];
            }

            var attr = Attribute.GetCustomAttribute(type, typeof(AttributeType));

            if (attr != null)
            {
                _cache.Add(type, attr);
                return (AttributeType)attr;
            }
            else
            {
                throw new ArgumentException($"The specified attribute: {nameof(AttributeType)} was not found.");
            }
        }
    }


texts: WebAPI - Return models vs entity and partial class with meta data

texts:
Wanted some opinions on something I have been working with, I've tried a few ways of structuring the way I retrieve and return data to my WebAPI, and I'm pretty happy with what I have so far, but I was looking for a comparison of the pro's and con's of using models vs entities for returning data on the WebAPI.

In my opinion, from what I've seen, adding a model factory and returning models is good because you get control over what your object looks like, but it does mean you now have to map the entities to that model somewhere, increasing the code you have to write, particularly if you have a lot of entities.

On the other hand, having partial classes of the generated objects allows me the same extensibility, and by adding a meta data class using MetadataType(typeof(typename)), I am able to decide what will be serialized and how they are built, giving me full control again over the structure, and being able to extend it when I want to, rather than having to for every entity.

So, if I can get the same benefits with partials and metadata, without the additional code in mapping to models, what are other downsides, how come this approach is not as common? I mean, if I wanted I could do the mapping this way too, without the need for any factories to do the mapping, just by attributing the fields to be ignored and creating new ones with Get/Set to point to the original property.

An example:

Generated by T4 template:

 public partial class FileHeader : BaseEntity
 {
    public FileHeader()
    {
        this.FileVersionSubs = new HashSet<FileVersion>();
    }

    public int FileId { get; set; }
    public string Name { get; set; }
    public string Caption { get; set; }

    public virtual ICollection<FileVersion> FileVersionSubs { get; set; }
 }

The partial I make:

[MetadataType(typeof(FileHeaderMetaData))]
public partial class FileHeader
{
    // Additional fields go here
}

Metadata file:

public class FileHeaderMetaData
{
    // Any attributes for existing fields here, eg:
    [MyCustomAttribute]
    public int FileId { get; set; }
}

If I were to approach this from a Model point of view, I would be repeating the same properties for every class I generate and wanted to return as well as mapping them, rather than the ones I explicitly want to change or hide.

Thoughts, feelings and suggestions welcome!


texts: Program that converts a number to a letter of the alphabet

texts:
#include <iostream>

int main() {
    int letter = 0;
    std::cout << "Please type in a number: ";

    while (1) {
        std::cin >> letter;
        //less than 1 or greater than 26
        if (!(letter < 1 || 26 < letter)) {
            std::cout << "The letter that corosponds to that value is '"
                      << char(64+letter) << "'\n";
            return 0;
        }
        std::cout <<"The English Alphabet only has 26 letters. Try again\n";
    }
}

Gets a integer and prints it as a character. I had thought about using stdio instead of stream but I didn't want it to look scary to a beginner.


texts: Ruby script to to check the status of a rabbitmq queue and send alert

texts:
We are using a message broker called rabbitmq. The code checks the status of number of messages in q queue and sent messages. This is achieved by a curl request to a given API.The script has a sleep of 5 seconds. I want to beutify and optimize this code for memory. I am getting offences too many lines. Since there is an infinite loop Want to make sure code does not leak memory.

 require 'net/http'
 require 'uri'
 require 'json'
 require 'slack-notifier'
 require 'sevak_publisher'

  CONFIG = YAML.load_file(File.join(__dir__, 'rabbitmq_config.yml'))
  def monitor_rabbitmq
      rabbitmqctl_url = CONFIG['rabbitmqctl']['url']
      rabbitmqctl_user = CONFIG['rabbitmqctl']['username']
      rabbitmqctl_password = CONFIG['rabbitmqctl']['password']
      uri = URI.parse("#{rabbitmqctl_url}/api/queues")
      request = Net::HTTP::Get.new(uri)
      request.basic_auth(rabbitmqctl_user, rabbitmqctl_password)
      req_options = { use_ssl: uri.scheme == 'https' }
      response = Net::HTTP.start(uri.hostname, uri.port, req_options)  do |http|
           http.request(request)
     end
    queue_details = JSON.parse(response.body)
    queue_details.each do |queue|
          output = { name: queue['name'],
           messages: {
             total: queue['messages'],
             ready: queue['messages_ready'],
             Unacknowlged: queue['messages_unacknowledged']
           },
           node: queue['node'],
           state: queue['state'],
           consumers: queue['consumers'] }
         puts output
         if output[:messages][:ready] > 1
              sent_alert_slack("RabbitMQ QUEUE High! \n #{output[:messages][:ready]} :\n #{output}")
              sent_sms(message)
         end
      end
   end
   def sent_alert_slack(message)
      notifier = Slack::Notifier.new CONFIG['slack_settings']    ['notification_api'],
                             channel: '#rabbitmq-monitoring',
                             username: 'notifier'
      notifier.ping message
    end

    def sent_sms(message)
        SevakPublisher.configure do |f|
          f.host = CONFIG['bunny']['host']
          f.port = CONFIG['bunny']['port']
          f.username = CONFIG['bunny']['username']
          f.password = CONFIG['bunny']['password']
          f.queues = ['sms_default']
        end
        publisher = SevakPublisher::Publisher.new
        CONFIG['sms_alert_receivers'].each do |msisdn|
           publisher.publish('sms_default', msisdn: msisdn, message:     message)
        end
    end
   loop do
      begin
      puts "\n", Time.now
      monitor_rabbitmq
   rescue => e
     puts "Error: #{e.message}"
     end
    sleep(300)
    end


texts:
Linked:
Google reCAPTCHA Validator: Iteration II

I have also created a simple Google Recaptcha Validation class to handle verification.

I used some code from CodingFusion's post Google New reCaptcha I am not a robot using asp .net, but I have altered it so that it fit my use case, and to make it extendable and reusable.

Can I clean it up further?

public class ReCaptchaValidator
{
    private readonly string _ReCaptchaSecret;
    private readonly string _ReCaptchaSiteKey;
    public List<string> ErrorCodes { get; set; }

    public ReCaptchaValidator(string reCaptchaSecret)
    {
        _ReCaptchaSecret = reCaptchaSecret;
        this.ErrorCodes = new List<string>();
    }
    public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)
    {
        _ReCaptchaSecret = reCaptchaSecret;
        _ReCaptchaSiteKey = reCaptchaSiteKey;
        this.ErrorCodes = new List<string>();
    }

    public bool ValidateCaptcha(HttpRequest request)
    {
        var sb = new StringBuilder();
        sb.Append("https://www.google.com/recaptcha/api/siteverify?secret=");
        sb.Append(_ReCaptchaSecret);
        sb.Append("&response=");
        sb.Append(request.Form["g-recaptcha-response"]);

        //client ip address
        sb.Append("&remoteip=");
        sb.Append(GetUserIp(request));

        //make the api call and determine validity
        using (var client = new WebClient())
        {
            var uri = sb.ToString();
            var json = client.DownloadString(uri);
            var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
            var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            var result = serializer.ReadObject(ms) as RecaptchaApiResponse;

            if (result == null)
            {
                return false;
            }
            else if (result.ErrorCodes != null)
            {
                foreach(var code in result.ErrorCodes)
                {
                    this.ErrorCodes.Add(code.ToString());
                }
                return false;
            }
            else if (!result.Success)
            {
                return false;
            }
            else //-- If successfully verified.
            {
                return true;
            }
        }
    }

    //--- To get user IP(Optional)
    private string GetUserIp(HttpRequest request)
    {
        var visitorsIpAddr = string.Empty;

        if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            visitorsIpAddr = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        }
        else if (!string.IsNullOrEmpty(request.UserHostAddress))
        {
            visitorsIpAddr = request.UserHostAddress;
        }
        return visitorsIpAddr;
    }

}
[DataContract]
public class RecaptchaApiResponse
{
    [DataMember(Name = "success")]
    public bool Success;

    [DataMember(Name = "error-codes")]
    public List<string> ErrorCodes;
}


texts: Programmatic text substitution across rows and columns in R

texts:
I'm replaced character strings with numeric codes in R. I find myself doing a lot of copying and pasting, so there's probably a better solution with apply, sapply, or ddply that I'm missing.

Here's an example:

example <- data.frame(matrix(nrow = 20, ncol = 20))
example[,1]  <- 30:49
example[,10] <- 10:29
example[,2]  <- c("apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                  "apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                  "apple", "banana", "gum", "steak")
example[,3:9]  <- c("banana", "gum", "steak", "apple", "banana", "gum", "steak",
                    "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                    "banana", "gum", "steak", "apple", "apple", "apple")
example[,11:20]  <- c("apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                      "apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                      "apple", "banana", "gum", "steak")
names(example) <- c("ID", "food_day_1", "food_day_2", "food_day_3", "food_day_4",
                    "food_day_5", "food_day_6", "food_day_7", "food_day_8",
                    "Some_Numeric_Code", "otherfood_day_1", "otherfood_day_2",
                    "otherfood_day_3", "otherfood_day_4", "otherfood_day_5",
                    "otherfood_day_6", "otherfood_day_7", "otherfood_day_8",
                    "otherfood_day_9",  "otherfood_day_10")

which looks like:

> head(example)
  ID food_day_1 food_day_2 food_day_3 food_day_4 food_day_5 food_day_6 food_day_7 food_day_8 Some_Numeric_Code otherfood_day_1
1 30      apple     banana     banana     banana     banana     banana     banana     banana                10           apple
2 31     banana        gum        gum        gum        gum        gum        gum        gum                11          banana
3 32        gum      steak      steak      steak      steak      steak      steak      steak                12             gum
4 33      steak      apple      apple      apple      apple      apple      apple      apple                13           steak
5 34      apple     banana     banana     banana     banana     banana     banana     banana                14           apple
6 35     banana        gum        gum        gum        gum        gum        gum        gum                15          banana
  otherfood_day_2 otherfood_day_3 otherfood_day_4 otherfood_day_5 otherfood_day_6 otherfood_day_7 otherfood_day_8 otherfood_day_9
1           apple           apple           apple           apple           apple           apple           apple           apple
2          banana          banana          banana          banana          banana          banana          banana          banana
3             gum             gum             gum             gum             gum             gum             gum             gum
4           steak           steak           steak           steak           steak           steak           steak           steak
5           apple           apple           apple           apple           apple           apple           apple           apple
6          banana          banana          banana          banana          banana          banana          banana          banana
  otherfood_day_10
1            apple
2           banana
3              gum
4            steak
5            apple
6           banana

Here's what I did:

example$food_day_1[example$food_day_1 %in%
                            c("apple", "banana")] <- 1
example$food_day_1[example$food_day_1 %in%
                     c("gum", "steak")] <- 2

and so on.

What should I have done?


texts: Why is my C program for calculating Euler's constant of poor quality?

texts:
I was trying to post this code to a Wikipedia article, but it was soon removed.  I then asked about the code in the page's talk section, and some other contributors said that is was "very poor"  and that "there are clearly going to be underflows all over the place."  What does that mean?  What is an "underflow"?

Could you please tell me more about my program's flaws and how it can be improved?  Please give me some constructive criticism.  Here is where I originally posted the code.

#include <stdio.h>

long factorial(int n) {
    long result = 1;
    for (int i = 1; i <= n; ++i)
    result *= i;
    return result;
}

int main ()
{
    double n=0;
    int i;
    for (i=0; i<=32; i++) {
        n=(1.0/factorial(i))+n;
    }
    printf("%.32f\n", n);
}

Here is the result of the program 2.71828182845904553488480814849027


texts:
The pusherr and poperr procedures maintain an internal stack as a lisp-like
linked-list. It's a little slower than an earlier stackwise
version according to naive testing. It allocates lots of 2- and 3- element
arrays for its data. But the code using them becomes very readable IMO with this
approach.

The memo-func function generates a procedure body specified by the
template but with the DICT replaced by the dict argument.

The resulting procedure simply pushes the local dict, then pushes an error handler for the /undefined
error, then just does load, and pops the handler and the dict. If load does not find the needed value, it will signal an /undefined error which will be caught be our handler.

The error handler calls the procedure named /default and saves the input and output as a new definition in the local dict.

Improvements?

%!

<<
/errorstack null  % [ {errordict/errname{handler}} null ]

/pusherr {
    errordict 3 1 roll 3 copy pop 2 copy get    % ed /n {new} ed /n {old}
    3 array astore cvx  errorstack   2 array astore  /errorstack exch store
    put
}

/poperr {
    errorstack dup null ne {
        aload pop  /errorstack exch store
        exec put
    } if
}

/memo-func {
    {
        DICT begin
            /undefined { pop dup default dup 3 1 roll def } pusherr
                load
            poperr
        end
    }
    dup length array copy
    dup 3 2 roll 0 exch put cvx
}
>> begin

/fib <<
    0 1
    1 1
    /default { dup 2 sub fib  exch 1 sub fib  add }
>> 100 dict copy  memo-func  def

0 1 100 {  fib =  } for

The 100 dict copy allows you to also set the initial size of the dictionary to  determine how many entries you can add before it needs to rehash.

This code was previously posted in comp.lang.postscript at the end of a thread which includes the stackwise version mentioned above.


texts: Simple for loop to calculate headers size based on a specific ratio

texts:
How can I improve the following for loop (wannabe function) to create harmonic sizes for headers based on a specific ratio?

var base = 16;
var goldenRatio = 1.618;
var list = "";
for(var i=6; i>0; i--){
    list = "\nh" + i + " { font-size: " + base + "px; }" + list;
    base *= Math.round(base*goldenRatio);
}
console.log(list)


texts:
My approach was to find each occurrence of the PNG's file signature followed by its end of file (EOF) and write the bytes between to a new file whose name is simply a counter starting at zero.

use std::env;
use std::fs::File;
use std::io::prelude::*;

const SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
const EOF: [u8; 8] = [73, 69, 78, 68, 174, 66, 96, 130];

fn main() {
    let path = env::args().nth(1).unwrap();
    let mut f = File::open(path).unwrap();

    let mut buf = Vec::new();
    f.read_to_end(&mut buf).unwrap();

    let mut iter = buf.iter();
    let mut i = 0;

    while let Some(start) = iter.rposition(|&x| x == SIGNATURE[0]) {

        if buf[start..].starts_with(&SIGNATURE) {

            let mut iter = buf[start..].iter();

            let mut end = iter.position(|&x| x == 130).unwrap();

            loop {
                let slice = &buf[start..start + end + 1];
                if slice.ends_with(&EOF) {
                    let mut f = File::create(i.to_string() + ".png").unwrap();
                    f.write_all(slice).unwrap();
                    i += 1;
                    break;
                }

                end += match iter.position(|&x| x == 130) {
                    Some(x) => { x + 1 },
                    None => break,
                };
            }
        }
    }
}

The only reason I used rposition instead of position for start was because the file I was working with had all its PNG's embedded at the end.

I had attempted to replace some of the unwraps with try!s but realized that the macro needs to be called from a function that returns a Result, i.e. can't be used in fn main(), and couldn't figure out how best to break up the code.

Was wondering if there might be a better way to approach the problem. If not, how can I at least clean up this implementation?


texts:
I was learning some DOM manipulation and interaction with third-party APIs by building a simple interface to get the people who commented on a PR on GitHub.

I got great feedback for my initial prototype: Interface for getting Github PRs commenters using Github API.

Now I am trying to get into OOP using ES6 Classes, so I build this GitHubPR class to handle all the interaction with the GitHub API:

const apiUrl = 'https://api.github.com'

export default class GitHubPR {
  constructor(prUrl) {
    GitHubPR.validatePRUrl(prUrl)
    this.prUrl = new URL(prUrl)
    this.prApiUrl = GitHubPR.prUrlToApiEndpoint(prUrl)
  }

  static validatePRUrl(prUrl) {
    if (!GitHubPR.isValidPRUrl(prUrl)) {
      throw new Error('Not a valid GitHub Pull Request Url.')
    }
    return prUrl
  }

  static isValidPRUrl(prUrl) {
    const githubPullRequestPattern = RegExp(
      /^https:\/\/github.com\/[\w-_.+]+\/[\w-_.+]+\/pull\/\d+\/?$/
    )
    return githubPullRequestPattern.test(prUrl)
  }

  static prUrlToApiEndpoint(prUrl) {
    GitHubPR.validatePRUrl(prUrl)
    const { pathname } = new URL(prUrl)
    const prApiUrl = new URL(
      `/repos${pathname.replace('/pull/', '/pulls/')}`,
      apiUrl
    )
    return prApiUrl
  }

  static async fetch(endpoint) {
    const apiOptions = {
      headers: {
        Accept: 'application/vnd.github.v3+json',
      },
    }
    const url = endpoint.startsWith(apiUrl) ? endpoint : `${apiUrl}${endpoint}`
    return (await fetch(url, apiOptions)).json()
  }

  fetchInfo() {
    return GitHubPR.fetch(this.prApiUrl.pathname)
  }

  fetchReviews() {
    return GitHubPR.fetch(`${this.prApiUrl.pathname}/reviews`)
  }

  async fetchReviewers() {
    const reviews = await GitHubPR.fetch(`${this.prApiUrl.pathname}/reviews`)
    const uniqueReviewers = [...new Set(reviews.map(review => review.user.url))]
    return Promise.all(
      uniqueReviewers.map(reviewer => GitHubPR.fetch(reviewer))
    )
  }
}

I would love to have some feedback on this. I am new to OOP and ES6 classes, so not sure if this is following good practices or if I am making good use for a class here, or how could I make this class more robust according to OOP principles.

My idea is being able to use it in something like this:

import GitHubPR from './github-pr'

document
  .querySelector('#pull-request-form')
  .addEventListener('submit', onsubmit)

async function onsubmit(event) {
  event.preventDefault()
  const pr = new GitHubPR(document.querySelector('#pull-request-url').value)
  const [info, reviewers] = await Promise.all([
    pr.fetchInfo(),
    pr.fetchReviewers(),
  ])
  renderInfo(info)
  renderReviewers(reviewers)
}


texts:
I want to backup a single SQLite database daily up to 30 days back, but I also want to keep at least 2 backups at all times (i.e. if there have been no backups in the last 30 days because the database didn't change, I don't want to delete old backups).

I came up with this simple script that is supposed to run as a daily cronjob:

#!/bin/bash

BACKUP_FILE="/path/to/db.sqlite3"
BACKUP_DIR="$HOME/backups"

today=`date "+%Y-%m-%d"`

# Less than 31 days old, i.e. 30 days or younger
if find "$BACKUP_FILE" -type f -mtime -31 | grep -q .
then
        find "$BACKUP_DIR" -type f -mtime +30 -exec rm {} \;
fi

last_backup=$(ls -t "$BACKUP_DIR" | head -1)
if [ -n "$last_backup" ] && diff "$BACKUP_FILE" "$BACKUP_DIR/$(ls -t "$BACKUP_DIR" | head -1)" >/dev/null
then :
else
        cp "$BACKUP_FILE" "$BACKUP_DIR/$today.sqlite3"
fi

I'm not sure if using a nop in the second then clause makes sense, but it seemed cleaner to me than wrapping the condition in a test and checking $?.

The database is used by <20 people and not changed very often, but I'm not sure if I should lock the database anyways - and I'm also not sure how to lock it from a shell script.

Since this is the first bash script I've ever written for serious use, I'd appreciate any feedback on how it could be improved.


texts:
I have an Android app that uses randomly generated tokens to log in.  They're 5 characters long, are sent to a user's email address, and have a short lifespan, so I don't think I need anything that's extremely secure.

I'm getting odd result that suggest I'm not really generating random numbers.  That, or I'm seeing patterns that don't really exist.

For example, the last few tokens generated were:

0pqrH
UMOPQ
d789r
jmnde

These have patterns:

pqr
789
all caps
all lowercase

There are some tokens generated with scattered characters:

f80!#
NLog#
Z6kpJ

It just seems that there are too many patterns to be coincidence.

static public String getToken(int chars) {
    String CharSet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890!@#$";
    String Token = "";
    for (int a = 1; a <= chars; a++) {
        Token += CharSet.charAt(new Random().nextInt(CharSet.length()));
    }
    return Token;
}

Am I generating random numbers correctly? Should I be picking a seed? Is this in my imagination?


texts: Most efficient solution for USACO: Cow Gymnastics - Python

texts:
I was trying to figure out this problem, and I did. However, my code is so abhorrently ugly that I want to tear out my eyeballs when I look at it:
with open("gymnastics.in", "r") as fin:
  rounds, cows = [int(i) for i in fin.readline().split()]
  nums = [tuple(map(int, line.split())) for line in fin]

def populatePairs(cows):
  pairs = []
  for i in range(cows):
      for j in range(cows):
          if i != j:
              pairs.append((i+1,j+1))
  return pairs

def consistentPairs(pairs, nums):
  results = []

  for i in pairs:
      asdf = True
      for num in nums:
          for j in num:
              if j == i[1]:
                  asdf = False
                  break
              if j == i[0]:
                  break
          if not asdf:
              break
      if asdf:
          results.append(i)

  return results

pairs = populatePairs(cows)

with open("gymnastics.out", "w+") as fout:
  print(len(consistentPairs(pairs, nums)), file=fout)

I feel like that there should definitely be a better solution that is faster than \$O(n^3)\$, and without the triple nested for-loop with the if-statements trailing behind them, but I cannot, for the love of god, think of a better solution.
Problem synopsis:
Given an \$n\$ by \$m\$ grid of points, find the number of pairs in which number is consistently placed before the other.
Example:
Input:
3 4
4 1 2 3
4 1 3 2
4 2 1 3

Output:
4
Explanation:
The consistent pairs of cows are (1,4), (2,4), (3,4), and (3,1), in which case 4 is consistently greater than all of them, and 1 is always greater than 3.


texts: Linked lists of templated classes vs function ptr

texts:
I am designing a library for a hierarchical problem. At each stage of the hierarchy there are several "tools" at hand. If at a state N one tool succeeds, the solution is passed to the next (N+1) state. If all tools of stage N fail, we return to the state N-1 (previous) and let the previous stage handle the problem.

I have two possible ideas how to structure this problem. One uses a linked list of templated classes, the other binds directly to the next stage's run function.
My question is, is any of these superior to the other (or are both flawed) and why?

The first solution uses templates to create a linked list of templated classes.

template <typename Input, typename Output>
struct BaseSolver
{
    virtual boost::optional<Output> run(const Input& _input) = 0;
};

template<typename Input>
struct BaseStage
{
    virtual bool runAndRecover(const Input &_input)
    {
        return true;
    }
};

template<typename Input, typename Output>
struct Stage1 : BaseStage<Input>
{
    bool run(const Input& _input)
    {
        for(const auto& solver : solvers_)
        {
            const auto currentResult = solver->run(_input);
            if(currentResult && nextStage->runAndRecover(currentResult.get()))
            {
                return true;
            }
        }
        return false;
    }

    std::vector<boost::shared_ptr<BaseSolver<Input, Output>>> solvers_;

    BaseStage<Output>* nextStage;
};

This is the other solution. It binds only to the run() function of the next stage

template<typename Input, typename Output>
struct Stage2
{
    typedef boost::function<boost::optional<Output> (Input)> SolverFunction;
    typedef boost::function<bool(Output)> NextStage;

    bool run(const Input& _input)
    {
        for(const auto& solver : solverFunctions_)
        {
            const auto solverResult = solver(_input);
            if(solverResult && nextStage_(solverResult.get()))
            {
                return true;
            }
        }
        return false;
    }

    std::vector<SolverFunction> solverFunctions_;
    // will be bind to the next stage::run
    NextStage nextStage_;
};

PS: Both versions compile and run as a prototype.


texts: Sorting elements according to frequency of occurence in C++

texts:
I am sorting the elements in an array according to their frequency of occurrence in decreasing order and if two elements have same frequency then they are sorted in increasing order. I have used std::map to count the frequency and then copy the elements from std::map to std::vector<std::pair<K, V>>.

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

struct greater
{
   template<class T>
   bool operator()(T const &a, T const &b) const { return a.second > b.second; }
};

template<class T>
void sortByFreq(std::vector<T>& v)
{
  std::map<T, T> count;

  for (int i : v){
      count[i]++;
  }

  std::vector<std::pair<T, T>> mapcopy;

  for(auto itr = count.begin(); itr != count.end(); itr++)
  {
    mapcopy.push_back(*itr);
  }

  std::sort(mapcopy.begin(), mapcopy.end(), greater());

  std::cout << "Elements sorted according to Frequency \n";

  auto itr = mapcopy.begin();
  while(itr != mapcopy.end())
  {
    for(int i = 0; i < itr->second; i++)
    {
      std::cout << itr->first <<" ";
    }
  itr++;
  }

}

int main()
{
  std::vector<int> vec = {2, 3, 2, 4, 5, 12, 12, 3, 4, 3};
  sortByFreq(vec);
  std::vector<char> c ={ 'e', 't', 'r', 'e', 't', 't', 'f'};
  sortByFreq(c);
return 0;
}

The Output is

3 3 3 2 2 4 4 12 12 5
t t t e e f r

Review this code and help me to improve it.


texts: C function to print arrays of arbitrary data type

texts:
C is naturally clumsy at polymorphism but I wanted to avoid duplication so I wrote this function. But I'm sure there are ways left to improve it. Please not that for brevity's sake not all data types have been included.

void print_int(const void *number) {
    int result = *((int*) number);
    printf("%d ", result);
}

void print_double(const void *number) {
    double result = *((double*)number);
    printf("%f ", result);
}

/// Prints arrays of arbitrary type
/// \param array The array to print
/// \param length The length of the array
/// \param type The data type xxx of the array elements in the form of "TYPE_XXX"
/// \return 1 in case of an invalid data type
int print_array(const void *array, size_t length, char *type) {

    void (*function)(const void *number);
    void *cast_array;
    size_t size;

    if (!strcmp(type, TYPE_INT)) {
        function = print_int;
        cast_array = (int *) array;
        size = sizeof(int);
    } else if (!strcmp(type, TYPE_DOUBLE)) {
        function = print_double;
        cast_array = (double *) array;
        size = sizeof(double);
    } else {
        return 1;
    }

    for (size_t i = 0; i < length; ++i) {
        function(cast_array + i * size);
    }
    printf("\n");
    return 0;
}


texts:
I have a concept of the user having many API keys, but the API key belongs to the user, so I did the following:

config/routes.rb

  resources :users do
    resources :api_keys, path: '/developmentcenter'
  end

app/models/api_key.rb

class ApiKey < ActiveRecord::Base
  belongs_to :user
end

app/controllers/api_keys.rb

Note: I have separate some of the logic up because I don't like messy methods, so I split them into lib/aisis_planner/api_keys_controller_mixins.rb.

class ApiKeysController < ApplicationController
  before_action :authenticate_user!

  def index
    @user = User.find(params[:user_id])
    @api_key = User.apikeys
  end

  def create
    @user = User.find(params[:user_id])
    @api_key = ApiKey.new(create_new_api_key)
    create_api_key(@api_key, @user)
    end

  def destroy
    @user = User.find(params[:user_id])
    destroy_api_key(@user)
  end

  private

  def create_new_api_key
    params.permit(:api_key, user_attributes: [:id])
  end
end

lib/aisis_planner/api_keys_controller_mixins.rb

module AisisPlanner
  module ApiKeysControllerMixins
    def create_api_key(api_key, user)
      if api_key.save
        flash[:notice] = 'Created a new API Key'
        redirect_to user_path(user.id)
      else
        flash[:alert] = 'Could not create API Key please try again'
        redirect_to user_path(user.id)
      end
    end

    def destroy_api_key(user)
      ApiKey.find(params[:id]).destroy
      flash[:notice] = 'Api Key has been deleted.'
      redirect_to user_path(user.id)
    end
  end
end

Now for the tests. There are no integration tests at this time (I use capybara).

require 'spec_helper'

describe ApiKeysController do
  let(:user) { FactoryGirl.create(:user) }

  describe "#create" do
    it "should not create an api key for those not logged in" do
      post :create, :user_id => '', :id => ''
      expect(response).to redirect_to login_path
    end

    it "should create an api key" do
      sign_in user
      cookies[:auth_token] = user.auth_token
      post :create, :user_id => user.id.to_param
      expect(response).to redirect_to user_path(user.id)
    end
  end

  describe "#destroy" do
    it "should not delete an api for a user not logged in" do
      post :destroy, :user_id => '', :id => ''
      expect(response).to redirect_to login_path
    end

    it "should delete an api key for a logged in user" do
      sign_in user
      cookies[:auth_token] = user.auth_token
      key = FactoryGirl.create(:api_key, user_id: user.id)
      post :destroy, :user_id => user.id.to_param, :id => key.id.to_param
    end
  end
end

What are your thoughts?


texts: Improve if-statement for multiple strings

texts:
I working with a lot of Strings which I get from a web-form:

final String user = request.getParameter("user");
final String pw = request.getParameter("password");
final String name = request.getParameter("name");
final String shortname = request.getParameter("shortname");
final String appl_name = request.getParameter("appl_name");
final String db_size_str = request.getParameter("db_size");
final String was_admin_string = request.getParameter("was_admin");
final String sap_nr = request.getParameter("sap_nr");
final String etl_string = request.getParameter("etl");
final String mq_string = request.getParameter("mq");
final String msg_broker_string = request.getParameter("msgbroker");
final String java_batch = request.getParameter("javab");
final String server = request.getParameter("server");
final String apverantw1 = request.getParameter("appliverantw1");
final String apverantw2 = request.getParameter("appliverantw2");
final String psp = request.getParameter("psp");
final String version = request.getParameter("version");
final String applialias = request.getParameter("applialias");
final String applityp = request.getParameter("applityp");
final String data = request.getParameter("data");
final String yesdata = request.getParameter("yesdata");
final String moreoptions = request.getParameter("moreoptions");

If only one of them is empty, the program should be stopped. At this time I check that with an ugly if-statement if no one of the strings is empty:

if (user != null && name != null && shortname != null && appl_name != null && db_size_str != null && was_admin_string != null && sap_nr != null && etl_string != null && mq_string != null
                && msg_broker_string != null && java_batch != null && server != null && apverantw1 != null && apverantw2 != null && psp != null && version != null && applialias != null
                && applityp != null && data != null && yesdata != null && moreoptions != null)

This was produced over the time when I added one string after one.
How can I improve this? I mean, it is a really big, ugly if-statement. But I don't have a clue how can I write this even better.


texts:
It starts by taking two user input from the console and putting them into strings. I then pad them to get them to the same length. I get the length of the num1 and assign it to the integer len. I then start a for loop from 1 to the value of len.

I get the last charterer in num1 and num2 and assign then to char1 and char2.
I then add pass which is a integer, num1 and num2 to get the total of a colum like if you were doing normal addition by hand.
I do a bitwise AND to get check if the number would have anything in the units column. If it would I add on to the start of my total. Else I add a zero.
I then do a right shift on the column_total and assign it to pass. This is to pass on any values which need to go into the next column.

In the next bit I have a while loop which would run until it clears out pass. I assign pass into column_total. I have the same logic to before with the if and else but instead of shifting column_total we now shift pass.

I then just write the total to console.

Module Module1

    Sub Main()
        Dim pass, column_total, len As Integer
        Dim total, char1, char2 As String

        Console.Write("Please enter your first binary number")
        Dim num1 As String = Console.ReadLine()

        Console.Write("Please enter your second binary number")
        Dim num2 As String = Console.ReadLine()

        If num1 > num2 Then
            num2 = num2.PadLeft(num1.Length() - num2.Length + 1, "0"c)
        Else
            num1 = num1.PadLeft(num2.Length() - num1.Length + 1, "0"c)
        End If

        len = num1.Length()

        For i = 1 To num1.Length()
            char1 = num1.Chars(len - i)
            char2 = num2.Chars(len - i)
            column_total = pass + char1 + char2

            If column_total And &H1 Then
                total = "1" + total
            Else
                total = "0" + total
            End If
            pass = column_total >> 1
            Console.WriteLine(total)

        Next

        While pass <> 0
            column_total = pass
            If column_total And &H1 Then
                total = "1" + total
            Else
                total = "0" + total
            End If
            pass >>= 1
        End While

        Console.WriteLine("The answer is: " & total)
        Console.ReadLine()

    End Sub

End Module


texts:
I am writing spring hibernate app to make online test and this method for calculating user grade I have one to many relations between multi-choice question and answer.

Also, please check this question

@Service
public class StudentServiceImpl implements StudentService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    QuestionRepository questionRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    Transformer transformer;

    @Override
    @Transactional
    public void correctAnswer(List<StudentAnswersDTO> questionAnswers) {
        logger.info("****** start correct answers ********");
        Long grade = 0L;
        List<QuestionRightAnswerDTO> rightAnswerDTOS = questionRepository.getRightAnswers();
        for (StudentAnswersDTO questionAnswer : questionAnswers) {
            if (questionAnswer.getType().toLowerCase().equals(AppConstants.MULTI_CHOICE)) {
                if (isCorrectAnswer(questionAnswer.getId(), questionAnswer.getAnswerId(), rightAnswerDTOS))
                    grade++;
            }
        }

        User currentStudent = userRepository.findByMobileNumber(SecurityHelper.getCurrentUser());
        ((Student) currentStudent).setGrade(grade);
        ((Student) currentStudent).setStudentAnswers(transformer.transform(questionAnswers, AnswerSelected.class));

        logger.info("****** end correct answers ********");
    }

    private boolean isCorrectAnswer(Long id, Long answerId, final List<QuestionRightAnswerDTO> rightAnswerDTOS) {
        for (QuestionRightAnswerDTO rightAnswer : rightAnswerDTOS) {
            if (id.equals(rightAnswer.getQuestionId()) && answerId.equals(rightAnswer.getAnswerId()))
                return true;
        }
        return false;
    }
}


texts:
It is sometimes necessary for a generator function to expose state. In those situations it is advised to wrap the generator function as method __iter__ in a class. Here is an example:

class C:
    def __iter__(self):
        for i in range(4):
            yield i
            self.state = i

It is convenient to use this in a for loop since the for loop will call iter() on the object, however, the object itself is not an iterator, so you cannot do this:

c = C()
print(next(c))

Which is inconvenient. To get around this inconvenience I have come up with the following class:

class C:
    def __init__(self):
        self.next = self.__iter__().__next__
    def __iter__(self):
        for i in range(4):
            yield i
            self.state = i
    def __next__(self):
        return self.next()

Usage example:

c = C()
while 1:
    try:
        num = next(c)
        print(num)
        if num == 2:
            print("state:", c.state)
    except Exception:
        break

Is this the best way to design the class? I haven't seen this technique used anywhere else so I'm wondering why everyone else isn't using it, since the C objects can be used both as iterators and as iterables.


texts:
How can I improve the following code?

private const string OAuthTokenUri = "oauth2/token";

private static string GetOAuthTokenUri(string uriAddress)
{
   var uri = new Uri(uriAddress);
   var baseUri = uri.GetLeftPart(UriPartial.Authority);
   var s = new Uri(new Uri(baseUri), OAuthTokenUri);
   return s.ToString();
}

I call GetOAuthTokenUri() like:

var oauthTokenUri = GetOAuthTokenUri("http://www.example.com/mypage/default.aspx");

As a result I'm getting

http://www.example.com/oauth2/token

Please help to improve GetOAuthTokenUri


texts: Compare files, returning first differing line

texts:
Exercise 7-6 from the K&R book.
Compares 2 files, printing the line number and content with the first dissimilarity.
What am I doing that could be improved?

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

#define MAXLINE 100

/* compare: compare files, printing first differing line */
int main(int argc, char *argv[])
{
    FILE *fp1, *fp2;
    char line1[MAXLINE], line2[MAXLINE];
    int i;
    char *prog = argv[0];

    /*require 2 files to comp*/
    if (argc != 3)
    {
        fprintf(stderr, "Incorrrect usage: got %d arguments, expected 3", argc);
        exit(1);
    }
    /*attempt to open files*/
    if (!( (fp1 = fopen(*++argv, "r")) && (fp2 = fopen(*++argv, "r")) ))
    {
        fprintf(stderr, "%s: can't open %s\n", prog, argv[1] || argv[2]);
        exit(2);
    }
    /*read line from each file*/
    for (i = 0; fgets(line1, MAXLINE, fp1) && fgets(line2, MAXLINE, fp2); i++)
    {
        if (strcmp(line1, line2))
        {
            /* print line # and line that differed */
            fprintf(stdout, "Line %d\n%s: %s\n%s: %s", i, argv[1], line1, argv[2], line2);
            break;
        }
    }
}


texts:
I solved the following problem on Hackerrank.

The challenge is to:

  Parse HTML input and display the tags and attributes in lexicographically ascending order.

This is the input format:

2 //number of test cases/ lines of html

Example Link

More Link Examples...

This is the output format:

tag-1:attribute-1,attribute-2,attribute-3....
tag-2:attribute-1,attribute-2,attribute-3....
tag-3:attribute-1,attribute-2,attribute-3....
...
tag-n:attribute-1,attribute-2,attribute-3....

Example solution:

a:href
div:class
p:

I am trying to get better at writing meaningful code for my solutions. Any comments/suggestions?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

private static StringBuilder htmlBuilder = new StringBuilder("");
private static Pattern rgxForTagAtEnd = Pattern.compile("(<[a-z0-9]+)$");
private static Pattern rgxForTagAtStart = Pattern.compile("^[a-z0-9]+");
private static Pattern rgxToExtractTags = Pattern.compile("(<[a-z]+[^>]*>)");
private static Pattern rgxToExtractTagName = Pattern.compile("(?:<)[a-z0-9]+");
private static Pattern rgxToExtractAttribute = Pattern.compile("[a-z]+(?:=[\"\'])");

public static boolean checkForBeginningOfTag(){
    Matcher beginningOfTag = rgxForTagAtEnd.matcher(htmlBuilder.toString());
    Boolean B = beginningOfTag.find();
    return B;
}

public static boolean doesTagEndInTheSameLine(String remainingHtml){
    Matcher endingOfTag = rgxForTagAtStart.matcher(remainingHtml);
    Boolean B = endingOfTag.find();
    return B;
}

public static void printTagsAndAttributes(){
    Matcher M = rgxToExtractTags.matcher(htmlBuilder.toString());
    Map<String,TreeSet<String>> tagsAndAttributes = new TreeMap<String,TreeSet<String>>();
    while(M.find()){
        String tag = M.group();
        Matcher tagName = rgxToExtractTagName.matcher(tag);
        Matcher attrName = rgxToExtractAttribute.matcher(tag);
        TreeSet<String> attributes = new TreeSet<String>();
        while(attrName.find()){
            attributes.add(attrName.group(0));
        }
        while(tagName.find()){
            String nameOfTag = tagName.group(0);
            if(tagsAndAttributes.containsKey(nameOfTag)){
                TreeSet<String> tmpSet = new TreeSet<String>(tagsAndAttributes.get(nameOfTag));
                tmpSet.addAll(attributes);
                tagsAndAttributes.put(nameOfTag,tmpSet);
            }else{
                tagsAndAttributes.put(tagName.group(),attributes);
            }
        }
    }

    for(String tag: tagsAndAttributes.keySet()){
        String result = "";
        result = result + tag.substring(1,tag.length()) + ":";
        for(String attribute: tagsAndAttributes.get(tag)){
            result+=attribute.substring(0,attribute.length()-2)+",";
        }
        if(result.charAt(result.length()-1) == ','){
            System.out.print(result.substring(0,result.length()-1));
        }else{
            System.out.print(result);
        }
        System.out.println();
    }
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int T = scanner.nextInt();
    scanner.nextLine();
    for(int i=0;i<T;i++){
        if(scanner.hasNextLine()){
            String nextLine = scanner.nextLine();
            if(checkForBeginningOfTag()){
                if(!doesTagEndInTheSameLine(nextLine)){
                    htmlBuilder.append(" ");
                }
            }
            htmlBuilder.append(nextLine);
        }
    }

    printTagsAndAttributes();
}
}


texts:
I'm working on chat client for mobile devices, and I need to get new messages from server as fast, as possible and, if it possible, keep battery alive.

I've created such class, that listens for server on it's own thread. Here is run method of Thread:

@Override
public void run(){
    try{
        //actually these lines defined in constructor
        String address="127.0.0.1";
        int port=46969;
        int reconnectInterval=15000;
        int interval=1000;
        Socket socket;
        //--- constructor's end

        SocketAddress addr=new InetSocketAddress(address, port);
        InputStream is=null;
        OutputStream os=null;
        ByteBuffer buf=ByteBuffer.allocate(2048);

        int beat=0;
        while(!interrupted()){
            //if socket not created - create it
            //if socket not connected - connect it
            if(socket==null || !socket.isConnected()){
                socket=new Socket();
                while(!socket.isConnected()){
                    try{
                        socket.connect(addr,reconnectInterval);
                    }catch(IOException e){
                        Log.d("AppLog", "Can't connect to socket. Reconnecting...");
                        socket=new Socket(); //recreate socket (if connection failed)
                        sleep(reconnectInterval);
                    }
                    continue;
                }
                try{
                    is=socket.getInputStream(); //open socket streams
                    os=socket.getOutputStream();
                }catch(IOException e){
                    Log.d("AppLog","Can't open socket streams - IOException");
                    interrupt();
                    break;
                }
                Log.d("AppLog", "Socket connected");
            }

            while(socket.isConnected()){
                sleep(interval);

                //send heart beats to socket to check connection
                beat++;
                if(beat>30)
                    try{
                        os.write(1);
                    }catch(IOException e){
                        Log.d("AppLog", "Can't send heartbeat");
                        socket=null;
                        break;
                    }finally{
                        beat=0;
                    }

                //read from socket
                try{
                    if(is.available()>0 && buf.remaining()>0){
                        while(is.available()>0 && buf.remaining()>0)
                            buf.put((byte) is.read());
                    }else if(buf.position()>0){
                        get(extractBytes(buf));
                        buf.clear();
                    }else buf.clear();
                }catch(IOException e){
                    Log.d("AppLog", "Can't read from socket - IOException");
                }
            }
        }
    }catch(InterruptedException e){
        Log.d("AppLog", "Interrupted exception has occured");
    }
}

Questions:

1) Would sleep method save resources (and battery)?

2) Is it efficient way, to read from socket and keep connection alive?


texts: Triggering based on words or phrases entered in a text box

texts:
I am working on a simple loop that when a user enters text into a textbox if certain words or phrases are entered, xyz is triggered. I have my code working as needed but am looking for way to improve / optimize it.

$("#input_test").on("keyup",function(){
    var common = false;

    var inputVal = $(this).val().toLowerCase().replace(/[^a-zA-Z ]/g, "");

    var triggerWords = ['hello there','world', 'hello world', 'how do I turn this on', 'general kenobi'];

        var common = triggerWords.some(function(v){
           return inputVal.indexOf(v) !== -1;
        });

        if(common){
            $('#showme').show(300);
        }else{
            $('#showme').hide(300);
        }

});

Working JSFiddle


texts:
I am new to threading and I am a junior developer, so I guess there are many mistakes. My scenario is this:

look into the database
if there are data which should be sent

add the data to the queue

if queue is not empty

send the next message and remove it from the queue
sleep 10 seconds

if a message from another thread arrived

stop waiting and go to next message in queue

if no message from another thread arrived

go back to the first step, but do this only 2 times
if a message still hasn't arrived from another thread

pass to the next message until queue is empty

return to the first step

I am trying to do this like this:

private Thread ReceiveThread;
private Thread SendThread;
internal static Thread ServiceThread;

These 3 threads:

ReceiveThread = new Thread(ReceiveTask);
ReceiveThread.Start();
ServiceThread = new Thread(SerAutoThread.SendServiceMsg);
ServiceThread.Start();
SendThread = new Thread(SendTask);
SendThread.Start();

class SerAutoThread
{
    internal static object[] NextService;
    public static readonly object _locker = new object();
    internal static Queue<object[]> Services;
    internal static int sendingTime = 0;
    private static DatabaseFirebird DB;
    internal static void SendServiceMsg()
    {
        DB = new DatabaseFirebird();
        DB.Open(ConnectionStr);
        Services = new Queue<object[]>();
        while (true)
        {
            if (Services.Count != 0)
            {
                SetNextSerAndSend();
            }
            else
            {
                CheckAndSetServices();
            }
        }
    }

    private static void SetNextSerAndSend()
    {
        NextService = Services.Dequeue();
        for (int j = 0; j < 4; j++)
        {
            if (sendingTime == TRANSMITTED)
            {
               //pass to next msg
               sendingTime = 0;
               j = NEXTMSG;
            }
            else if (sendingTime < 3)
            {
                sendingTime++;
                Byte[] data = SetNextPckage();
                DeviceManager.MessageSendQueue.PostItem(new SendMessage("UDPCmd",
                NextService[(int)NextMsg.DeviceId].ToString(),
                data, data.Length));
                MyDebug.WriteLine("Sended...");
                lock (_locker)
                {
                    Monitor.Wait(_locker, TimeSpan.FromSeconds(10));
                }
            }
            else
            {
                // pass to next msg
                j = NEXTMSG;
            }
        }
    }
}

private void ReceiveTask()
{
    ReceiveMessage receiveMsg;
    while (true)
    {
        receiveMsg = Com.MessageReceiveQueue.GetItem(-1);
        SerAutoThread.sendingTime = SerAutoThread.TRANSMITTED;
        lock (SerAutoThread._locker)
        {
            Monitor.Pulse(SerAutoThread._locker);
        }
    }
}

 private void SendTask()
 {
     SendMessage msg;
     while (true)
     {
         msg = MessageSendQueue.GetItem(-1);
         String rtrn = PushData(msg);
     }
 }

Is this thread-safe or not?  I'm not sure if something is wrong with the design or I'm doing something wrong elsewhere.

And this is not my entire code (for understanding).  When I actually run the app, this works fine.  Yesterday just ones my Database management system (Firebird) locked.  Then I stopped my app, stopped Firebird server then started again and ran my app again.  Now it is ok again. I am not using threads with deep understanding. So I am worried about thread safety.

Is it possible for the thread-locked Firebird?


texts: An integer is even subset of another integer

texts:
An integer m is defined to be an even subset of another integer n if every even factor of m is also a factor of n.

18 is an even subset of 12 because the even factors of 18 are 2 and 6 and these are both factors of 12.
But 18 is not an even subset of 32 because 6 is not a factor of 32.

I wrote the following code to check for even subsets.

public class EvenSubset {
public static void main(String args[]) {
    System.out.println("The result is: " + isEvenSubset(18, 32));
}
public static boolean isEvenSubset(int m, int n) {
    boolean status = false;
    int firstNumber = 0;
    int secondNumber = 0;
    for(int i = 2; i < m ; i++) {
        if(( m % i == 0) && (i % 2 == 0)) {
            firstNumber = i;
            for(int j  = 2;  j < n ; j++) {
                if( (n % j == 0) && (j % 2 == 0)){
                    secondNumber = j;
                    if(firstNumber == secondNumber) {
                        status = true;
                        break;
                    } else {
                        status = false;

                    }
                }

        }
       if(!status){
           status = false;
       }

    }

}
    return status;
}
 }