texts: Notify user of credential failure and make another attempt

texts:
The below code works because of the do operator on line 24. Is there a more functional way to get the test to pass, or would you consider this an appropriate use of do?

import RxSwift

struct Token: Equatable {
    let rawValue: String
    static func ==(lhs: Token, rhs: Token) -> Bool {
        return lhs.rawValue == rhs.rawValue
    }
}

protocol Login {
    func getCredentials() -> Observable<(email: String, password: String)>
    func presentAuthFailure(_ error: Observable<Error>)
}

protocol Network {
    func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token>
}

// MARK: - function Under Test
func checkCredentials(login: Login, network: Network) -> Observable<Token> {
    let credentials = login.getCredentials()
    let token = credentials.flatMap { network.getAuthToken(credentials: $0) }
        .do(onError: { login.presentAuthFailure(Observable.just($0)) }) // can this be done in some other way?
    return token.retry()
}

// MARK: - Test harness
class MockLogin: Login {
    func getCredentials() -> Observable<(email: String, password: String)> {
        assert(_credentials == nil)
        _credentials = PublishSubject()
        return _credentials!
    }

    func presentAuthFailure(_ error: Observable<Error>) {
        _ = error.subscribe(onNext: { [unowned self] error in
            assert(self._error == nil)
            self._error = error
        })
    }

    var _credentials: PublishSubject<(email: String, password: String)>?
    var _error: Error?
}

class MockNetwork: Network {
    func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token> {
        assert(_token == nil)
        _token = PublishSubject()
        return _token!
    }

    var _token: PublishSubject<Token>?
}

func testTwoBadAttempts(login: MockLogin, network: MockNetwork) {
    checkCredentials(login: login, network: network).subscribe()

    assert(login._credentials != nil)

    let credentials = (email: "foo", password: "bar")
    login._credentials?.onNext(credentials)

    assert(network._token != nil)

    let error = NSError(domain: "testing", code: -1, userInfo: nil)
    network._token?.onError(error)

    assert(login._error != nil)

    network._token = nil
    login._error = nil

    login._credentials?.onNext(credentials)

    network._token?.onError(error)

    assert(login._error != nil)
}

let login = MockLogin()
let network = MockNetwork()
testTwoBadAttempts(login: login, network: network)


texts: Making prime (sieve) code faster and able to run on big numbers

texts:
For an input triple (a, b, c), the task is to count the number of integers in the inclusive range [a, b] which have c distinct prime factors. This entails factoring each of the numbers in the range [a, b] and establishing how many distinct prime factors each has.

I need faster code so my program runs faster and works on big numbers.

#include<bits/stdc++.h>
using namespace std;

bool f[100000001];
void siv()
{
    f[1] = 1;
    for (long long i = 2; i * i <= 100000001; ++i)
    {
        if (!f[i])
            for (long long j = i * i; j <= 100000001; j += i)
                f[j] = 1;
    }
}

int main()
{
    siv();
    vector<long long>V;
    long long a,b,c;
    int t,counter=1;
    cin >> t;
    while (t--)
    {
        int count=0;
        cin >> a >> b >> c;

        for (long long i=a; i <= b; ++i)
        {
            V.clear();
            for(long long q = 1; q <= i; ++q)
            {
                if(i % q == 0)
                {
                    if (!f[q])
                        V.push_back(q);
                }
            }
            if (V[0] == 1)
                V.erase(V.begin());
            if (V.size() == c)
            {
                ++count;
            }
        }
        cout << "Case #" << counter++ << ": " << count << endl;
    }
    return 0;
}

Example input for what I need:

5 15 2
2 10 1
24 42 3

The output should be like this:

5
7
2

\$2 \le a \le b \le 10^7\$

\$1 \le c \le 10^9\$

The output shows how many integers in the inclusive range [a, b] have a prime of exactly c.

In the first test case, the numbers in the inclusive range [5, 15] with c= 2 are 6, 10, 12, 14, and 15. All other numbers in this range have c=1.


texts: Convert hours and minutes to total minutes

texts:
This is a simple exercise in C designed to work on IO. The purpose of the program is simple: convert a number of hours and minutes to a total number of minutes.

#include <stdio.h>

const unsigned short MinutesPerHour = 60;

int main(int argc, char* argv[])
{
    int hours, minutes, total;

    if(argc == 1)
    {
        puts("Enter the number of hours:");
        scanf("%d", &hours);
        puts("Enter the number of minutes:");
        scanf("%d", &minutes);
    }
    else if(argc == 2)
    {
        hours = atoi(argv[1]);
        minutes = 0;
    }
    else if(argc == 3)
    {
        hours = atoi(argv[1]);
        minutes = atoi(argv[2]);
    }
    else if(argc != 3)
    {
        printf("Usage: %s (int hours) (int minutes)\n", argv[0]);

        return -1;
    }

    total = (hours * MinutesPerHour) + minutes;
    printf("%d hourss and %d minutes is %d minutes\n", hours, minutes, total);

    return 0;
}

Is there specifically any way I could improve the argument/input parsing blocks? Would it be more consistent to ask the user for minutes if they supply an hours command line argument? Should I offer the variety of options at all, or should I stick to command line arguments only or "dynamic" input only?

Bonus: Are there any meaningful names that could be assigned to the 1, 2, and 3 in the parsing blocks that would make the code more readable? Magic numbers are bad, but since it is checking the number of arguments, I can't think of anything other than if (argc == OneArgument) else if (argc == TwoArguments)... which seems silly.


texts:
My thoughts are to create a method that contains all of the variables declared. Is it better to say initialized?

I would like it to be more efficient but still as clear as possible for future maintenance of the code. Any suggestions for the main bulk of information, such as methods?

if (incomeDec <= 300)
{
    taxRateDec1 = 0.15m;
    taxDec = incomeDec * taxRateDec1;
}
else if (incomeDec <= 450)
{
    tierAmtInt = 300;
    taxRateDec1 = 0.15m;
    taxRateDec2 = 0.2m;

    tempValueDec = tierAmtInt * taxRateDec1;
    taxDec = (incomeDec - tierAmtInt) * taxRateDec2;
    taxDec = taxDec + tempValueDec;
}
else
{
    tierAmtInt = 300;
    tierAmtInt2 = 150;
    taxRateDec1 = 0.15m;
    taxRateDec2 = 0.2m;
    taxRateDec3 = 0.25m;

    tempValueDec = tierAmtInt * taxRateDec1;
    tempValueDec = tempValueDec + tierAmtInt2 * taxRateDec2;
    taxDec = (incomeDec - tempValueDec) * taxRateDec3;
    taxDec = taxDec + tierAmtInt;
}

incomeDec = incomeDec - taxDec;


texts:
I am currently working on a little binary patcher. My current code works fine but I do want my code to be optimized (fast) and as clean as possible. Could you all please help me review this?

IDE: Delphi 7 and XE7

const
  OriginalByte: array [0 .. 55] of Byte = ($64, $69, $6E, $67, $20, $6D, $65,
    $20, $68, $69, $73, $00, $00, $00, $00, $27, $00, $00, $28, $00, $00, $00,
    $21, $00, $00, $00, $63, $6F, $6D, $70, $75, $74, $65, $72, $2E, $00, $00,
    $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $27, $00, $00, $28,
    $00, $00, $00, $00);

  BytetoWrite: array [0 .. 55] of Byte = ($63, $68, $6F, $67, $20, $6D, $65,
    $20, $68, $69, $73, $00, $00, $00, $00, $27, $00, $00, $28, $00, $00, $00,
    $21, $00, $00, $00, $63, $6F, $6D, $70, $75, $74, $65, $72, $2E, $00, $00,
    $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $27, $00, $00, $28,
    $00, $00, $00, $06);

function CompareByteArrays(FirstArray, SecondArray: array of Byte): Boolean;

var
  Counter: Integer;
begin

  Result := True;
  if Length(FirstArray) <> Length(SecondArray) then
  begin
    Result := False;
    Exit;
  end;

  for Counter := Low(FirstArray) to High(FirstArray) do

  begin
    if (FirstArray[Counter]) <> (SecondArray[Counter]) then
    begin
      Result := False;
      Exit;
    end

  end;

end;

procedure DoMyPatch();
var

  i: Integer;
  FileName: string;
  input: TFileStream;

  FileByteArray, ExtractedByteArray: array of Byte;

begin
  FileName := 'Cute1.res';

  try
    input := TFileStream.Create(FileName, fmOpenReadWrite);
  except
    on E: Exception do
    begin
      ShowMessage(E.Message);
      Exit;
    end
  end;

  input.Position := 0;
  SetLength(FileByteArray, input.size);
  input.Read(FileByteArray[0], Length(FileByteArray));
  for i := Low(FileByteArray) to High(FileByteArray) do
  begin

    ExtractedByteArray := Copy(FileByteArray, i, Length(OriginalByte));

    if CompareByteArrays(ExtractedByteArray, OriginalByte) = True then
    begin
      // Begin Patch
      input.Free;
      try
        Win32Check(CopyFile(PChar(FileName), PChar(ChangeFileExt(FileName,
          '.BAK')), False));
      except
        on E: Exception do
        begin
          ShowMessage(E.Message);
          Exit;
        end
      end;

      try
        input := TFileStream.Create(FileName, fmOpenReadWrite);
      except
        on E: Exception do
        begin
          ShowMessage(E.Message);
          Exit;
        end
      end;

      input.Seek(i, SoFromBeginning);

      input.Write(BytetoWrite[0], Length(BytetoWrite));

      ShowMessage('Patch Success');
      input.Free;
      Exit;
    end;
  end;
  ShowMessage('Patch Fail');

  input.Free;

end;


texts: Simple PHP image upload with error handling

texts:
I wrote this method to upload a floor plan image:

function upload_image($path, $file) {
    $errors = [];
    $ext = pathinfo($file["name"])['extension'];

    //randomly generate filename to avoid conflicts
    $filename = uniqid().'.'.$ext;

    if ($file["size"] > 2000000) {
        $errors[] = "The image cannot be greater than 2MB";
    }

    if (!in_array($ext, ["jpg", "jpeg", "png"])) {
        $errors[] = "The image can only be of .jpg, .jpeg or .png format";
    }

    if (empty($errors)) {
        move_uploaded_file($file["tmp_name"], $path.$filename);
    }

    return array(
        "name" => $filename,
        "errors" => $errors
    );
}

Implementation:

if (isset($_POST['create'])) {
    $image = upload_image(IMG_PATH."/floorplans/", $_FILES['floorplan']);
    $floorplan = new FloorPlan($_POST['floorplan']);

    if (empty($image['errors'])) {
        $floorplan->image = $image['name'];
    } else {
        foreach ($image['errors'] as $error) {
            $floorplan->errors[] = $error;
        }
    }
}

I'm very happy with it and everything seems to work fine, but I am just wondering if there is a better/more efficient way to do this.


texts: Remove known Excel passwords with PowerShell

texts:
I have this PowerShell code that loops through Excel files in a specified directory; references a list of known passwords to find the correct one; and then opens, decrypts, and saves that file to a new directory. This currently processes ~40 workbooks in roughly 5 minutes, which is still longer than I'd like (but better than the initial 40 minute runtime).

Note that I previously posted under the same title here, but now I am looking for a review after solving a rather obvious error.

# Get Current EXCEL Process ID's so they are not affected but the scripts cleanup
# SilentlyContinue in case there are no active Excels
$currentExcelProcessIDs = (Get-Process excel -ErrorAction SilentlyContinue).Id

$a = Get-Date

$ErrorActionPreference = "SilentlyContinue"

CLS

# Paths
$encrypted_path = "C:\PoShTest\Encrypted"
$decrypted_Path = "C:\PoShTest\Decrypted\"
$processed_Path = "C:\PoShTest\Processed\"
$password_Path  = "C:\PoShTest\Passwords\Passwords.txt"

# Load Password Cache
$arrPasswords = Get-Content -Path $password_Path

# Load File List
$arrFiles = Get-ChildItem $encrypted_path

# Create counter to display progress
[int] $count = ($arrfiles.count -1)

# New Excel Object
$ExcelObj = $null
$ExcelObj = New-Object -ComObject Excel.Application
$ExcelObj.Visible = $false

# Loop through each file
$arrFiles| % {
    $file  = get-item -path $_.fullname
    # Display current file
    write-host "`n Processing" $file.name -f "DarkYellow"
    write-host "`n Items remaining: " $count `n

    # Excel xlsx
    if ($file.Extension -like "*.xls*") {

    # Loop through password cache
        $arrPasswords | % {
            $passwd = $_

            # Attempt to open file
            $Workbook = $ExcelObj.Workbooks.Open($file.fullname,1,$false,5,$passwd)
            $Workbook.Activate()

            # if password is correct save decrypted file to $decrypted_Path
                if ($Workbook.Worksheets.count -ne 0 )

                {
                    $Workbook.Password=$null
                    $savePath = $decrypted_Path+$file.Name
                    write-host "Decrypted: " $file.Name -f "DarkGreen"
                    $Workbook.SaveAs($savePath)

             # Added to keep Excel process memory utilization in check
                    $ExcelObj.Workbooks.close()

             # Move original file to $processed_Path
                    move-item $file.fullname -Destination $processed_Path -Force

                }
                else {
            # Close Document
                    $ExcelObj.Workbooks.Close()
                }
        }

    }

$count--
# Next File
}
# Close Document and Application
    $ExcelObj.Workbooks.close()
    $ExcelObj.Application.Quit()

Write-host "`nProcessing Complete!" -f "Green"
Write-host "`nTime Started   : " $a.ToShortTimeString()
Write-host "Time Completed : " $(Get-Date).ToShortTimeString()
Write-host "`nTotal Duration : "
NEW-TIMESPAN –Start $a –End $(Get-Date)

# Remove any stale Excel processes created by this scripts execution
Get-Process excel -ErrorAction SilentlyContinue | Where-Object{$currentExcelProcessIDs -notcontains $_.id} | Stop-Process


texts:
My code is very very slow. Could you give me hints on how I can make it much faster?

for (stdext::hash_map<unsigned __int32, CVertex*>::iterator it1 = graph.begin(); it1 != graph.end(); it1++)
{
    for (std::vector<CVertex*>::iterator it2 = it1->second->getNeighbors().begin(); it2 != it1->second->getNeighbors().end(); it2++)
    {
        if ((*it2)->isEqualTo(it1->second)) continue;
        for (std::vector<CVertex*>::iterator it3 = (*it2)->getNeighbors().begin(); it3 != (*it2)->getNeighbors().end(); it3++)
        {
            if ((*it3)->isEqualTo(*it2) || (*it3)->isEqualTo(it1->second)) continue;
            for (std::vector<CVertex*>::iterator it4 = (*it3)->getNeighbors().begin(); it4 != (*it3)->getNeighbors().end(); it4++)
            {
                if ((*it4)->isEqualTo(*it3) || (*it4)->isEqualTo(*it2) || (*it4)->isEqualTo(it1->second)) continue;
                for (std::vector<CVertex*>::iterator it5 = (*it4)->getNeighbors().begin(); it5 != (*it4)->getNeighbors().end(); it5++)
                {
                     if ((*it5)->isEqualTo(*it4) || (*it5)->isEqualTo(*it3) || (*it5)->isEqualTo(*it2) || (*it5)->isEqualTo(it1->second)) continue;
                     for (std::vector<CVertex*>::iterator it6 = (*it5)->getNeighbors().begin(); it6 != (*it5)->getNeighbors().end(); it6++)
                     {
                         if (it1->second->isEqualTo(*it6))
                         {
                             unsigned __int32 *circle = new unsigned __int32[5];

                             circle[0] = it1->second->getWord();
                             circle[1] = (*it2)->getWord();
                             circle[2] = (*it3)->getWord();
                             circle[3] = (*it4)->getWord();
                             circle[4] = (*it5)->getWord();

                             m_results.push_back(circle);
                         }
                     }
                }
            }
        }
    }
}

I think this question is not subjective because I've found many good things on the Internet yet:

I use only vectors which is much faster (the not reserved too) because of the cache.
You cannot see here, but I use only inline function in vertex class.
I tried to reduce the numbers into uint 32 bit.

But I still miss good trick because its time is lifetime. For example, do you think I can make better compiler settings?

Or it's also very useful if you say I cannot make it much faster because in that case I don't waste more energy into finding a better solution.


texts: Increase performance of string matching function

texts:
I've benchmarked my program, and have discovered that the single function taking the most time is the one that does the following.

Takes string that is a delimited list, and splits it into individual strings (Within the program, the individual strings are called statements)
Looks at the individual strings, compares them to a known set of strings (Called a statement library. It contains additional information relating to these strings that I need)

I cannot change the input data, since it comes from several different systems, and the closest thing we can get to something in common is a delimited list of strings.

So, enough background, the first implementation of this was a naive set of LINQ statements:

var statements = textStatements
    .Select(ts => Library.Statements
        .FirstOrDefault(s => ts.Equals(s.FullText, StringComparison.OrdinalIgnoreCase)))
    .Where(s => s != null).ToList();

So, statements is a list of Statement objects, which contain the additional data I need. I figure this is worst case is about O(n^2)-ish.

Once this function was identified as a bottleneck, I made a first attempt at optimizing this function. First, I ensured the split list of statements, and the known list of statements were both sorted, and then implemented this:

var textStatements = SplitStatements(data).ToList();
var statementCount = textStatements.Count;
var libraryCount = Library.Statements.Count;
var libraryOffset = 0;
var foundStatements = new Dictionary<string, Statement>();
for (var i = 0; i < statementCount; i++)
{
    var thisStatement = textStatements[i];
    for (var j = libraryOffset; j < libraryCount; j++)
    {
        var currentLibraryStatement = Library.Statements[j];
        if (string.Equals(thisStatement, currentLibraryStatement.FullText, StringComparison.OrdinalIgnoreCase))
        {
            foundStatements[(currentLibraryStatement.Category.Name + currentLibraryStatement.Code).ToUpperInvariant()] = currentLibraryStatement;
            libraryOffset = j + 1;
            break;
        }
        if (string.Compare(thisStatement, currentLibraryStatement.FullText, StringComparison.OrdinalIgnoreCase) < 0)
        {
            libraryOffset = j;
            break;
        }
    }
}

Essentially, I loop through the statements I need to look up, and start working through the library of statements, remembering where the last statement was found, so I can exclude all statements in the library that are before the last one found.

This did result in a speedup, but not as much as I would hope, hence me throwing this out here to see if I can get another perspective.


texts: Checking whether two lists contain the same elements

texts:
I have two lists of numbers:

$$\{i_1, i_2, i_3,i_4\}$$ and $$\{j_1,j_2,j_3,j_4\}$$

The problem I want to solve is: Inside a loop, if the following two conditions are satisfied, then it will do something I want, otherwise it just cycle the loop. The conditions are:

Both lists contain four different numbers;
If ignoring the ordering, in other words, we view these two lists as two set, then they are the same.

I want to find a very fast way to get the answer to the problem. I have very slow Fortran code as follows:

if (i2==i1) cycle
if (i3==i1) cycle
if (i3==i2) cycle
if (i4==i1) cycle
if (i4==i2) cycle
if (i4==i3) cycle

if (j2==j1) cycle
if (j3==j1) cycle
if (j3==j2) cycle
if (j4==j1) cycle
if (j4==j2) cycle
if (j4==j3) cycle
q1=0
q2=0
q3=0
q4=0
if (i1==j1)q1=1
if (i1==j2)q1=2
if (i1==j3)q1=3
if (i1==j4)q1=4
if (i2==j1)q2=1
if (i2==j2)q2=2
if (i2==j3)q2=3
if (i2==j4)q2=4
if (i3==j1)q3=1
if (i3==j2)q3=2
if (i3==j3)q3=3
if (i3==j4)q3=4
if (i4==j1)q4=1
if (i4==j2)q4=2
if (i4==j3)q4=3
if (i4==j4)q4=4

if (q1*q2*q3*q4==24)then
 Something I want to do
endif

I think to find a good program, the following should also be considered as well as cutting down the number of instructions:

The probability to have four different numbers in both lists are about
1/10;
The probability to have for these two lists containing two same set
of numbers are very small, about 10^(-11);
I really have to do many loops.

Could someone help me out? I think a good idea can really boost the code.


texts: Determine final player in a counting game

texts:
I made a function in which 17 players are counting to number N. Function as a parameter takes a number N and returns which player is going to say N. If current number is divisible by 9 the counting order is reversed, and if current number is divisible by 17 the next player is skipped. I made this code, but is a little bit too big for me, so I wonder if there is another (less code) way I could solve it.
func playertold(number: Int)  {

var currentNumber:Int = 1
var currentPlayer:Int = 1
var reversedOrder:Bool = false

while currentNumber != number {

    if currentNumber % 9 == 0 {

        reversedOrder = !reversedOrder

    }

    if  currentNumber % 17 == 0 {
        if reversedOrder {
            if currentPlayer == 2 {
                currentPlayer = 17
            } else if currentPlayer == 1 {
                currentPlayer = 16
            } else {
                currentPlayer -= 2
            }
        } else{
            if currentPlayer == 16 {
                currentPlayer = 1
            }else if currentPlayer == 17 {
                currentPlayer = 2
            }else {
                currentPlayer += 2
            }
        }
    } else {

    if reversedOrder {
        currentPlayer -= 1

        if currentPlayer < 1 {
            currentPlayer = 17
        }
    } else {
        currentPlayer += 1

        if currentPlayer > 17 {
            currentPlayer = 1
        }
    }
    }

    currentNumber += 1

}

print("Player who will say number \(number) is \(currentPlayer)")
}


texts: Build List from unshared items from two other Lists

texts:
Ultimately, my goal is to take two lists and then generate a third consisting of items that the first two lists do NOT share. I am able to get the results I want using two foreach loops, but I am hoping to learn about some magical List tool that will do it more cleanly.

public List<string> removeMatchingItems(List<string> List1, List<string> List2)
{
    List<string> desiredList = new List<string>();

    foreach (string value in List1)
    {
        if (!List2.Contains(value))
        { desiredList.Add(value); }
    }
    foreach (string value in List2)
    {
        if (!List1.Contains(value))
        { desiredList.Add(value); }
    }
    return desiredList;
}


texts:
I'd like to receive a CR for the following command-line program options' initializing using boost::program_options. I'd like to know if there is a better way of doing this using boost::program_options or using another available library/code:

#include <iostream>
#include <boost/program_options.hpp>

using namespace std;
namespace po = boost::program_options;

int main(int ac, char* av[]) {
    /// Command line options initialize
    po::options_description visible_desc("Usage: program [options] [path/]logger_filename");
    po::options_description full_desc;
    po::positional_options_description pd;
    bool verbose, anomaly_detection, analyze_activity;
    string normal_login_word;
    string log_file_path;
    string week_start_day;

    auto generic_group = po::options_description("Generic options");
    generic_group.add_options()
            ("help,h", "produce help message")
            ("verbose", po::value<bool>(&verbose)->default_value(false), "Show detailed times of login.")
            ;

    auto calender_group = po::options_description("Calender options");
    calender_group.add_options()
            ("week-start-day,d", po::value<string>(&week_start_day)->default_value("Monday"), "Week starting day ('--week-start-day help' for a list).")
            ;

    auto log_group = po::options_description("Logger options");
    log_group.add_options()
            ;

    auto hidden_options_group = po::options_description("Logger options");
    hidden_options_group.add_options()
            ("log-path,l", po::value<string>(&log_file_path)->default_value("/home/sherlock/message_from_computer"), "Path to login/logout logger.")
            ;

    auto anomalies_group = po::options_description("Mode options");
    anomalies_group.add_options()
            ("analyze-log", po::value<bool>(&analyze_activity)->default_value(true), "Analyze activity - show activity times and summarise activity.")
            ("anomaly-detection", po::value<bool>(&anomaly_detection)->default_value(false), "Check for anomalies in logger.")
            ("normal-login-word", po::value<string>(&normal_login_word)->default_value("login"), "For anomaly detector- word that should symbol a login line in login/logout logger (after '+' sign).")
             ;

    pd.add("log-path", -1);

    visible_desc.add(generic_group).add(calender_group).add(log_group).add(anomalies_group);
    full_desc.add(generic_group).add(calender_group).add(log_group).add(anomalies_group).add(hidden_options_group);

    /// Command line options applying
    po::variables_map vm;
    po::store(
            po::command_line_parser(ac, av)
            .options(full_desc)
            .positional(pd)
            .run(), vm);
    po::notify(vm);

    /*
     ... Analyze options ...
    */
    return 0;
}

Update: after @pacmaninbw and @ALX23z CRs I created a new updated post: program options from command line initialize [v2 - after CR]


texts: Project Euler Problem 6: Sum square difference

texts:
Continuing to work my way through some of of Project Euler. Problem 6 solved by my code below. Is it better to use sumOfTheSquares += i*i or utilize Math.Pow()?

  The sum of the squares of the first ten natural numbers is,
  \$1^2 + 2^2 + ... + 10^2 = 385\$

  The square of the sum of the first ten natural numbers is,
  \$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$

  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(SumSquareDifference(100));
        Console.ReadLine();
    }

    static int SumSquareDifference(int upperValue)
    {
        int sumOfTheSquares = 0;
        for (int i = 1; i <= upperValue; i++)
        {
            sumOfTheSquares += (int)Math.Pow(i,2); //Can't formulate this myself...
        }

        int squareOfTheSums =  (int)Math.Pow((upperValue + 1) * (upperValue / 2),2);

        return squareOfTheSums - sumOfTheSquares;
    }
}


texts: Generates a randomized locally-administered unicast MAC address

texts:
This is the first time I've attempted writing something in bash, and would appreciate any feedback or criticism to make it better.

#! /bin/bash
macArr=( 0 0 0 0 0 0 )
for ((i=0; i < ${#macArr[@]}; ++i))
do
    let "byte=$RANDOM%255"
    # the first byte must have the least significant bits set to "10"
    # in order to identify as a locally administered unicast MAC
    if [ $i -eq 0 ];then
        let "byte=(((byte>>1)|1)<<1)"
    fi
    prependZero=$([ $byte -lt 16 ] && echo 1 || echo 0)
    # convert byte from decimal int to hex string
    byte=$(printf "%x" "$byte")
    # uppercase any letters in the string
    macArr[$i]="${byte^^}"
    if [ $prependZero -eq 1 ];then
        macArr[$i]="0${macArr[$i]}"
    fi
done
printf "%s" "${macArr[@]}"


texts: Basic Rust HTTP request as a learning exercise

texts:
For work, we have to use Atlassian Jira, which is depressing. To make my life a bit easier, I decided to write a cli application to get ticket summaries, and I thought it would make a good first project in rust. The code below works, but I would be grateful for any tips/improvements. I'm a python programmer, so it's almost certainly not idiomatic rust...

extern crate reqwest;
extern crate tokio;
use serde_json;
use reqwest::header::{AUTHORIZATION,ACCEPT,CONTENT_TYPE,HeaderValue,HeaderMap};

const BASE_URL: &str = "https://subdomain.atlassian.net/rest/api/latest/issue";

fn parse_config() -> String {
    let config_file = std::fs::read_to_string("/home/username/.config/jiracli").expect("No config file found");
    String::from(config_file.trim())
}

async fn summarise(client: reqwest::Client, ticket_number:String) -> Result<String, Box<dyn std::error::Error>> {
    let compiled_url = format!("{}/{}", &BASE_URL, ticket_number);
    let json_response: serde_json::Value = client.get(&compiled_url).send().await?.json().await?;
    let ticket_fields = json_response["fields"].as_object().unwrap();
    let ticket_summary = ticket_fields.get("summary").unwrap().as_str().unwrap();
    let ticket_status = ticket_fields["status"].as_object().unwrap().get("name").unwrap().as_str().unwrap();
    let ticket_creator = ticket_fields["creator"].as_object().unwrap().get("displayName").unwrap().as_str().unwrap();
    let response=format!("Creator: {}\nStatus: {}\nSummary: {}", ticket_creator,ticket_status,ticket_summary);
    Ok(String::from(response))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let verb = std::env::args().nth(1).expect("No verb provided");
    let ticket_number = std::env::args().nth(2).expect("No ticket provided");
    let formatted_auth = format!("Basic {}", parse_config());
    let auth_header_value = HeaderValue::from_str(&formatted_auth).unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, auth_header_value);
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
    headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
    let client = reqwest::Client::builder()
        .default_headers(headers)
        .build()?;
    let result = match &verb[..] {
        "summary" => Ok(summarise(client, ticket_number).await),
        _ => Err("Not implemented")
    };
    println!("{}", result.unwrap()?);
    Ok(())
}


texts: Script to auto-generate Markdown tables of contents

texts:
I would greatly appreciate feedback on the enclosed script, which auto-generates a Markdown table of contents for Github-flavoured Markdown, with respect to:

Consistency with Ruby idiom & style
Any use of bad practices

#!/usr/bin/env ruby

def usage
  puts "Usage: #{$0} FILE.md"
  exit 1
end

class ToCWriter
  def initialize(source_file, top=2, max=4)
    @source_file = source_file
    @top = top
    @max = max
    @c = 1
    @level  = ""
    @header = ""
    @start  = ""
    write
  end

  def write
    puts "#### Table of contents\n\n"

    File.open(@source_file).each_line do |line|
      next unless line.match(/^#/)

      @level, @header = line.match(/^(#+) (.*)/).captures
      next if @header == "Table of contents"
      next if skip?

      ref = header_to_ref
      set_start

      puts "#{@start} [#{@header}](##{ref})"
    end
  end

 private

  def skip?
    len = @level.length
    len < @top || len > @max
  end

  def header_to_ref
    @header
      .gsub(/ /, "-")
      .gsub(/[\.\/,&\()<>-]+/, "-")
      .gsub(/-$/, "")
      .downcase
  end

  def set_start
    len = @level.length
    if len == @top
      @start = "#{@c}."
      @c += 1
    else
      bullet = len % 2 == 0 ? "*" : "-"
      @start = "    " * (len - 2) + bullet
    end
  end
end

usage unless ARGV.length == 1
source_file = ARGV[0]

ToCWriter.new(source_file)


texts: Update existing key value if present and then deserialize json to POCO efficiently

texts:
I have a json string ProcessValue in which I need to extract a particular key (client_id) value and then I need to encode that value using HttpUtility.HtmlEncode and put it back in the same JSON string. ProcessValue is one of the header name which has a json value in it.
Below is my code which does that but I am deserializing twice looks like. Is there any way to improve below code?
ProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A
if (!string.IsNullOrWhiteSpace(ProcessValue))
{
    dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(ProcessValue);
    if (jsonObject.client_id != null)
    {
        var value = jsonObject.client_id;
        jsonObject.client_id = HttpUtility.HtmlEncode(value);
        var modifiedJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
        ProcessValue = modifiedJsonString;
    }
    ProcCustomer = DeserializeJson<ProcCustomer>(ProcessValue);
}

private T DeserializeJson<T>(string str) where T : new()
{
    try
    {
        return JsonSerializer.Deserialize<T>(str);
    }
    catch (Exception e)
    {
        return new T();
    }
}

Here ProcessValue at LINE A is:
{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value6","client_id":"HÃ¤nzendes"}

I am extracting client_id value and then encoding it and after that putting it back to same json. And then I am deserializing this modified json value to ProcCustomer POCO. ProcCustomer is the POCO class which holds all the fields value. So I am deserializing and serializing to get my updated json string ProcessValue and then I deserialize this json to ProcCustomer POCO class.
There are places where we use ProcessValue json string directly as it is one of the header value and using ProcCustomer POCO fields as well so that is why I was doing above things. I wanted to see if there is anything I can do to optimize my above code where I don't have to deserialize and then serialize and then again deserialize to put it in POCO?
Also I am mixing Utf8Json library with Newton json library. I prefer to use Utf8 json library for both serialization and deserialization in my above code.


texts:
I was given a homework and I have 2 solutions: one that uses this and other one that doesn't.

I tested both solutions on jsPerf but sometimes it says the version with this is faster or sometimes the other one. So I think I cannot really rely on jsPerf. Anyway, should performance be always the top priority?

By the way, here is the problem statement:

  Write a function addg that adds from many invocations, until it sees an empty invocation.

  Something like:

  addg();                // undefined

  addg(2)();             // 2

  addg(2)(7)();          // 9

  addg(3)(0)();          // 3

  addg(1)(2)(4)(8)();    // 15

  addg(5)(4)(-2)();      // 7

Here are my 2 solutions:

version with this:

function add(a,b){
  return a+b;
}

function addg(val){
  var numbers = [];

  this.addToCollection = function(val){
    numbers.push(val);

    if(typeof val !== 'number'){  // in case of ()
      var sum = 0,
          l = numbers.length;

      numbers.forEach(function(num, i){
        if(i === l-1){
          return;
        } else {
          sum = add(sum, num);
        }
      });

//       console.log(numbers);

      if(numbers.length === 1 && numbers[0] === undefined){
        return undefined;
      } else {
        return sum;
      }

    } else {  // in case of (n)
      return this.addToCollection;  // return the function each time so you can apply it to other numbers in the chain
    }

  };

  return this.addToCollection(val);
}

console.log(addg());                // undefined
console.log(addg(2)());             // 2
console.log(addg(2)(7)());          // 9
console.log(addg(3)(0)());          // 7
console.log(addg(1)(2)(4)(8)());    // 15
console.log(addg(5)(4)(-2)());      // 7

version without this:

function add(a,b){
  return a+b;
}

function addg(val){
  var numbers = [];

  function addValues(val){
    numbers.push(val);

    if(typeof val !== 'number'){  // in case of ()

      var sum = 0,
          l = numbers.length;

      numbers.forEach(function(num, i){
        if(i === l-1){
          return;
        } else {
          sum = add(sum, num);
        }
      });

//       console.log(numbers);

      if(numbers.length === 1 && numbers[0] === undefined){
        return undefined;
      } else {
        return sum;
      }

    } else {  // in case of (n)
      return addValues; // return the function each time so you can apply it to other numbers in the chain
    }
  }

  return addValues(val);

}

console.log(addg());                // undefined
console.log(addg(2)());             // 2
console.log(addg(2)(7)());          // 9
console.log(addg(3)(0)());          // 7
console.log(addg(1)(2)(4)(8)());    // 15
console.log(addg(5)(4)(-2)());      // 7

I would like to know which version is better and why. If you have any suggestions for improving my code, please feel free to let me know.


texts: How can I simplify the following code that calculates standard deviation

texts:
Before I get started I have spent much time searching for the answer. It seems the most referenced way is here, http://www.developer.com/print.php/3794146. I am not quite understanding how to optimize. See below.

public void CalculateStdDev()
{
    arrayItemCount = 0; // integer
    average = 0; // double
    double itemsSum = 0;
    double[] values = new double[DS.Tables[0].Rows.Count];
    double[] deviations = new double[DS.Tables[0].Rows.Count];
    double[] squareDeviations = new double[DS.Tables[0].Rows.Count];
    double squareDeviationsSum = 0;
    double squareDeviationsAverage = 0;
    stdDeviation = 0; // double

    for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
    {
        if (DS.Tables[0].Rows[i].ItemArray.GetValue(1).ToString() != "")
        {
            values[arrayItemCount] = Convert.ToDouble(DS.Tables[0].Rows[i].ItemArray.GetValue(1));
            itemsSum += Convert.ToDouble(DS.Tables[0].Rows[i].ItemArray.GetValue(1));
            arrayItemCount += 1;
        }
    }
    average = itemsSum / arrayItemCount;
    for (int i = 0; i < arrayItemCount; i++)
    {
        deviations[i] = Math.Abs(values[i] - average);
        squareDeviations[i] = deviations[i] * deviations[i];
        squareDeviationsSum += squareDeviations[i];
    }
    squareDeviationsAverage = squareDeviationsSum / Convert.ToDouble(arrayItemCount - 1);
    stdDeviation = Math.Round(Convert.ToDouble(Math.Sqrt(squareDeviationsAverage)), 3);
}


texts:
I'm interested in optimizing my code. Can someone help me understand the best way to trim this code down with DRY methodology?

So I've got these two classes here preforming WMI queries on two separate Win32 classes. My questions are:

Should I keep them separated in different classes based on the Win32 class for organizational purposes?
Should I use a parent partial class and split these into different files?
Should I use methods with optional parameters or overloads in order to reduce the number of classes here?
Why is the selected method best?

public class Win32OperatingSystem
{
    public ulong GetFreePhysicalMemory()
    {
        return GetProperty("FreePhysicalMemory");
    }

    public ulong GetTotalVirtualMemorySize()
    {
        return GetProperty("TotalVirtualMemorySize");
    }

    public ulong GetFreeVirtualMemory()
    {
        return GetProperty("FreeVirtualMemory");
    }

    private ulong GetProperty(string propertyName)
    {
        ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
            ("SELECT " + propertyName + " FROM Win32_OperatingSystem");
        using (var enu = moSearcher.Get().GetEnumerator())
        {
            if (!enu.MoveNext()) return 0;
            return BytesToMegaBytes((ulong)enu.Current[propertyName]);
        }
    }

    private ulong BytesToMegaBytes(ulong bytes)
    {
        return bytes / (ulong)1024;
    }
}

public class Win32ComputerSystem
{
    public string GetName()
    {
        return GetProperty("Name");
    }

    public string GetManufacturer()
    {
        return GetProperty("Manufacturer");
    }

    public string GetModel()
    {
        return GetProperty("Model");
    }

    private string GetProperty(string propertyName)
    {
        ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
            ("SELECT " + propertyName + " FROM Win32_ComputerSystem");
        using (var enu = moSearcher.Get().GetEnumerator())
        {
            if (!enu.MoveNext()) return "Unable to retrieve " + propertyName + " from Win32_ComputerSystem!";
            return enu.Current[propertyName].ToString();
        }
    }
}

Questions in this series

This is the first question in the series.

First iteration of DRY refactoring

Second iteration of DRY refactoring.

Genericizing PropertyValues


texts:
I want to learn how to write good code. Starting off with simple programs for now. So any suggestions regarding style, readability or more efficient ways of implementation, etc. would really be appreciated!

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

int main(int argc, char** argv)
{
  bool running = true;

  while(running == true)
  {
    string input;
    cout << "[Enter 'exit' to exit the program]\n";
    cout << "Enter the text you want to reverse: ";
    getline(cin, input);

    if (input.compare("exit") == 0)
    {
      running = false;
      break;
    }

    reverse(input.begin(), input.end());
    cout << "The reversed version of your text is: " << input << endl << endl;
  }
  return 0;
}


texts:
I've been learning C# for 2 month and in the process of writing a quiz via file i/o. I want to know if there is a better way to getting the questions and answers rather than using switch statement so that it does not look too cluttered. I've tried using fields and properties but I don't know how to implement them into getting the lines in the txt. I've been using switch statement to get the array of the lines and the program work.
Here is a simple of my program:
    public class QuestionUI
    {

        String[] fileName = File.ReadAllLines(@"TraviaQuestion.txt");
        private String [] NO_OF_ANSWERS = new string[5];
        private String[] NO_OF_QUESTIONS = new String[5];

 public void Questions(int num)
        {
            NO_OF_QUESTIONS[0] = fileName[0];

            switch(num)
            {
                case 1:
                    {
                        Console.WriteLine("\n" + NO_OF_QUESTIONS[0]);
                        GetAnswer(1);
                        break;
                    }
               }
         }

  public void GetAnswer(int num)
        {
            switch (num)
            {
                case 1:
                    {
                        Console.WriteLine(NO_OF_ANSWERS[0] = fileName[1]);
                        Console.WriteLine(NO_OF_ANSWERS[0] = fileName[2]);
                        break;
                    }
            }
         }

 public void GetCorrectAnswer(String input, int num)
        {

            switch (num)
            {
                case 1:
                    {
                        if (input.ToUpper() != "B")
                        {
                            Console.WriteLine("Incorrect!");
                            GetExplanation(1);
                        }
                        else
                        {
                            Console.WriteLine("Correct!");
                        }
                        break;
                    }
             }
           }
 public void GetExplanation(int num)
        {
           switch(num)
            {
                case 1:
                    {
                        Console.WriteLine(fileName[6]);
                        break;
                    }
            }
         }
 public void ReadQuestionFile()
        {
            String input;

            Questions(1);
           input = Console.ReadLine();
            GetCorrectAnswer(input,1);
        }

```


texts:
It's the first time managing Mongoose by socket.io and I'm wondering if this could be a good way:

socket.on('comment sent', function(data){
    var comment = new Comment(data);
    comment.save(function(err) {
        if (err) {
            //may be better send a custom error
            return io.emit('comment error',err);
        }
        io.emit('comment added',comment);
    });
});


texts: HackerRank - Birthday Cake Candles and the counting loop

texts:
I was having fun on solving one of the HackerRank simple challenges
- Birthday Cake Candles.

Description

  Colleen is turning n years old! Therefore, she has n candles of various heights on her cake, and candle i has heighti. Because the taller candles tower over the shorter ones, Colleen can only blow out the tallest candles.

Given the heighti for each individual candle, find and print the number of candles she can successfully blow out.

Input Format

The first line contains a single integer, , denoting the number of candles on the cake.
The second line contains  space-separated integers, where each integer  describes the height of candle .

Output Format

Print the number of candles Colleen blows out on a new line.

Sample Input 0

4
3 2 1 3

Sample Output 0

2

Explanation 0

We have one candle of height 1, one candle of height 2, and two candles of height 3. Colleen only blows out the tallest candles, meaning the candles where height=3. Because there are 2 such candles, we print 2 on a new line.

My solution to the exercise above. You can find full code in gist with full code

function birthdayCakeCandles(n, ar) {
  var counts = {};

  ar.forEach(function(x) {
      counts[x] = (counts[x] || 0) + 1;
  });

  var toAr = Object.keys(counts).map(function(key){ return counts[key]; });
  var result = Math.max.apply(Math, toAr);

  return result;
}

n - number of candles
ar - array with heights of the candles

I would like to get a feedback on my part of the code, as I guess I might do a lot of unnecessary steps.


texts:
Below is an implementation of two graph traversals. Graph constructor creates a random graph with a fixed number of edges (fixed as a proportion of the maximum number of vertices, number_nodes-1).

Any comments welcome, but especially data structure and algorithm comments. Tests are not implemented properly, but it is ok in this case.

import random
class Graph:
    def __init__(self, number_nodes, max_number_edges = 0.5):
        if (max_number_edges > 1) or (max_number_edges < 0):
            raise ValueError("max_number_edges is out of range")
        self.nodes_connections = {node_nb : range(node_nb+1, number_nodes) for node_nb in xrange(number_nodes)}
        for key, value in self.nodes_connections.iteritems():
            while len(value) > (max_number_edges * (number_nodes - key - 1)):
                index_to_remove = random.randint(0, len(value)-1)
                del value[index_to_remove]

    def Print(self):
        for key, value in self.nodes_connections.iteritems():
            print key, value

    def IterateInBreadth(self, start_node_id):
        visited_nodes_ids = []
        scheduled_nodes_ids = [start_node_id]
        while scheduled_nodes_ids:
            node_id = scheduled_nodes_ids[0]
            new_scheduled_nodes_ids = [node for node in self.nodes_connections[node_id]
                                        if not (node in visited_nodes_ids or node in scheduled_nodes_ids)]
            new_scheduled_nodes_ids += [key for key, value in self.nodes_connections.iteritems()
                                            if (node_id in value) and not (key in visited_nodes_ids or key in scheduled_nodes_ids)]
            scheduled_nodes_ids += new_scheduled_nodes_ids
            visited_nodes_ids.append(node_id)
            del scheduled_nodes_ids[0]
        return visited_nodes_ids

    def __IterateInDepth(self, start_node_id, visited_nodes):
        visited_nodes.append(start_node_id)
        for key, value in self.nodes_connections.iteritems():
            if start_node_id in value:
                if key not in visited_nodes:
                    self.__IterateInDepth(start_node_id = key, visited_nodes = visited_nodes)
        for value in self.nodes_connections[start_node_id]:
            if value not in visited_nodes:
                self.__IterateInDepth(start_node_id = value, visited_nodes = visited_nodes)

    def IterateInDepth(self, start_node_id):
        visited_nodes = []
        self.__IterateInDepth(start_node_id, visited_nodes = visited_nodes)
        return visited_nodes

if __name__ == '__main__':
    #random.seed(1000)

    g = Graph(number_nodes = 11, max_number_edges = 0.33)
    g.Print()
    print g.IterateInBreadth(8)
    print g.IterateInBreadth(0)
    print g.IterateInDepth(8)
    print g.IterateInDepth(0)


texts:
I successfully solved a problem on Hackerrank called Contacts, but I'm curious if my code in C++ looks good to C++ developers. If not, how it should be improved.
Below is the short description of the problem and then the code itself.
Problem

Add name, where name is a string denoting a contact name. This must store name as a new contact in the application.
Find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting with partial and print the count on a new line.

So, given sequential add and find operations, perform each operation in order.
Solution
Use a Trie like structure to solve the problem. All the children of a node have a common prefix of the contact associated with that parent node, and the root is associated with the empty string.
Code
struct node {
    uint32_t count = 0;
    std::unordered_map<char, std::unique_ptr<node>> childrenMap;
};

/*
 * Complete the contacts function below.
 */
std::vector<uint32_t> contacts(std::vector<std::vector<std::string>>& queries) {
    std::vector<uint32_t> results;

    node root;
    for (const auto& row : queries) {
        const auto operation = row[0];
        const auto name = row[1];

        if (operation == "add") {
            auto* parent = &root;
            for (auto& ch : name) {
                auto& childrenMap = parent->childrenMap;
                if (!childrenMap.count(ch)) {
                    childrenMap.emplace(ch, std::make_unique<node>());
                }
                childrenMap[ch]->count++;
                parent = childrenMap[ch].get();
            }
        } else {
            auto* parent = &root;
            auto result = 0;
            for (auto& ch : name) {
                auto& childrenMap = parent->childrenMap;
                if (!childrenMap.count(ch)) {
                    result = 0;
                    break;
                }
                parent = childrenMap[ch].get();
                result = childrenMap[ch]->count;
            }
            results.push_back(result);
        }
    }

    return results;
}


texts:
I navigate with IE, do various things, then select all results option from a list and fire on click event. Once all results have been listed, I loop through their URLs, using the following code to gather data inside these URLs.

What can I do to improve speed of data scraping (apart from VB Script
multithreading)?

With

IE navigation, visible = false and no images I had 1000 links extracted in 3min 45sec
msxml2.XMLHTTP in 3min 30sec
msxml2.serverXMLHTTP 1min 40sec - .setRequestHeader "Content-Type", "text/xml" and .setRequestHeader "Accept-Encoding", "compress, gzip" didn't affect performance

Is it better to declare and create objects within this Sub (meaning inside the loop for 42,000 links) or outside and make them public variables?

Public Sub PrintCompanyData()
Dim oDom As Object: Set oDom = CreateObject("htmlFile")
Dim htmlelePopUp As IHTMLElement
Dim unformattedData As String

With CreateObject("msxml2.serverXMLHTTP") 'CreateObject("msxml2.xmlhttp")
    .Open "GET", Link, False
    '.setRequestHeader "Content-Type", "text/xml"
    '.setRequestHeader "Accept-Encoding", "compress, gzip"
    .send

    If .ReadyState = 4 And .Status = 200 Then

        oDom.body.innerHTML = .responseText

        With WS
            For Each htmlelePopUp In oDom.getElementsByTagName("tbody")
                unformattedData = htmlelePopUp.Children(htmlelePopUp.Children.Length - 1).innerText
                .Range("a" & ItemCount + 1).Value2 = Replace(unformattedData, Chr(10), vbNullString)
            Next htmlelePopUp
        End With

    End If

End With

Set oDom = Nothing

End Sub


texts: Finding Egyptian fractions with A* search

texts:
I've written an A* search to find the optimal solution to the equation

$$ \dfrac{4}{n} = \dfrac{1}{x} + \dfrac{1}{y} + \dfrac{1}{z} $$

with \$n, x, y, z\$ positive integers, and \$n\$ given; the optimal solution being the one with smallest sum \$ x + y + z \$.

(The Erdős–Straus conjecture states that there are solutions to this equation for all \$n>2\$.)

My working version:

def evaluate(option):
    return sum(option)

def generate_options(option):
    def option_valid(o):
        prev = o[0]
        for el in o[1:]:
            if el < prev:
                return False
            prev = el
        return True

    x, y, z = option
    opt = (x + 1, y, z)
    if option_valid(opt): yield opt
    opt = (x, y + 1, z)
    if option_valid(opt): yield opt
    opt = (x, y, z + 1)
    if option_valid(opt): yield opt

def is_solution(current, n):
    x, y, z = current
    if (4 / n) == (1 / x + 1 / y + 1 / z):
        return True
    return False

def A(option, generate_options, evaluate, is_solution):
    done = set()
    paths = PriorityQueue()
    paths.put((evaluate(option), option))
    done.add(option)
    while not paths.empty():
        price, current = paths.get()
        if is_solution(current):
            return price, current
        for gp in generate_options(current):
            if gp not in done:
                done.add(gp)
                paths.put((evaluate(gp), gp))
    return None

def main():
    def solution(x):
        return is_solution(x, n=18)

    print(A(
        (1, 1, 1),
        generate_options=generate_options,
        evaluate=evaluate,
        is_solution=solution))

The problem I see with this code would be that since I store all the checked solutions into a set, I could potentially run out of memory for an \$n\$ that would require a large amount of checked options. In my mind, I could fix this by clearing the entire set every \$m\$ iterations, but that could lead back to some options being checked more than once.

I'm fairly new to Python, and I also wonder if there's a better way to write my generate_options function. I do know there was no need to make it into a generator, but I did it that way for the sake of seeing how they work.


texts:
I do a lot of unit testing(tdd) and would like some comments about my style. Here is a simple example from a composite.

Is there anything I could improve?

public class ChangedClaimsServiceComposite : IChangedClaimsService
{
    private readonly IChangedClaimsService[] changedClaimsServices;

    public ChangedClaimsServiceComposite(params IChangedClaimsService[] changedClaimsServices)
    {
        if (changedClaimsServices == null) throw new ArgumentNullException("changedClaimsServices");
        this.changedClaimsServices = changedClaimsServices;
    }

    public List<IChangedClaim> GetChangedClaims()
    {
        return changedClaimsServices.SelectMany(x => x.GetChangedClaims()).ToList();
    }

    public void SetClaimUpdated(IChangedClaim changedClaim)
    {
        foreach (var changedClaimsService in changedClaimsServices)
        {
            changedClaimsService.SetClaimUpdated(changedClaim);
        }
    }
}

[TestFixture]
public class ChangedClaimsServiceCompositeTests
{
    [Test]
    public void GetChangedClaimsSouldCombineResultsFromDependedServices()
    {
        //Arrange
        var changedClaimService1 = new Mock<IChangedClaimsService>();
        var changedClaimService2 = new Mock<IChangedClaimsService>();

        var changedClaim1 = CreateAnyChangedClaim();
        var changedClaim2 = CreateAnyChangedClaim();
        var changedClaim3 = CreateAnyChangedClaim();
        var changedClaim4 = CreateAnyChangedClaim();

        changedClaimService1.Setup(x => x.GetChangedClaims())
            .Returns(new List<IChangedClaim>() {changedClaim1, changedClaim2});
        changedClaimService2.Setup(x => x.GetChangedClaims())
            .Returns(new List<IChangedClaim>() { changedClaim3, changedClaim4 });

        var sut = new ChangedClaimsServiceComposite(
            changedClaimService1.Object,
            changedClaimService2.Object);

        //Act
        var result = sut.GetChangedClaims();

        //Assert
        var expectedResult = new List<IChangedClaim>()
        {
            changedClaim1,
            changedClaim2,
            changedClaim3,
            changedClaim4
        };
        Assert.That(result, Is.EqualTo(expectedResult), "result");
    }

    [Test]
    public void SetClaimUpdatedShouldCallSameMethodOnDependedServices()
    {
        //Arrange
        var changedClaimService1 = new Mock<IChangedClaimsService>();
        var changedClaimService2 = new Mock<IChangedClaimsService>();

        var changedClaim = CreateAnyChangedClaim();

        var sut = new ChangedClaimsServiceComposite(
            changedClaimService1.Object,
            changedClaimService2.Object);

        //Act
        sut.SetClaimUpdated(changedClaim);

        //Assert
        changedClaimService1.Verify(x => x.SetClaimUpdated(changedClaim), "changedClaimService1");
        changedClaimService2.Verify(x => x.SetClaimUpdated(changedClaim), "changedClaimService2");
    }

    private IChangedClaim CreateAnyChangedClaim()
    {
        return new Mock<IChangedClaim>().Object;
    }
}


texts: Copy a file, renaming it if the destination already exists.

texts:
I would love some feedback on this little utility function:

/**
 * Copy $src to $dest, renaming it if the desired destination already exists.  The
 * string '.versionX' is inserted before the file extension if a file must be
 * renamed, with X incremented as needed.
 *
 * @return boolean true if copy was successful, false otherwise.
 */
public static function copy_with_rename($src, $dest)
{
    if (file_exists($dest))
    {
        // See if it's the same.
        $existingFileHash = sha1_file($dest);
        $new_file_hash = sha1_file($src);
        if ($existingFileHash != $new_file_hash)
        {
            // File of same name exists, but is different.
            $last_dot_pos = strrpos($dest,'.');
            $file_count = 2;
            // So find a new name.
            do
            {
                $base_name = substr($dest, 0, $last_dot_pos);
                $ext = substr($dest, strlen($base_name)); // with dot
                $new_name = $base_name.'.version'.$file_count.$ext;
                $file_count++;
            } while (file_exists($new_name) && sha1_file($src)!=sha1_file($new_name));
            // And then try the copy again, with the new name.
            return file::copy_with_rename($src, $new_name);
        } else
        {
            return true;
        }
    } else
    {
        $dest_dir = dirname($dest);
        // Create (to any depth) the destination directory, if required.
        if (!file_exists($dest_dir))
        {
            mkdir($dest_dir, 0777, true);
        }
        // And finally do the actual copy.
        return copy($src, $dest);
    }
}


texts: Alternative to null check after DOM traversal?

texts:
I have this code working, but I'm not sure if it's the best way to write it. I was watching a JS talk on Maintainable JavaScript, and saw that I probably shouldn't be comparing my element  to null, and instead should use typeof. However, regardless what is returned, it's still an object.

What my code does:

So I needed this code to determine which top-level nav the sub-menu navigations correspond too. What this example does is finds a submenu nav item and grabs it's inner text, then it gets thrown into a while loop to traverse the DOM to find the top-level nav's innerText so I can then have both a top-level nav name and sub-menu nav name. However if the top-level nav does not have a sub-menu then it returns nothing.

var element = document.getElementsByClassName('gtm_navHeader')[25];
var elementText = element.innerText
var elementClass = "menu-parent";

while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){
    element = element.parentNode;
}

  if (element == null){
    console.log('equals null - ' + elementText);
  }else{
    var anchor = element.querySelector("a");
    var clean = (anchor.innerText || anchor.textContent).toLowerCase() + " : " + elementText;
    console.log('does not equal - ' + clean);
}

JS FIDDLE

Let me know if you have any questions. Happy to provide more information.


texts: Side Scrolling App Too Slow (using UIScrollView)

texts:
I'm building an app where the user can press play and then the app will scroll through some musical notes (like sheet music). I use a timer and counter to move the view along. The code works ok, except that every time I press play to start the view scrolls at a different speed. The first time is very slow but it gets to the speed I want after playing through a few times. I assume this is because as I repeat the action, iOS loads things into memory and is able to run things faster and smoother.

Is there some way to speed things up, or perhaps there is a different approach than using a UIScrollView for something it wasn't really designed for? Any ideas are much appreciated!

import UIKit

class TimelineViewController: UIViewController {

var screenHeight = UIScreen.main.bounds.height
var screenWidth = UIScreen.main.bounds.width
var scrollView = UIScrollView()
let canvasWidth = 7204
var counter = 0
var timer = Timer()

func setupScrollView() {
    scrollView.frame = self.view.bounds
    let scrollImageView = UIView()
    scrollImageView.frame = CGRect(x: 0, y: 0, width: canvasWidth, height: Int(screenHeight))
    scrollView.contentSize = scrollImageView.bounds.size
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.showsVerticalScrollIndicator = false
    scrollView.backgroundColor = .black
    scrollView.addSubview(scrollImageView)
    self.view.addSubview(scrollView)
}

@objc func updateTime() {
    DispatchQueue.global(qos: .default).async {
        let counterStop = self.canvasWidth-(Int(self.screenWidth))
        guard self.counter < counterStop else {return}
        self.counter += 1
        }

    UIView.animate(withDuration: 0.1, animations: {
        self.scrollView.setContentOffset(CGPoint(x: self.counter, y: 0), animated: false)
})}

@IBAction func startPlayhead(_ sender: Any) {
    print("Play pressed")
    counter = 0
    let tempoSetter = 0.03
    timer = Timer.scheduledTimer(timeInterval: tempoSetter, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    setupScrollView()
    var measureMarkerCoords: [Int] = [600,1200,1800,2400,3000,3600,4200, 4800, 5400, 6000, 6600,7200]
    var colourOrder: [UIColor] = [UIColor.red,UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple, UIColor.red,UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple]

    for i in 0...11 {
        let measureMarker = UIView(frame:CGRect(x:measureMarkerCoords[i],y:0,width:4,height:Int(screenHeight)))
        measureMarker.backgroundColor = colourOrder[i]
        self.scrollView.addSubview(measureMarker)
    }

    let playButton = UIButton(frame: CGRect(x: 10, y: 5, width: 44, height: 44))
    playButton.setTitle("Play", for: .normal)
    playButton.addTarget(self, action: #selector(startPlayhead(_:)), for: .touchUpInside)
    view.addSubview(playButton)
}
}


texts: begin() vs rbegin(): how can I avoid duplication?

texts:
Can the display function be re-written to avoid duplication of the std::for_each loop?

#include <iostream>
#include <set>
#include <algorithm>

struct Widget
{
    int id;
    Widget(int i) : id(i){}
};

namespace std
{
    template<>
    struct less<Widget *> {
    public:
        bool operator ()(Widget *const& a, Widget *const& b) const {
            return  (a->id < b->id);
        }
    };
}

void display(const std::set<Widget *>& wList, bool order)
{
    if (order) {
        std::for_each(wList.begin(), wList.end(), [](const Widget* x) {
            std::cout << x->id << std::endl;
        });
    }
    else {
        std::for_each(wList.rbegin(), wList.rend(), [](const Widget* x) {
            std::cout << x->id << std::endl;
        });
    }
}

int main()
{

    std::set<Widget *> s;

    s.insert(new Widget(1));
    s.insert(new Widget(2));
    s.insert(new Widget(5));
    s.insert(new Widget(3));
    s.insert(new Widget(9));
    s.insert(new Widget(7));

    display(s, false);
}


texts:
I have a function that takes the root node as input and needs to return if the tree is a proper BST as per the definition below:

The data value of every node in a node's left subtree is less than
the data value of that node.
The data value of every node in a node's
right subtree is greater than the data value of that node
It cannot contain duplicate values.

Here's my implementation

  boolean checkBST(Node root) {
        if(root==null) return false;
        Queue<Node> q = new LinkedList<>();
        Set<Integer> s = new HashSet<>();
        q.add(root);
        while(q.size()>0){
            Node t = q.poll();
            if(s.contains(t.data))
                return false;
            s.add(t.data);
            if(t.left!=null)
                {
                    if(t.data<=t.left.data)
                        return false;
                q.offer(t.left);
            }
            if(t.right!=null){
                if(t.data>=t.right.data)
                    return false;
                q.offer(t.right);
            }
        }
        return true;
    }

Things to discuss:

I've pursued a Breadth first approach. Is there a better approach?
The above procedure fails for some test inputs (I don't know what the inputs are that breaks it). Trying to find out what they are
Issues with the above implementation


texts: Is this really what has to be done to clear the selection of an ASP.NET TreeView?

texts:
I have a TreeView called myTreeView. I want to be able to write a single statement after which myTreeView.SelectedNode is null, but TreeView.SelectedNode doesn't have a setter. I've looked at the decompiled source of TreeView, and there is a SetSelectedNode method (that can accept null), but it's internal.

So I made this extension method:

public static void ClearSelection(this TreeView treeView)
{
    var currentSelection = treeView.SelectedNode;
    if (currentSelection != null)
    {
        currentSelection.Selected = false;
    }
}

and now I can just say

myTreeView.ClearSelection();

But this seems insane. Am I missing something?


texts:
I am working to improve this script, which should prepare a text to be sent as a GSM short message using only the GSM 7-bit character coding with Basic Character Set Extension.

import logging
import traceback
import unicodedata
logger = logging.getLogger(__name__)

class IsGSM:

    def __init__(self):
        self.gsm = "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?" \
      "¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ§¿abcdefghijklmnopqrstuvwxyzäöñüà"
        self.ext = "^{}\\[~]|€"
        self.toBeNormalized = '\xa0'+'\xc2'
        self.ascii_gsm = {}
        self.ascii_map()
        self.normalize_dict = {}
        self.normalize_map()

    def ascii_map(self):
        for c in self.gsm:
            #if ord(c) < 256:
            self.ascii_gsm[ord(c)] = True
        for c in self.ext:
            #if ord(c) < 256:
            self.ascii_gsm[ord(c)] = True

    def normalize_map(self):
        for c in self.toBeNormalized:
            self.normalize_dict[c] = True

    def _is_gsm(self, content):

        template = content

        try:
            template.encode('windows-1252')
        except UnicodeEncodeError:
            return False

        for c in content:
            if ord(c) not in self.ascii_gsm:
                return False
        return True

    @classmethod
    def is_gsm(cls, content):
        instance = IsGSM.instance()
        return instance._is_gsm(content)

    @classmethod
    def normalizeBodyContent(cls, content):
        instance = IsGSM.instance()
        return instance._normalizeBodyContent(content)

    @classmethod
    def instance(cls):
        """Singleton like accessor to instantiate backend object"""
        if not hasattr(cls, "_instance"):
            cls._instance = cls()
        return cls._instance

    def _normalizeBodyContent(self, content):
        try:
            target_content = [c for c in content]
            content_length = len(target_content)
            for ith in range(content_length):
                if target_content[ith] in self.normalize_dict:
                    target_content[ith] = unicodedata.normalize("NFKD",target_content[ith])

            content = "".join(target_content)
        except Exception as e:
               logger.error('Exception occurred normalizing content {0}'.format(content))
               traceback.print_exc()
               raise e
        return content

if __name__ == "__main__":
    print(IsGSM.is_gsm("Est a punto de restablecer la contrasea de su cartera de Kutxabank. Por favor, introduzca la sigui..."))
    print(IsGSM.is_gsm("This should fix the problem. Your content xxxxx from ÄA K COMPANY LTD will be delivered by xxxx today.Track your content at  some_url@&!"))

I can refactor the _normalizeBodyContent method like this:

def _normalizeBodyContent(self, content):
    try:
        target_content = [c for c in content]
        content_length = len(target_content)
        for ith in self.normalize_dict:
            target_content = target_content.replace(ith,
                                         unicodedata.normalize("NFKD", ith))
        content = "".join(target_content)
    except Exception as e:
        logger.error('Exception occurred normalizing content {0}'.format(content))
        traceback.print_exc()
        raise e
    return content

Is this an improvement on the original, in-terms of processing time and readability?

I'm particularly interested in comparing the lookup via in and overwrite against using the replace() library function.  Review on any portion of the whole script is also appreciated.


texts: Adding, deleting elements as per autocomplete results - updated

texts:
I am working on a Python/Django project which has turned into a JavaScript/jQuery project due to the amount of asynchronous functionality that I thought to add.
There is a JavaScript file which is doing everything for the JS side. I am a newbie in JavaScript/jQuery and am starting to think that this is going to become a big problem soon.
I asked for a previous review but as I never got one there and the file has changed a lot since then I am placing part of the file where I think something can be be improved.

Some functions which are being used by the code:

function bind_events(cur_obj, e) {
    var trigger_name = "";
    if (e.keyCode == 13) {
        trigger_name = EV_ENTER_KEY;
    } else if (e.altKey && e.keyCode == "N".charCodeAt(0)) {
        trigger_name = EV_ALT_N;
    }
    $(cur_obj).trigger(trigger_name);
}

//Auxiliary functions for categories
function get_all_categories() {
    var class_ids = [];
    $(CLASS_DEL_CATEGORY).each(function () {
        class_ids.push(get_class_string(this, 11));
    });
    return class_ids.join(",");
}

function enter_category(category_box, trigger_event, trigger_data) {
    if (value_in_selector(category_box, CLASS_UI_MENU_ITEM) == false) {
        alert(MSG_NOT_CATEGORY);
    } else if (value_in_selector(category_box, CLASS_CATEGORY) == true) {
        alert(MSG_CATEGORY_ADDED);
        category_box.val("");
    } else {
        category_box.trigger(trigger_event, trigger_data);
    }
}

function add_category(cur_obj, e, data) {
    $.ajax({
        url: URL_CATEGORY,
        data: {'value': $(cur_obj).val()},
        success: function (output) {
            data.cat_list.append(output);
            $(cur_obj).val("");
            if (data.trigger_obj !== undefined) {
                data.trigger_obj.trigger(data.next_trig);
            }
        }
    });
}

The code that I think needs to be improved is below.

//Actions for Search's category box
CATEGORY_INPUT.on({
    keyup: function (e) {
        bind_events(this, e);
    },

    "enterKey": function () {
        enter_category($(this), EV_ADD_CATEGORY, [
            {
                cat_list: CATEGORY_LIST_SEARCH,
                trigger_obj: BOOKMARK_LIST,
                next_trig: EV_UPDATE_BOOKMARKS
            }
        ])
    },

    "addCategory": function (e, data) {
        add_category(this, e, data);
    },

    "clearAll": function () {
        $(CLASS_CATEGORY).remove();
        $(this).val("");
        BOOKMARK_LIST.trigger(EV_CLEAR_ALL);
    }
});

//Actions for Add Bookmark's category box
CATEGORY_BOX.on({
    keyup: function (e) {
        bind_events(this, e);
    },

    "enterKey": function () {
        enter_category($(this), EV_ADD_CATEGORY, [
            {
                cat_list: CATEGORY_LIST_ADD,
                trigger_obj: undefined,
                next_trig: undefined
            }
        ])
    },

    "addCategory": function (e, data) {
        add_category(this, e, data);
    }
});

As you can see nearly same events are bound to both with minor changes. I thought to bind events to multiple selectors but as not all are same events readability will suffer.

Any thoughts for improvements?


texts:
I am experimenting with cryptography and I was wondering if somebody has some suggestion how I could improve my code and methodology.

I want my process to generate more securely the cryptography process if that is possible

import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

@SuppressWarnings("ClassWithoutLogger")
public class Crypto_Security {

  static public final String CRY_ALGO = "AES";

  static public String encrypt(byte[] pSecret, String pValue) throws GeneralSecurityException {
    Key aesKey = new SecretKeySpec(pSecret, CRY_ALGO);
    Cipher cipher = Cipher.getInstance(CRY_ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(pValue.getBytes());
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(encrypted);
  }

  static public String decrypt(byte[] pSecret, String pEncrypted) throws GeneralSecurityException {
    SecretKeySpec skeySpec = new SecretKeySpec(pSecret, CRY_ALGO);
    Cipher cipher = Cipher.getInstance(CRY_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original = cipher.doFinal(Base64.getDecoder().decode(pEncrypted));
    return new String(original);
  }

  static public void main( String[] args ) {
    try {
      System.out.println("enc " + encrypt( "2144226321110063".getBytes() , "serial.txt" ));
      System.out.println("dcr " + decrypt( "2144226321110063".getBytes() , "oLQgEUxg3Z3zMSsSkiKpBg==" ));
    } catch( GeneralSecurityException e ) {
      e.printStackTrace();
    }
    return;
  }

  private Crypto_Security() {
  }

}


texts: Calculate "average", "median" and "percentile" from a long array

texts:
I have this method which calculates the average, median and percentile information given a long array of numbers. Is there any better and efficient way to do the same?

  public static double median(long[] numbers) {
    Arrays.sort(numbers, 0, numbers.length);
    int middle = numbers.length / 2;
    if (numbers.length % 2 == 1) {
      return numbers[middle];
    } else {
      return (numbers[middle - 1] + numbers[middle]) / 2.0;
    }
  }

  public static double average(long[] numbers) {
    int sum = 0;
    for (long l : numbers)
      sum += l;
    double average = 1.0d * sum / numbers.length;
    return average;
  }

  public static long[] percentiles(long[] numbers, double... percentiles) {
    Arrays.sort(numbers, 0, numbers.length);
    long[] values = new long[percentiles.length];
    for (int i = 0; i < percentiles.length; i++) {
      int index = (int) (percentiles[i] * numbers.length);
      values[i] = numbers[index];
    }
    return values;
  }


texts: Handling IndexError using lambda function within scrapy

texts:
I've written a script using python's scrapy library to parse some fields from craigslist. The spider I've created here is way normal than what usually gets considered ideal to be reviewed. However, I've tried to handle the list index out of error issue using a customized function within scrapy. There might be better ways to do so but What I noticed with the one I've tried that when there are several fields to scrape then this customized function play a vital role to deal with those fields whose values are none. I'll be vary glad to have any better ideas to do the same. Thanks in advance.

Here is what I've tried:

import scrapy
from scrapy.crawler import CrawlerProcess

class CraigsspSpider(scrapy.Spider):
    name = 'craigssp'

    start_urls = ['http://bangalore.craigslist.co.in/search/rea?s=120']
    #the below function is able to handle IndexError
    get_result = lambda item,path:item.css(path).extract_first() if item.css(path) else ""

    def parse(self, response):
        for items in response.css(".result-info"):
            date = CraigsspSpider.get_result(items,".result-date::text")
            name = CraigsspSpider.get_result(items,".hdrlnk::text")
            price = CraigsspSpider.get_result(items,".result-price::text")
            yield{'Date':date,'Name':name,'Price':price}

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(CraigsspSpider)
c.start()


texts:
I am trying to make a simple expression evaluator in Java using Jacc (a parser generator). I am done with the AST creation and now need to create an evaluator. For this I made a simple test to try to understand how visitors work. Here is my code

interface Visitor
{
    public void visitB(B b);
    public void visitC(C c);
    public void visitD(D d);
}

class PrintVisitor implements Visitor
{
    public void visitB(B b)
    {
        b.child1.accept(this);
        b.child2.accept(this);
        System.out.println("a B visited: " + b.name);
    }

    public void visitC(C c)
    {
        c.child.accept(this);
        System.out.println("a C visited: " + c.name);
    }

    public void visitD(D d)
    {
        System.out.println("a D visited: " + d.name);
    }
}

abstract class A
{
    public String name;
    abstract void accept(Visitor v);
}

class B extends A
{
    public A child1;
    public A child2;

    public B(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitB(this);
    }
}

class C extends A
{
    public A child;

    public C(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitC(this);
    }
}

class D extends A
{
    public D(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitD(this);
    }
}

class Main
{
    public static void main(String[] args)
    {
        B b1 = new B("b1");
        B b2 = new B("b2");

        C c1 = new C("c1");
        C c2 = new C("c2");

        D d1 = new D("d1");
        D d2 = new D("d2");
        D d3 = new D("d3");
        D d4 = new D("d4");

        /*
            b1
          /   \
        c1    c2
      /         \
    b2           d2
   /  \
 d3   d4

        */

        b1.child1 = c1;
        b1.child2 = c2;

        c1.child = b2;
        c2.child = d2;

        b2.child1 = d3;
        b2.child2 = d4;

        PrintVisitor v = new PrintVisitor();
        b1.accept(v);
    }
}

I would appreciate if you guys commented on my understanding of visitors.


texts:
I am using the Python module urllib3. It occurs to me that there is a better way to design a good class when I rebuild my last site crawler.

class Global:
    host = 'http://xxx.org/'
    proxy=True
    proxyHost='http://127.0.0.1:8087/'
    opts=AttrDict(
        method='GET',
        headers={'Host':'xxxx.org',
              'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0',
              'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
              'Accept-Language':'en-us;q=0.5,en;q=0.3',
              'Accept-Encoding':'gzip, deflate',
              'Connection':'keep-alive',
              'Cookie':'xxxxxxx',
              'Cache-Control':'max-age=0'
              },
        assert_same_host=False
    )
    def getPool(self,proxy=None):
        if proxy is  None:
            proxy = self.proxy
        if(self.proxy):
            http_pool = urllib3.proxy_from_url(self.proxyHost)
        else:
            http_pool = urllib3.connection_from_url(self.host)
        return http_pool

class Conn:
    def __init__(self, proxy):
        self.proxy= proxy
        self.pool = Global().getPool(self.proxy)
    def swith(self):
        self.pool = Global().getPool(not self.proxy)
    def get(url, opts=Global.opts):
        try:
          self.pool.urlopen(
              method=opts.method,
              url= url,
              headers= opts.headers,
              assert_same_host=opts.assert_same_host
              )
        except TimeoutError, e:
            print()
        except MaxRetryError, e:
            # ..

I try to make class contains all global configs and data for others to call,
just like I do in JavaScript. But, are these classes too tightly coupled? Should I just merge them together?


texts:
The exercise is as follows:

  Create a class called Fraction that can be used to represent the ratio of two integers.
  Include appropriate constructors, properties, and methods. If the denominator becomes
  zero, throw and handle an exception. Create an application class to test the Fraction class.

The program runs.  Will someone look over my code for this exercise?

Fraction.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Part2
{
    public class Fraction
    {
        private int numerator;
        private int denominator;

        /// <summary>
        /// Initialize the fraction properties
        /// </summary>
        /// <param name="numerator">Upper number</param>
        /// <param name="denominator">Lower number</param>
        public Fraction(int numerator, int denominator)
        {
            this.Numerator = numerator;
            this.Denominator = denominator;
        }

        /// <summary>
        /// Access tot he numerator property
        /// </summary>
        public int Numerator
        {
            get { return this.numerator; }
            set { this.numerator = value; }
        }

        /// <summary>
        /// Access to the denominator property
        /// </summary>
        public int Denominator
        {
            get { return this.denominator; }
            set
            {
                if (value == 0)
                {
                    throw new Exception("0 denominator");
                }

                this.denominator = value;
            }
        }

        /// <summary>
        /// Return a string representation of a fraction
        /// </summary>
        /// <returns>Displayable attribute</returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(this.Numerator + "/" + this.numerator);
            sb.Append(" or ");
            sb.Append(this.Numerator / this.Denominator);

            return sb.ToString();
        }
    }
}

Application.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Part2
{
    public class Application
    {
        /// <summary>
        /// Entry point of the program
        /// </summary>
        public static void Main(string[] args)
        {
            // Create a fraction
            Fraction f1 = new Fraction(1, 2);
            Console.WriteLine(f1);

            try
            {
                // Create another fraction
                Fraction f2 = new Fraction(2, 0);
                Console.WriteLine(f2);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
    }
}


texts: Django social network application - database schema

texts:
I am writing a simple social media application in Django. I would like to know whether the following model structure is correct, or how can I improve the schema to get better performance. Do I need to split the following relation into a separate model? Like in this question

Models.py

class User(AbstractBaseUser, PermissionsMixin):
    """
    Custom user model with email as username
    """
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=75, blank=True, null=True)
    last_name = models.CharField(max_length=75, blank=True, null=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    date_of_birth = models.DateField(validators=[validate_dob],
                                     blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    avatar = models.URLField(blank=True, null=True)
    followers = models.ManyToManyField("self", blank=True,
                                       symmetrical=False,
                                       related_name='following')

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    @property
    def age(self):
        current_year = datetime.datetime.today.year
        return current_year - self.date_of_birth.year

    def get_full_name(self):
        return '{} {}'.format(self.first_name, self.last_name)

    def get_short_name(self):
        return self.first_name

class Post(models.Model):
    title = models.CharField(max_length=45)
    description = models.CharField(max_length=144)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    published_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['published_on']

    def __str__(self):
        return self.title

To prepare the feed for a requested user, I would like to use the query,

u1 = User.objects.first()
posts = Post.objects.filter(author__in=u1.following.all())


texts: Creating a user via social auth, merging and modifying appropriately

texts:
I'm using Sequelise with node.js, and I have a feeling the paradigm I'm using to modify objects is not working well, as my code is getting messy rather quickly.

The function User.createOrMerge is designed to be called after a successful social auth (Google, Facebook etc.), with kwargs being the social auth token to check against the user (e.g. { googleId: "some-oauth-token" }).

I seem to be writing a lot of code to deal with the overhead of using promises. Is there a way to do this more elegantly or is this my life now?

User.findByUsername = function(username, success, error){
  User.findOne({
    where: {
      username: username
    }
  }).then(function(user){
    success && success(user);
  }, function(){
    error && error();
  });
};

User.findByEmail = function(email, success, error){
  User.findOne({
    where: {
      email: email
    }
  }).then(function(user){
    success && success(user);
  }, function(){
    error && error()
  });
}

User.createOrMerge = function(username, email, kwargs, success, failure){
  // if user with kwargs exists, return that
  User.findOne({
    where: kwargs
  }).then(function (user) {
      if(user){
        success && success(user);
      }else{
        // if email address exists, merge user
        User.findByEmail(email, function(user){
          if(user){
            user.updateAttributes(kwargs).then(function(){
              success && success(user);
            });
          }else{
            // if username exists, modify this one
            User.findByUsername(username, function(user){
              if(user){
                username += UUID();
              }
              // finally create a new user
              kwargs['username'] = username;
              kwargs['email'] = email;
              User.create(kwargs).then(function(user){
                success && success(user);
              }, function(){
                failure && failure();
              });
            }, function(){
              failure && failure();
            });
          }
        }, function(){
          failure && failure();
        });
      }
  }, function(){
    failure && failure();
  });
}


texts: How to deal with method which throws 7 exceptions

texts:
I'm re factoring some code and have come across a method which is throwing 7 exceptions, the method length is approx 20 lines. The method caller wraps this method in a try catch, and just catches the generic Exception. Is there a better way to handle this ? I don't think I should handle each possible exception thrown individually ?

try {
setter();
}
catch(Exception e){
e.printStackTrace();
}

    private void setter() throws MalformedURLException, IOException, ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException, XPathExpressionException
    {
        .....
    }


texts:
I'm currently getting into MVC, and I'm working on a simple CRUD application but to make best use of relational database layout I need to use ViewModels so things look prettier on the UI.

I have a ViewModel:

public class CreateAPIViewModel
{
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "Description")]
    public string Description { get; set; }

    [Display(Name = "Team")]
    public int TeamID { get; set; }

    [Display(Name = "Application")]
    public int ApplicationID { get; set; }

    [Display(Name = "Team")]
    public IEnumerable<SelectListItem> Team { get; set; }

    [Display(Name = "Application")]
    public IEnumerable<SelectListItem> Application { get; set; }

    [Display(Name = "Location")]
    public string Location { get; set; }

    [Display(Name = "Keywords")]
    public string Keywords { get; set; }
}

And in my APIController I have this action:

public ActionResult Create()
{
    CreateAPIViewModel viewModel = new CreateAPIViewModel();

    //Fill team - seems a bit long doesn't it?
    listOfTeams = team.getAllTeams();

    List<SelectListItem> listOfTeamsSelect = new List<SelectListItem>();

    foreach (_Team_Detail item in listOfTeams)
    {
        listOfTeamsSelect.Add(new SelectListItem { Value = Convert.ToString(item.ID), Text = item.Name });
    }

    viewModel.Team = listOfTeamsSelect;

    //Fill application - seems a bit long doesn't it?
    listOfApplications = application.getAllApplications();

    List<SelectListItem> listOfApplicationsSelect = new List<SelectListItem>();

    foreach (_Application item in listOfApplications)
    {
        listOfApplicationsSelect.Add(new SelectListItem { Value = Convert.ToString(item.ID), Text = item.Name });
    }

    viewModel.Application = listOfApplicationsSelect;

    //Send view model back
    return View(viewModel);
}

Is this the best way to be going about this process for creating a Create page so I can have dropdowns?


texts:
I am implementing A064604 - OEIS for positive integers up to 10 billion.

I am finding the divisors in \$O(\sqrt N)\$. So, the overall time complexity of running the formula right now is \$O(N\sqrt N)\$. How do I improve on this?

Pastebin

import math

def factors(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def sigma_4(n):
    l = factors(n)
    ans=0
    for factor in l:
        ans += (pow(factor,4))
    return ans

n=int(raw_input())
ans=0
for i in xrange(1,n+1):
    ans+=sigma_4(i)
print ans


texts: Calculating a table of deBroglie wavelengths for various electron energies

texts:
Here is the formula for the deBroglie wavelength of an electron versus its kinetic energy:
$$ \lambda(E_k) = h\left/\sqrt{\frac{(E_k+m_eC^2)^2-m_e^2C^4}{C^2}}\right.$$
and here is simple script that prints a CSV with plot data:

#!/usr/bin/python
import csv
from scipy import constants as spc
import numpy as np

vev = np.arange(1,1e6,100);
vWavelength = map( lambda n: \
               spc.h/np.sqrt( (np.power(spc.eV*n+spc.m_e*np.power(spc.c,2),2)-np.power(spc.m_e,2)*np.power(spc.c,4))/np.power(spc.c,2) ), \
               vev );
np.savetxt('plotdata/1a.csv', np.transpose(np.array([vev, vWavelength])));

The vWavelength line is abysmal, in my opinion. How can I make this code better?


texts:
JavaScript is the language everyone uses without bothering to learn it first, and I'm no exception. I'm trying to set up autorefresh with longpolling. What I have on the client side is the following:

var getAjaxer = function(element) {

    return function() {
        $.ajax({
            url: "/path/to/resource",
            success: function(response) {
                element.html(response);
            },
            dataType: "html",
            timeout: 10000,
            type: "POST",
            complete: arguments.callee
        });
    };
}

var startAjaxing = function() {
    myajaxer = getAjaxer($("#myid"));
    myajaxer();
}

$(startAjaxing);

This works, but I'm worried I might be doing it all wrong. Could I get some pointers on how I could use the language more effectively?


texts: Dynamically generated controls based on data from dictionary

texts:
I have attempted the GUI controls creation in a prompt based on data from dictionary.  Is this the best way of implementing this?

import sys
from PyQt4 import QtCore, QtGui

class MessageBox(QtGui.QDialog):
    """docstring for MessageBox"""
    def __init__(self, data=None, parent=None):
        super(MessageBox, self).__init__(parent)
        self._data = data
        self.buildUi()

    def buildUi(self):
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setSpacing(10)
        for index, (key, values) in enumerate(self._data.iteritems()):
            getLbl = QtGui.QLabel("Get", self)
            label = QtGui.QLabel(key, self)
            chkBox = QtGui.QCheckBox(self._data[key][0], self)
            chkBox.setToolTip("Click here to get the book")
            version = QtGui.QSpinBox( self)
            version.setValue(self._data[key][-1])
            version.setRange(self._data[key][-1], 12)
            self.gridLayout.addWidget(getLbl, index, 0)
            self.gridLayout.addWidget(label, index, 1)
            self.gridLayout.addWidget(chkBox, index, 2)
            self.gridLayout.addWidget(version, index, 3)
        self.layout = QtGui.QVBoxLayout()
        self.okBtn = QtGui.QPushButton("OK")
        self.layout.addLayout(self.gridLayout)
        self.horLayout = QtGui.QHBoxLayout()
        self.horLayout.addStretch(1)
        self.horLayout.addWidget(self.okBtn)
        self.layout.addLayout(self.horLayout)
        self.setLayout(self.layout)

class MainWindow(QtGui.QMainWindow):
    """docstring for MainWindow"""
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # self.widget = FormWidget()
        self._data = {
                'Contact':['Carl Sagan', 2],
                'End of Faith':['Sam Harris', 7],
                'On Mars':['Patrick Moore', 1],

                }
        self.btn = QtGui.QPushButton("Hello", self)
        self.btn.clicked.connect(self._launchMessageBox)

        self.show()

    def _launchMessageBox(self):
        dlg = MessageBox(self._data)
        dlg.exec_()

def main():
    app = QtGui.QApplication(sys.argv)
    window =  MainWindow()
    window.show()
    # window.raise_()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


texts: Reasonable way to implement "safe" math operations using _Generic?

texts:
I've been thinking about a way to make it easier to safely use math operations with C's basic datatypes (e.g. using the CERT C coding standard).  So far, I've come up with something like this:

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

#define safe_add(x, y) _Generic((x + y),                    \
                            unsigned int: safe_add_uint,    \
                           unsigned long: safe_add_ulong    \
                       )(x, y, __FILE__, __LINE__)

unsigned long
safe_add_ulong(unsigned long x, unsigned long y,
               const char* filename, int line_num)
{
    if (x < ULONG_MAX - y)
        return x + y;
    else {
        fprintf(stderr,
                "Integer wrap-around occurred, File: %s, Line: %d\n",
                filename, line_num);
        exit(EXIT_FAILURE);
    }
}

unsigned int
safe_add_uint(unsigned int x, unsigned int y,
              const char* filename, int line_num)
{
    if (x < UINT_MAX - y)
        return x + y;
    else {
        fprintf(stderr,
                "Integer wrap-around occurred, File: %s, Line: %d\n",
                filename, line_num);
        exit(EXIT_FAILURE);
    }
}

int
main()
{
    /*
     *  usual arithmetic conversions results in this calling
     *  the uint version of safe_add...
     */
    safe_add(2000000000, 3000000000u);

    printf("We shouldn't get here...(unless unsigned int uses more than 32 bits)\n");
}

Output of the above would be something similar to:

  Integer wrap-around occurred, File: /.../main.c, Line: 41

and the program exits with a failure code (assuming the OS supports that).

Obviously, additional operations and types need to be added as well as handling signed arithmetic, but are there any problems with this overall method that I may be missing?

Is there perhaps an easier way to write this that I've overlooked?