texts:
I have a procedure for normalizing variables, the details of which can be viewed in this white paper.

I would like to be able to make the routine scalable to handle any number of variables.  Below is the R code for a 4 variable example with a regular correlation coefficient substituted for the preferred nonlinear coefficient (for simplicity and demonstration purposes).  Any insights or comments are appreciated.

VN_Normalization <- function(A1, A2, A3, A4){

#Array1 Scaling Factor
RG_Factor_A1_A2<- mean(A1)/mean(A2)
RG_Factor_A1_A3<- mean(A1)/mean(A3)
RG_Factor_A1_A4<- mean(A1)/mean(A4)

#Array2 Scaling Factor
RG_Factor_A2_A1<- mean(A2)/mean(A1)
RG_Factor_A2_A3<- mean(A2)/mean(A3)
RG_Factor_A2_A4<- mean(A2)/mean(A4)

#Array3 Scaling Factor
RG_Factor_A3_A1<- mean(A3)/mean(A1)
RG_Factor_A3_A2<- mean(A3)/mean(A2)
RG_Factor_A3_A4<- mean(A3)/mean(A4)

#Array4 Scaling Factor
RG_Factor_A4_A1<- mean(A4)/mean(A1)
RG_Factor_A4_A2<- mean(A4)/mean(A2)
RG_Factor_A4_A3<- mean(A4)/mean(A3)

#A1 as Reference Gene
A1_1 <- A1
A2_1 <- A2*RG_Factor_A1_A2*abs((cor(A1,A2)))
A3_1 <- A3*RG_Factor_A1_A3*abs((cor(A1,A3)))
A4_1 <- A4*RG_Factor_A1_A4*abs((cor(A1,A4)))

#A2 as Reference Gene
A1_2 <- A1*RG_Factor_A2_A1*abs((cor(A1,A2)))
A2_2 <- A2
A3_2 <- A3*RG_Factor_A2_A3*abs((cor(A2,A3)))
A4_2 <- A4*RG_Factor_A2_A4*abs((cor(A2,A4)))

#A3 as Reference Gene
A1_3 <- A1*RG_Factor_A3_A1*abs((cor(A1,A3)))
A2_3 <- A2*RG_Factor_A3_A2*abs((cor(A3,A2)))
A3_3 <- A3
A4_3 <- A4*RG_Factor_A3_A4*abs((cor(A3,A4)))

#A4 as Reference Gene
A1_4 <- A1*RG_Factor_A4_A1*abs((cor(A1,A4)))
A2_4 <- A2*RG_Factor_A4_A2*abs((cor(A4,A2)))
A3_4 <- A3*RG_Factor_A4_A3*abs((cor(A4,A3)))
A4_4 <- A4

A1_Normalized <- (A1_1+A1_2+A1_3+A1_4)/4
A2_Normalized <- (A2_1+A2_2+A2_3+A2_4)/4
A3_Normalized <- (A3_1+A3_2+A3_3+A3_4)/4
A4_Normalized <- (A4_1+A4_2+A4_3+A4_4)/4

p = sample(rainbow(10))
boxplot(list(A1,A2,A3,A4,A1_Normalized,A2_Normalized,A3_Normalized,A4_Normalized),
  las=2, names=c("Array1","Array2","Array3","Array4",
  "Array1_Normalized","Array2_Normalized","Array3_Normalized","Array4_Normalized"),
    col=c("white","white","white","white",p,p,p,p))

}


texts: C inner product function without using array subscripting

texts:
As part of a question designed to help us understand the relationship between pointers and arrays in C, I've been asked to write an inner product function that doesn't use any array subscripting. Here's what I came up with, but it looks like the kind of complicated 'clever' coding that we've traditionally been told NOT to write.
Any feedback on it, or how it could be done better / more efficiently would be much appreciated.

int inner_product(const int *a, const int *b, int n) {

    const int *p, *q;
    int result = 0;
    for(p = a, q = b; p < a + n, q < b + n; p++, q++) {
            result += *p * *q;
    }
    return result;
}

Edit - Inner product is simply summing the product of the indexes, so a[1,2,3] b[2,3,4] would be 1*2 + 2*3 + 3*4


texts: Filling a memory segment with a bit pattern

texts:
I want to fill a memory segment with a certain byte pattern using powerpc assembly:

# Task: Fill the area from 0x8000 to (inclusive) 0x8FFF with 0x55 (per byte read/write)

# Write start address - 1 into a register
addis r2, r0, 0x0000
ori r2, r2, 0x7FFF

# Bit pattern is 0x55
addi r3, r0, 0x55

# Size of memory segment + 1
addis r4, r0, 0x0000
ori r4, r4, 0x1000
# Move that length to CTR register
mtctr r4

loop:
#Write pattern from r3 into the address (1 + r2), and write the result of 1 + r2 back into r2
stbu r3, 1(r2)
# decrement CTR and see if we have reached the end of the segment
bdnz


texts: Using Parsec for simple arithmetic language

texts:
I've been reading Types and Programming Languages and I wanted to try to implement the first language in Haskell to understand it properly

I have barely written any Haskell before and not used Parsec so I would grateful for any feedback on this code

Here are some specific points I am unsure about

Is my main function sensible?
Can the eval function be expressed any better?
I'm unhappy with functionParser and ifParser. How can I code these better. In particular can the ifParser be coded in an applicative style?

If there's anything else you consider odd don't hesitate to mention it

import Control.Monad
import System.Environment
import Text.ParserCombinators.Parsec

data Term = TmTrue
          | TmFalse
          | TmIf Term Term Term
          | TmZero
          | TmSucc Term
          | TmPred Term
          | TmIsZero Term
          | TmError
    deriving Show

main :: IO[()]
main = do
    args <- getArgs
    forM args (\arg -> case parseArith arg of
                Left e -> print e
                Right term -> print $ eval term)

isNumerical :: Term -> Bool
isNumerical term = case term of
    TmZero -> True
    TmSucc subterm -> isNumerical subterm
    TmPred subterm -> isNumerical subterm
    _ -> False

eval :: Term -> Term
eval term = case term of
    TmTrue -> TmTrue
    TmFalse -> TmFalse
    TmZero -> TmZero
    TmIf term1 term2 term3 -> case eval term1 of
        TmTrue -> eval term2
        TmFalse -> eval term3
        _ -> TmError
    TmIsZero subterm -> case eval subterm of
        TmZero -> TmTrue
        t2 | isNumerical t2 -> TmFalse
        _ -> TmError
    TmPred TmZero -> TmZero
    TmPred (TmSucc subterm) -> eval subterm
    TmSucc subterm -> case eval subterm of
        t2 | isNumerical t2 -> TmSucc t2
        _ -> TmError
    _ -> TmError

parseArith :: String -> Either ParseError Term
parseArith input = parse arithParser "Failed to parse arithmetic expression" input

arithParser :: GenParser Char st Term
arithParser = try( ifParser )
          <|> try( succParser )
          <|> try( predParser )
          <|> try( isZeroParser )
          <|> try( trueParser )
          <|> try( falseParser )
          <|> try( zeroParser )

trueParser :: GenParser Char st Term
trueParser = string "true" >> return TmTrue

falseParser :: GenParser Char st Term
falseParser = string "false" >> return TmFalse

zeroParser :: GenParser Char st Term
zeroParser = char '0' >> return TmZero

functionParser :: String -> (Term -> Term) -> GenParser Char st Term
functionParser name funcTerm = do
    string $ name ++ "("
    term <- arithParser
    char ')'
    return $ funcTerm term

succParser :: GenParser Char st Term
succParser = functionParser "succ" TmSucc

predParser :: GenParser Char st Term
predParser = functionParser "pred" TmPred

isZeroParser :: GenParser Char st Term
isZeroParser = functionParser "iszero" TmIsZero

ifParser :: GenParser Char st Term
ifParser = do
    string "if"
    spaces
    term1 <- arithParser
    spaces
    string "then"
    spaces
    term2 <- arithParser
    spaces
    string "else"
    spaces
    term3 <- arithParser
    return $ TmIf term1 term2 term3


texts: Project Euler #58: Primes along the diagonals of a square spiral

texts:
I am working on Project Euler Problem 58:

  Starting with 1 and spiralling anticlockwise in the following way, a
  square spiral with side length 7 is formed.

37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18  5  4  3 12 29
40 19  6  1  2 11 28
41 20  7  8  9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49

  It is interesting to note that the odd squares lie along the bottom
  right diagonal, but what is more interesting is that 8 out of the 13
  numbers lying along both diagonals are prime; that is, a ratio of 8/13
  ≈ 62%.

  If one complete new layer is wrapped around the spiral above, a square
  spiral with side length 9 will be formed. If this process is
  continued, what is the side length of the square spiral for which the
  ratio of primes along both diagonals first falls below 10%?

My code gives the correct answer, but it takes a very long time to do it, even while using Pypy, a JIT compiler.

I would like to know some good ways to increase my efficiency in this problem.

import random
def m_r(n):
    d = n - 1
    s = 0
    while d % 2 == 0:
        d >>= 1
        s += 1
    for repeat in range(20):
        a = 0
        while a == 0:
            a = random.randrange(n)
        if not miller_rabin_pass(a, s, d, n):
            return False
    return True

def miller_rabin_pass(a, s, d, n):
    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in range(s-1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1

def eraSieve(n):
    sieve=[True]*(n+1)
    sieve[:2] = [False, False]
    sqrt = int(n**.5)+1
    for x in xrange(2, sqrt):
        if sieve[x]:
            sieve[2*x::x]=[False]*(n/x-1)
    return sieve

def diagonalNum(n): # n is the number of row
    increment = 2
    getDiaNum = 1
    limit = (n-1)/2
    sideLen = 1.0
    c = 0.0
    for i in xrange(1, limit + 1):
        count = 1
        while count <= 4:
            getDiaNum += increment
            if m_r(getDiaNum):
                c += 1
            count += 1
        increment += 2
        sideLen += 4
    return c / sideLen

for x in xrange(1, 100000):
    ratio = diagonalNum(x)
    print x
    if ratio < 0.10:
        break
print x


texts:
Can this function be cleaner? It looks to me that I have too much nesting (Using + If + While).

Public Shared Function GetLocationsAutocomplete(ByRef userData As IUser, ByVal prefix As String) As List(Of AutocompleteItem)
    Dim conn As DbConnection = DbProvider.GetDbConnection(ConnectionStringHelper.GetConnectionString(userData))
    Dim retValue As List(Of AutocompleteItem) = Nothing

    Const SQL As String = " SELECT DISTINCT TOP 20 Location " & _
                          " FROM userdetailstable WHERE ClientID=@ClientID " & _
                          " AND Location IS NOT NULL AND LEN(Location) > 0 AND Location LIKE @Filter "
    Try
        conn.Open()
        Logger.WriteConnectionInfo("UserDataAccess.GetLocationsAutocomplete", Logger.ConnectionActionType.Opened)

        ' Getting data from DB:
        Using cmd As DbCommand = DbProvider.GetDbCommand(SQL, conn)
            cmd.Parameters.Add("@ClientID", DbType.Int32).Value = userData.ClientID
            cmd.Parameters.Add("@Filter", DbType.String).Value = String.Format("%{0}%", prefix)
            Using reader As DbDataReader = cmd.ExecuteReader()
                If reader.HasRows Then
                    retValue = New List(Of AutocompleteItem)
                    ' Populate retValue list with project names:
                    Dim item As AutocompleteItem = Nothing
                    While reader.Read()
                        item = New AutocompleteItem()
                        item.Value = reader.GetString("Location")
                        item.Label = item.Value
                        retValue.Add(item)
                    End While
                End If
            End Using
        End Using
    Finally
        conn.Close()
        conn.Dispose()
        Logger.WriteConnectionInfo("SearchDataAccess.GetLocationsAutocomplete", Logger.ConnectionActionType.Closed)
    End Try

    Return retValue

End Function


texts:
Here is a custom Random<T> class which could be used as:

Random<int> random = Random<int>(10);
int zeroToTen = random.Next();

I also made it seedable through the ambient context, so the following is observed allowing to potentially have Seed anywhere above in the call stack to simplify unit testing:

Random<int> Numbers { get; } = new Random<int>(10);

[TestMethod]
public void Seed_With_Seed_Value()
{
    int[] a, b;
    using (new Seed("Numbers", 33))
        a = new[] { Numbers.Next(), Numbers.Next(), Numbers.Next(), Numbers.Next() };
    using (new Seed("Numbers", 33))
        b = new[] { Numbers.Next(), Numbers.Next(), Numbers.Next(), Numbers.Next() };

    CollectionAssert.AreEqual( a, b);
}

[TestMethod]
public void Seed_With_Sequence()
{
    using (new Seed("Numbers") { 1, 2, 3 })
    {
        Assert.AreEqual(1, Numbers.Next());
        Assert.AreEqual(2, Numbers.Next());
        Assert.AreEqual(3, Numbers.Next());
    }
}

where library code is:

public class Random<T>
{
    public Random(T max, [CallerMemberName] string name = null)
    {
        Max = max;
        Name = name;
    }

    T Max { get; }
    string Name { get; }
    public T Next() =>
        (T)Convert.ChangeType(
            Seed.Of(Name).Next(Convert.ToDouble(Max)),
            typeof(T));
}

and:

public class Seed : IEnumerable, IDisposable
{
    static AsyncLocal<Seed> Context { get; } = new AsyncLocal<Seed>();
    static Seed Default { get; } = new Seed();
    public static Seed Of(string name)
    {
        for (var c = Context.Value; c != null; c = c.Parent)
            if (c.Name == name)
                return c;

        return Default;
    }

    Seed()
    {
        Value = null;
        Sequence = new ConcurrentQueue<double>();
        Random = new Random();
    }

    public Seed(string name, int? value = null)
    {
        Name = name;
        Value = value;
        Parent = Context.Value;
        Context.Value = this;
        Sequence = new ConcurrentQueue<double>();
        Random = value == null
            ? new Random()
            : new Random(value.Value);
    }

    public void Dispose() => Context.Value = Parent;

    Seed Parent { get; }
    string Name { get; }
    int? Value { get; }
    ConcurrentQueue<double> Sequence { get; }
    Random Random { get; }
    public void Add(double next) => Sequence.Enqueue(next);
    public double Next(double max) =>
        Sequence.TryDequeue(out var value) ? value :
        Random.NextDouble() * max;

    public IEnumerator GetEnumerator() =>
        Sequence.GetEnumerator();
}


texts:
I've made a small function to output a multiplication grid (those things from primary school! :P) to an inputted number.

def make_grid(max):
    max += 1  # so the for loops go up to the desired number, inclusive
    print('X\t' + '\t'.join([str(_) for _ in range(max)]) + '\n')  # print all the numbers hoizontally
    for i in range(max):
        print(i, end="\t")  # print the vertical column of base numbers
        for x in range(max):
            print(str(i*x), end="\t")  # multiply the two numbers
        print('\n')

if __name__ == "__main__":
    try:
        max = int(input("Max Number? "))
        make_grid(max)
    except ValueError:
        print("Please enter a number!")

Choosing a max number of 5 (make_grid(5)) would output:

X 0   1   2   3   4   5

0 0   0   0   0   0   0

1 0   1   2   3   4   5

2 0   2   4   6   8   10

3 0   3   6   9   12  15

4 0   4   8   12  16  20

5 0   5   10  15  20  25

I'm looking for any improvements I could make, especially the \t's - as I use them to line up the numbers, but the gap gets pretty big, unnecessarily.


texts:
can anyone give me advice on how i can make my code more compact and efficient, and if you can, an implementation using OOP? Since, i just started learning Object Oriented Programming and it looks real hard.

def Hangman(): # for MENU
    print("H A N G M A N")
    while True:
        choice = input('Type "play" to play the game, "exit" to quit: ')
        if choice == "play":
            hint("option")
            play_game()
        if choice == "exit":
            break

def play_game(): # FOr game mechanics
    import random
    my_list = ['python', 'java', 'kotlin', 'javascript']
    # WORD CHOICES
    global lives, chosen_word, changed_word, changed_list, hidden_word, hidden_list
    lives = 8
    winner = False
    chosen_word = random.choice(my_list)
    changed_word = chosen_word[:]
    hidden_word = (len(chosen_word))*"-"
    hidden_list = list((len(chosen_word))*"-")
    changed_list = [char for char in changed_word]

    while lives != 0:
        guess = "-"
        print('\n', hidden_word, sep="") # gives the word every guess

        while True:
            guess = input("Input a letter: ")
            if len(guess) != 1:
                print("You should print a single letter\n")
                continue
            if guess != guess.lower() or not guess.isalpha():
                print("It is not an ASCII lowercase letter\n")
                continue
            break

        if guess not in changed_word:
            if guess in chosen_word:
                print('You already typed this letter')
                continue

            else:
                print("No such letter in the word")
                lives -= 1
                hint("check_lives")

        else:
            letter_found_count = chosen_word.count(guess)

            for _ in range(letter_found_count):
                indexfound = changed_word.find(guess)
                hidden_list[indexfound] = guess
                changed_list[indexfound] = "-"
                hidden_word = "".join(hidden_list)
                changed_word = "".join(changed_list)

        if hidden_word == chosen_word:
            print("\n%s\nYou guessed the word!\nYou survived!" % hidden_word)
            winner = True
            break

    if not winner:
        print("You are hanged!")
    if hint_count > 1:
        print(f"Though you used {str(hint_count)} hints")
    print()

def hint(setting):
    if setting == "game":
        global chosen_word, changed_word, changed_list, hidden_word, hidden_list
        for _ in range(len(changed_list)):
            guess = changed_list[_]
            if guess != "-":
                letter_found_count = chosen_word.count(guess)
                for _ in range(letter_found_count):
                    indexfound = changed_word.find(guess)
                    hidden_list[indexfound] = guess
                    changed_list[indexfound] = "-"
                    hidden_word = "".join(hidden_list)
                    changed_word = "".join(changed_list)

                return changed_word, hidden_word, changed_list, hidden_list

    if setting == "option":
        global hint_flag, hint_count
        hint_count = 0
        while True:
            choice = input("With Hints? 'Yes' or 'No': ")
            if choice.lower() == "yes":
                hint_flag = True
                break
            elif choice.lower() == "no":
                hint_flag = False
                break

    if setting == "check_lives":
        if lives != 0:
            if lives < 5: # HINT CONDITION
                if hint_flag:
                    while True:
                        choice = input("For hint, answer: 'yes' or 'no': ")
                        if choice.lower() == "yes":
                            changed_word, hidden_word, changed_list, hidden_list = hint("game")
                            hint_count += 1
                            break
                        elif choice.lower() == "no":
                            break

Hangman()
```


texts:
I need help making this code run faster.  I am using it to import a CSV file into Excel. It works, but it is very slow. The file is almost 20MB.

{Sub OpenTextFile()

Dim FilePath As String
Dim linitem As Variant
FilePath = "filepath.txt"
Open FilePath For Input As #1
row_number = 0
Do
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, "|")

ActiveCell.Offset(row_number, 30).Value = LineItems(0)
ActiveCell.Offset(row_number, 29).Value = LineItems(1)
ActiveCell.Offset(row_number, 28).Value = LineItems(2)
ActiveCell.Offset(row_number, 27).Value = LineItems(3)
ActiveCell.Offset(row_number, 26).Value = LineItems(4)
ActiveCell.Offset(row_number, 25).Value = LineItems(5)
ActiveCell.Offset(row_number, 24).Value = LineItems(6)
ActiveCell.Offset(row_number, 23).Value = LineItems(7)
ActiveCell.Offset(row_number, 22).Value = LineItems(8)
ActiveCell.Offset(row_number, 21).Value = LineItems(9)
ActiveCell.Offset(row_number, 20).Value = LineItems(10)
ActiveCell.Offset(row_number, 19).Value = LineItems(11)
ActiveCell.Offset(row_number, 18).Value = LineItems(12)
ActiveCell.Offset(row_number, 17).Value = LineItems(13)
ActiveCell.Offset(row_number, 16).Value = LineItems(14)
ActiveCell.Offset(row_number, 15).Value = LineItems(15)
ActiveCell.Offset(row_number, 14).Value = LineItems(16)
ActiveCell.Offset(row_number, 13).Value = LineItems(17)
ActiveCell.Offset(row_number, 12).Value = LineItems(18)
ActiveCell.Offset(row_number, 11).Value = LineItems(19)
ActiveCell.Offset(row_number, 10).Value = LineItems(20)
ActiveCell.Offset(row_number, 9).Value = LineItems(21)
ActiveCell.Offset(row_number, 8).Value = LineItems(22)
ActiveCell.Offset(row_number, 7).Value = LineItems(23)
ActiveCell.Offset(row_number, 6).Value = LineItems(24)
ActiveCell.Offset(row_number, 5).Value = LineItems(25)
ActiveCell.Offset(row_number, 4).Value = LineItems(26)
ActiveCell.Offset(row_number, 3).Value = LineItems(27)
ActiveCell.Offset(row_number, 2).Value = LineItems(28)
ActiveCell.Offset(row_number, 1).Value = LineItems(29)
ActiveCell.Offset(row_number, 0).Value = LineItems(30)

row_number = row_number + 1
Loop Until EOF(1)

Close #1
End Sub

}


texts: Data profiling in a dataframe based on an input file-pandas

texts:
I have a data file and a rules file. First column of rules file will have columns from the data file and the second column has an pandas operation which has to be performed on the respective Column. Please refer below details:

This is the input data:

d={'Name': ['Ankan', 'Shiv', nan, 'Sandeep'],
'email': ['ankan@domain.com', 'shiv.com', 'something@someting.com', 'sandeep@domain.com'],
'Street 1': ['Street Name 1', 'Street name 2', 'Street name 3', nan],
'LastName': [nan, nan, 'LastName1', 'LastName2'],
'Outlet_Code': ['123abc', nan, 12345, 'bca12']}
df= pd.DataFrame(d)

Which looks like:

      Name                   email       Street 1   LastName Outlet_Code
0    Ankan        ankan@domain.com  Street Name 1        NaN      123abc
1     Shiv                shiv.com  Street name 2        NaN         NaN
2      NaN  something@someting.com  Street name 3  LastName1       12345
3  Sandeep      sandeep@domain.com            NaN  LastName2       bca12

Now the rules file:

d1={'Column_Name': ['Name', 'LastName'], 'Rule': ['.isna()', '.isna()']}
file_rules=pd.DataFrame(d1)

  Column_Name     Rule
0        Name  .isna()
1    LastName  .isna()

I am trying to flag the cells in excel where the condition matches per column name. I have a working code which is :

m=df.eval([f'{a}{b}' for a,b in zip(file_rules['Column_Name'],file_rules['Rule'])])
cond=pd.DataFrame(m,index=file_rules['Column_Name'].to_numpy()).T

def dummy_color(x):
    c1='background-color:red'
    c2=''
    df1 = pd.DataFrame(np.where(cond,c1,c2),columns=x.columns,index=x.index)
    return df1
df.style.apply(dummy_color,axis=None,subset=file_rules.Column_Name)

Output:

I want to know if there is any better way of doing this,(since this would be handled by someone else)? Can I do this without df.eval()? Kindly suggest.


texts:
public static class StringHelpers
{
    public static string CapitalizeEachWord(this string sentence)
    {
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;

        if (String.IsNullOrEmpty(sentence))
        {
            return String.Empty;
        }

        return textInfo.ToTitleCase(sentence);
    }

    public static string CapitalizeFirstWord(this string sentence)
    {
        if (String.IsNullOrEmpty(sentence))
        {
            return String.Empty;
        }

        var words = sentence.Split();
        StringBuilder resultBuilder = new StringBuilder();

        var letters = words[0].ToCharArray();
        List<string> lettersHolder = new List<string>();
        lettersHolder.Add(letters[0].ToString().ToUpper());
        for (int i = 1; i < letters.Length; i++)
        {
            lettersHolder.Add(letters[i].ToString().ToLower());
        }

        foreach (var letter in lettersHolder)
        {
            resultBuilder.Append(letter);
        }

        resultBuilder.Append(" ");

        for (int i = 1; i < words.Length; i++)
        {
            resultBuilder.Append(words[i].ToLower());
            resultBuilder.Append(" ");
        }

        return resultBuilder.ToString();
    }
}

The first method, is supposed to correctly capitalize each word in a sentence. I don't think there's much room for improvement in that one.

The second method, seems a little confusing and even after I've written it and tested it, I cannot seem to fully put what it's doing into my buffer. That's a sign of code smell.

If I kinda get it now, what will happen down the line when I have to change it or something.


texts: Get resulting rectangle from two overlapping rectangles

texts:
I have a function that creates a rectangle from two rectangles that overlap, I was wondering if there is a smarter way to do it purely mathematically rather than lots of if statements to check min and max the way I currently have setup.

This is my function

    public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();
        //they don't overlap
        if (!a.Intersects(bounds)) return false;

        float minX;
        float maxX;
        float minZ;
        float maxZ;

        if (a.min.x > bounds.min.x)
            minX = a.min.x;
        else
            minX = bounds.min.x;

        if (a.max.x < bounds.max.x)
            maxX = a.max.x;
        else
            maxX = bounds.max.x;

        if (a.min.z > bounds.min.z)
            minZ = a.min.z;
        else
            minZ = bounds.min.z;

        if (a.max.z < bounds.max.z)
            maxZ = a.max.z;
        else
            maxZ = bounds.max.z;

        // using XZ plane for debug
        Vector3 min = new Vector3(minX,0,minZ);
        Vector3 max = new Vector3(maxX,0,maxZ);
        result.SetMinMax(min,max);
        return true;
    }

Here it is in action


texts:
I have produced a working menu component for a project I'm working on, but would like to reduce the amount of code used and improve the methods - especially in the Paint implementation - still further, I feel like the function I've used and the way I've passed the variables to it is a bit 'hacky' - IOW, I bodged it.

What methods could I use to increase the amount of encapsulation used in the drawing routine so I'm not defining variables in the Paint routine? The y2 variable in particular is irritating.

These are my drawing function and paint routine:

// Rectangle drawing function
Function DrawRect(cv : TCanvas; x1, y1, x2, y2, chR, clR, i : integer; txts : AnsiString; Lrect : TRect) : TRect;
begin
  with cv do begin
    // Test against Rect variables to set colour
    if (chR = i) and (clR = -1) then
      Brush.color := stateColor[bttn_on]
    else if (chR = i) and (clR = i) then
      Brush.color := stateColor[bttn_dwn]
    else
      Brush.color := stateColor[bttn_off];

    // Define Link Rectangle
    Lrect := Rect(x1, y1, x2, y2*(i+1));

    // Draw Rectangle
    Rectangle(Lrect);

    // Add text
    TextRect(Lrect, x1+5,  y1+5, txts);

    // Return co-ordinates of drawn rectangle as function result
    result := Lrect;
  end;
end;

// Canvas painting
procedure TOC_MenuPanel.Paint;
var
  y1, x2, y2, count : Integer;
begin
  inherited Paint;
  // Set length of array
  SetLength(MenuRects, fLinesText.Count);

  // Define Y1,Y2
  x2 := Width - Width div 20;
  y1 := Width div 20;

  with Canvas do begin
  // Draw outerRectangle outside of For loop
  Brush.color := clMenu;
  Rectangle(0, 0, Width, Height);

  // Loop for drawing menu items
  if fLinesText.Count = 0 then exit
  else
    for count := 0 to fLinesText.Count - 1 do begin
      // Define Y2
      y2 := TextHeight(fLinesText.strings[count])*2;

      // Cast rectangle draw function results to array for Mouse actions & draw rectangle
      MenuRects[count] := DrawRect(Canvas, 10, y1, x2, y2, chosenRect, clickedRect, count, fLinesText.strings[count], MenuRects[count]);

      // inc y1 for positioning the next box
      y1 := y1+y2;
    end;
  end;
end;


texts:
There is Three Validation Group A,B and No Group.

How to get validation result of only the specific validation group.

If Group A and No Group is not valid but all of group B is valid, i would like to get result as valid.

I have read the article validation in depth but don't find the straightforward solution.
http://msdn.microsoft.com/en-us/library/aa479045.aspx

Is there any simpler solution than this

    protected bool IsGroupB_Valid()
    {
        var validators = Page.GetValidators("B");

        foreach (IValidator item in validators)
        {
            if(item.IsValid == false)
            return false;
        }
        return true;
    }


texts:
I have implemented a simple iterator. Just want to check if I have missed anything.

interface iterator<E>
    {
        boolean hasNext();

        E next();
    }

    class Iterator<E> implements iterator
    {
        E[] arr;

        int curPos = 0;

        @Override
        public boolean hasNext()
        {
            if (curPos >= arr.length || arr[curPos] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        @Override
        public E next()
        {
            if(hasNext())
            {
                E res = arr[curPos];
                curPos++;
                return arr[curPos+1];
            }
            else
            {
                throw new runtimeException("No next element available !");
            }
        }

    }

Questions:

Why should I not use Object instead of E/template everywhere ?
How do I make an iterator for a binary tree.

I assume apart from the above, I would have to implement a traversal algorithm and try to find if the next "traversal" successor exist?


texts:
I am relearning C so if you could point obvious faults in this solution to this problem I'd greatly appreciate such comments. Please note that I'm using GCC extensions to use larger than 32 bit numbers. Most importantly I want to be aware of the quality of memory management in particular.

http://news.ycombinator.com/item?id=3429466

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

int64_t* next_pascal_row(int64_t* previous_row, int64_t previous_size)
{
  int64_t i;
  int64_t* retval;
  retval = (int64_t*)malloc(sizeof(int64_t)*(previous_size+1));
  for (i=0;i<previous_size+1;i++) {
    if (i==0 || i == previous_size) {
      retval[i] = 1;
    } else {
      retval[i] = previous_row[i-1] + previous_row[i];
    }
  }
  return retval;
}

void print_row(int64_t* row, int64_t size)
{
  int64_t i;
  for(i = 0; i < size; i++) {
    printf("%lld ",row[i]);
  }
  printf("\n");
}

int main()
{
  int64_t* first_row;
  int64_t* previous_row;
  int64_t* next_row;
  int64_t i,size;
  first_row = (int64_t*)malloc(sizeof(int64_t));
  first_row[0] = 1;
  size = 1;
  print_row(first_row,size);
  previous_row = first_row;
  for(i = 0; i<31;i++) {
    next_row = next_pascal_row(previous_row,size);
    size++;
    print_row(next_row,size);
    free(previous_row);
    previous_row = next_row;
  }
  free(next_row);
  return 0;
}


texts: Longest common substring approach using suffix arrays

texts:
I am trying to speed up a function to return the longest common substring.

The requirements:

The function takes two strings of arbitrary length (although on average they will be less than 50 chars each)
If two subsequences of the same length exist it can return either
Speed is the primary concern

This is what I have and it works according to my tests:

from os.path import commonprefix

class LongestCommonSubstr(object):

    def __init__(self, lstring, rstring):
        self.lstring = lstring+'0'
        self.rstring = rstring+'1'
        self._suffix_str_array = sorted(self._get_suffix_str(self.lstring)
                                    + self._get_suffix_str(self.rstring))
        self.longest_common_substr = self._get_lcsubstr()

    @staticmethod
    def _get_suffix_str(string):

        return [string[i:] for i in range(len(string))]

    def _get_lcsubstr(self):

        try:
            substr_len =0
            max_len = 0
            lcs = None
            for i,n in enumerate(self._suffix_str_array):
                if n[-1] != self._suffix_str_array[i+1][-1]:
                    substr = commonprefix([n,self._suffix_str_array[i+1]])
                    substr_len = len(substr)
                    if substr_len > max_len:
                        max_len = substr_len
                        lcs = substr

        except IndexError:
            pass
            return lcs

Can the code be made faster in pure Python? Is there a better option to differentiate the input strings when made into one sorted list than concatenating an ID to them?


texts: Why does my function think that "uiouioiu"is a plaindrome?

texts:
I was reading Introduction to Computation and Programming using Python and there in an exercise, we had to write a function which would tell us if a given word is a palindrome or not, recursively.

This is the code which I wrote:

word = input()

def isPalindrome(x):
    if len(x) > 1:
        if x[0] == x[-1] and isPalindrome(x[1:-1]):
            return('The word is Plaindrome.')
        else:
            return('It is not.')
    else:
        return(True) #As this is a base case.

print(isPalindrome(word))

This seems to work for all the words I pass into it except uiouioiu.
isPalindrome(uiouioiu) returns The word is Palindrome.

Could someone explain what is happening?

EDIT 1: If I modify the code to:

word = input()

def isPalindrome(x):
    if len(x) > 1:
        if x[0] == x[-1] and isPalindrome(x[1:-1]):
            return(True)
        else:
            return(False)
    else:
        return(True) #As this is a base case.

print(isPalindrome(word))

isPalindrome(uiouioiu) returns False as expected. Why is this happening?


texts: Programmatically getting the GUID of an application

texts:
Intrigued by the events chronicled here (also here and here), I saw the inherent utility in having a program-specific GUID available. The SO answers that were correct seemed a bit tightly-coupled and verbose. So I set out to make my own for use. Looking for a critique on the idea itself as well as maintainability, performance, etc. Improvements welcome.

public static class AssemblyExtensions
{
    /// <summary>
    /// The <see cref="GuidAttribute"/> for the entry assembly lazily gotten as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    private static readonly Lazy<Guid> _MyGuid = new Lazy<Guid>(() => Assembly.GetEntryAssembly().GetGuid());

    /// <summary>
    /// Lazily gets the <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    /// <returns>The <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.</returns>
    public static Guid GetMyGuid() => _MyGuid.Value;

    /// <summary>
    /// Gets the <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    /// <param name="assembly">The assembly.</param>
    /// <returns>The <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.</returns>
    public static Guid GetGuid(this Assembly assembly) => Guid.TryParse(
        ((GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault())?.Value,
        out Guid guid) ? guid : Guid.Empty;
}


texts: Java homework exercises working with 2D arrays

texts:
For an assignment to study up on an incoming exam, I have to make these little functions. These are review style functions that make sure we know the algorithms and code necessary to do well on the test. I'm looking for anything I can improve upon in my code, so I can get the best grade possible.

  Write a method called evens that will receive a 2-D array of integers and return the sum of all the even integers in the array.

public int evens(int[][] arr) {
    int sum = 0;
    for(int[] row : arr) {
        for(int item : row) {
            if(item % 2 == 0) {
                sum += item;
            }
        }
    }
    return sum;
}

  Write a method called check that will receive a 2-D array of String and a single letter (character). The method will return true if any of the strings start with the letter that is passed in (ignoring cases)

public boolean check(String[][] arr, char c) {
    for(String[] row : arr) {
        for(String item : row) {
            if(item.charAt(0) == c) {
                return true;
            }
        }
    }
    return false;
}

  Write a method called getColumn which receives a 2-D array of doubles, and an integer parameter n. The method returns a one-dimensional array which contains the elements in the nth column of the 2-D array.

public double[] getColumn(double[][] arr, int col) { // row by column
    double[] newarr = new double[arr.length];
    for(int i = 0; i < arr.length; i++) {
        newarr[i] = arr[i][col];
    }
    return newarr;
}

  Write a method called populate that takes two parameters, m and n. The method creates and returns an m x n matrix filled with the counting numbers in row-major order starting with one.

public int[][] populate(int m, int n) {
    int[][] arr = new int[m][n];
    int count = 1;
    for(int i = 0; i < arr.length; i++) {
        for(int j = 0; j < arr[i].length; j++) {
            arr[i][j] = count;
            count++;
        }
    }
    return arr;
}

My tester class (test.java)

import java.util.Arrays;

public class test {

    public static void main(String[] args) {

        test t = new test();
        int[][] array = {
            {1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10}
        };
        String[][] array2 = {
            {"abc", "def", "ghi"},
            {"jkl", "lmn", "opq"},
            {"rst", "uvw", "xyz"}
        };
        double[][] array3 = {
            {1.1, 1.2, 1.3, 1.4, 1.5},
            {1.6, 1.7, 1.8, 1.9, 2.0},
            {2.1, 2.2, 2.3, 2.4, 2.5},
            {2.6, 2.7, 2.8, 2.9, 3.0}
        };
        System.out.println("30 => " + t.evens(array));
        System.out.println();
        System.out.println("true => " + t.check(array2, 'd'));
        System.out.println();
        System.out.println("[1.1, 1.6, 2.1, 2.6] => " + Arrays.toString(t.getColumn(array3, 0)));
        System.out.println();
        System.out.println(Arrays.deepToString(t.populate(2, 5)));
    }
}


texts:
The tweepy.models.Status class creates a 'tweet' object, it has attribute .created_at which is the posting time of the tweet in the form of Python datetime object.

Here is the case, I have a function time_distribution(tweets, **kwargs) which calculates the distribution of the tweets by time. The function is at the end of this post.

Here is an example implementation, we may use the samples from statistweepy which is about 3000 tweets of @CocaCola_ID twitter account, stored in a .npy file. Each 'tweet' is a tweepy.models.Status object.

Example:

import numpy
import matplotlib.pyplot as plt

data = list(numpy.load('CocaCola_ID_3093samples_hour_min_21_50_date_24_6_2018.npy'))

dist_only = time_distribution(data, unit = 'hour')
print(dist_only)

fig, ax = plt.subplots(1, 1)
dist_and_plot = time_distribution(data, cont_hist = (ax, 20), unit = 'hour')
plt.show()

With argument cont_hist = (ax, n), the function also returns a histogram with n number of bins to be plotted on top of ax.

My question :

How to write it better? (sustainable, convenience, readable, compact)
How to optimize the performance?

import operator
import itertools

def time_distribution(tweets, unit = 'hour', output = 'frequency', cont_hist = False):

    if not any([unit == 'year', unit == 'month', unit == 'day', unit == 'hour']):
        raise AssertionError(' The argument unit must be one of \'year\',  \'month\',  \'day\', or \'hour\'. ')

    unicity_key = operator.attrgetter('created_at.'+unit)
    tweets = sorted(tweets, key=unicity_key)
    distribution = {}

    for time, time_tweets in itertools.groupby(tweets, key=unicity_key):

        time_tweets = list(time_tweets)

        if output == 'frequency':

            distribution[time] = len(time_tweets)
            fy = lambda x: x

        elif output == 'tweets':

            distribution[time] = time_tweets
            fy = lambda x: len(x)

        else:

            raise AssertionError(' The argument output must be either \'frequency\', or \'tweets\'. ')

    if cont_hist:

        axes = cont_hist[0]

        if unit == 'year':

            xt = [tweet.created_at.year + (tweet.created_at.month + (tweet.created_at.day + tweet.created_at.hour/24)/30)/12 for tweet in tweets]

        elif unit == 'month':

            xt = [(tweet.created_at.month + (tweet.created_at.day + tweet.created_at.hour/24)/30) for tweet in tweets]

        elif unit == 'day':

            xt = [(tweet.created_at.day + tweet.created_at.hour/24) for tweet in tweets]

        elif unit == 'hour':

            xt = [tweet.created_at.hour + (tweet.created_at.minute + tweet.created_at.second/60)/60 for tweet in tweets]

        a = int(min(xt)) + 1
        b = int(max(xt)) + 1

        ticks = range(a-1, b+2)

        histogram = axes.hist(xt, bins = cont_hist[1])
        axes.set_xticks(ticks)
        axes.set_xticklabels([str(i) for i in ticks])
        axes.set_xlabel(unit)
        axes.set_ylabel('frequency')

        return distribution, histogram

    return distribution

Plot result :


texts:
So I have a Know Your Customer provider interface like this to estimate risks associated with a customer:

public interface IRiskProvider
{
    string Name { get; }
    Task<Risk[]> FindRisksAsync(Customer customer);
}

And I would like to be able to create an instance of it from a delegate as well as intercept all the calls to the instance:

public static class RiskProvider
{
    public static IRiskProvider Create(string name, Func<Customer, Task<Risk[]>> actionAsync) =>
        new Relay(name, actionAsync);

    public static IRiskProvider Subscribe(this IRiskProvider provider, Func<Customer, Risk[], Task> actionAsync) =>
        Create(provider.Name, async customer =>
        {
            var risks = await provider.FindRisksAsync(customer);
            await actionAsync(customer, risks);
            return risks;
        });

    class Relay : IRiskProvider
    {
        public Relay(string name, Func<Customer, Task<Risk[]>> actionAsync) =>
            (Name, ActionAsync) =
            (name, actionAsync);

        public string Name { get; }
        Func<Customer, Task<Risk[]>> ActionAsync { get; }
        public async Task<Risk[]> FindRisksAsync(Customer customer) =>
            await ActionAsync(customer);
    }
}

An example consumption code would be this Throttler implementing circuit breaker decorator factory:

using IHistory = IHistory<(string Provider, long UserId), (Customer Customer, Risk[] Risks)>;

[Service]
public class Throttler : IThrottler
{
    public Throttler(IHistory history) => History = history;
    IHistory History { get; }

    public IRiskProvider Throttle(IRiskProvider provider, int attempts) =>
        RiskProvider
            .Create(provider.Name, async customer =>
            {
                var calls = await History.ReadAsync((provider.Name, customer.UserId), last: attempts);
                var tooMany = calls.Length == attempts;
                return
                    tooMany ? UnknownRisk.ServiceThrottled :
                    await provider.FindRisksAsync(customer);
            })
            .Subscribe((customer, risks) =>
                History.WriteAsync((provider.Name, customer.UserId), (customer, risks)));
}

Which uses a generic NoSql repository to write/read multiple values per a key:

public interface IHistory<TKey, TValue>
{
    Task WriteAsync(TKey key, TValue value);
    Task<(DateTime At, TValue Value)[]> ReadAsync(TKey key, int last = 1);
}

Does the Subscribe method name sounds reasonable here? Would you expect a subscription in the form of IDisposable being returned from it instead of subscribed instance suitable for chaining? What would be a better name instead of Subscribe for such an API to intercept all the calls?

It just looks like some mix between IEnumerable and IObservable for me. Would some simple ForEach be better?


texts:
As part of an assignment for college summer classes, I was tasked with writing a program that solves roots of negative numbers. I've ran it through the test cases I was provided and it computes correctly. I'm looking for any feedback, especially about the determine_factors function, which really should be renamed. It looks messy and I don't like it, but it's all I could come up with. I'll be tweaking it since it's not due for a while, but I wanted to get some experienced eyes on this.

"""
Helper tool for solving negative square roots.

@author Ben Antonellis
@date 06-08-2020
"""

from math import isqrt

from typing import List, Union, Tuple

def is_perfect(number: int) -> bool:
    """
    Returns if a number is a perfect square.
    """
    return number == isqrt(number) ** 2

def get_factors(number: int) -> List[List[int]]:
    """
    Returns all the factors of a number.
    """
    factors = [[x, number // x] for x in range(2, number + 1) if number % x == 0]
    factors = factors[:len(factors) // 2] # Removes duplicates and any [1, x] pairs #
    return factors

def determine_factors(factors: List[int], num: int) -> str:
    """
    Determines what factors are left at the end of calculation.
    """
    simplified, remainder = 0, 0
    for number, times_in_number in factors:
        if number == times_in_number:
            return f"{number}i"
        if get_factors(number) == [] and get_factors(times_in_number) == []:
            return f"√({num})i"
        if is_perfect(number):
            simplified += isqrt(number)
            if not is_perfect(times_in_number):
                if get_factors(times_in_number) == [] or not any(is_perfect(x) or is_perfect(y) for [x, y] in get_factors(times_in_number)):
                    remainder += times_in_number
                    return f"{simplified}√({remainder})i"
        elif is_perfect(times_in_number):
            simplified += isqrt(times_in_number)
            if not is_perfect(number):
                if get_factors(number) == []:
                    remainder += number
                    return f"{simplified}√({remainder})i"
    if not any(is_perfect(number) or is_perfect(times_in_number) for number, times_in_number in factors):
        return f"√({num})i"

def solve(num: int) -> str:
    """
    Solves a negative square root with the passed number.
    """
    num = abs(num)

    # Check for prime numbers #

    if not any(num % i == 0 for i in range(2, num)):
        return f"√({num})i"

    # Find all factors #

    factors = get_factors(num)

    # Determine what factors to use and weed out perfect numbers #

    return determine_factors(factors, num)

def main():
    num = int(input("Enter negative inside square root: "))
    result = solve(num)
    print(result)

if __name__ == "__main__":
    main()

Test cases are below

Input -> Output
---------------
-52 -> 2√(13)i
-20 -> 2√(5)i
-35 -> √(35)i
-36 -> 6i
-30 -> √(30)i
-18 -> 3√(2)i
-70 -> √(70)i
-90 -> 3√(10)i
-100 -> 10i


texts: Calculate SHA1 hash from binary and verify with a provided hash

texts:
I applied for a job and they asked me to write code with the following requirements:

  Get a "toolbar offer" description from
  http..update.utorrent.com/installoffer.php?offer=conduit.  Parse the
  bencoded (see http://en.wikipedia.org/wiki/Bencode) response and
  extract the URL of the binary and its SHA1 hash.  The hash is contained
  in the value of the key 'offer_hash'. The binary is in list for the
  key 'offer_urls' — please use the one prefixed with
  "http..download.utorrent.com/".

  Download the binary and calculate its hash

  Verify that the calculated SHA1 hash is identical to the one provided
  in the offer details.  It is okay to use existing libraries for
  bencoding, hashing, etc.

What is wrong with my code? The recruiter said it didn't meet their bar.

# Script that verifies the correctness of a toolbar offers

import urllib, bencode , hashlib
from hashlib import sha1

url = "http://update.utorrent.com/installoffer.php?offer=conduit"

filename = "content.txt"

f= urllib.urlretrieve(url, filename)

#Bdecoding the response

with open (str(filename), 'rb') as myfile:
           data=myfile.read()
           decoded = bencode.bdecode(data)

# Returning the list for the key 'offer_urls'

list = decoded['offer_urls']

#print list

# Returning the URL of the binary that is prefixed with "http://download3.utorrent.com/"

length = len (list)

prefix = "http://download3.utorrent.com/"

i= -1

while i < length:
     i = i + 1
     if list[i].startswith(prefix) :
        break
binary= list[i]

print "The URL of the the binary is: " , binary

# Returning the sha1 hash contained in the value of the key 'offer_hash'

encrypted_hash = decoded['offer_hash']
sha1_hash1 = encrypted_hash.encode('hex')
print "The sha1 hash contained in the value of the key 'offer_hash' is: " , sha1_hash1

# Downloading the binary and calculating its hash

urllib.urlretrieve ( binary , "utct2-en-conduit-20130523.exe")
file = "C:\Python27\utct2-en-conduit-20130523.exe"
with open (file, 'rb') as myfile:
           downloaded=myfile.read()

k = hashlib.sha1()
k.update(downloaded)
sha1file = k.hexdigest()
print "The sha1 hash of the downloaded binary is: " , sha1file

# Verify that the calculated sha1 hash is identical to the one provided in the offer details

if (sha1file == sha1_hash1) :
    print "Test result = Pass"
else :
    print "Test result = Fail"


texts: Javascript FizzBuzz and Behavior-Driven Development Using Mocha and Chai

texts:
I am currently getting closely acquainted with Behavior-Driven Development. Could someone tell me how I am doing with the Fizzbuzz program below? I am interested in both improving the JavaScript code and the BDD prowess. Any help is appreciated.
fizzbuzz.js
module.exports = function(word, value){
    function sortNumber(a,b) {
        return a - b;
    }

    numbers = function(divisor, max){
        var result = []
        for(i=1;i<=max;i++){
            if ((i % divisor) === 0)
                result.push(i)
        }
        return result
    }

    if (value <= 0)
        return ['error','nonpositive']

    else {
        switch(word) {
            case 'fizz':
                return numbers(3, value)
            case 'buzz':
                return numbers(5,value)
            case 'fizzbuzz':
                return numbers(3,value).concat(numbers(5,value)).filter(function(elem,index,self){
                        return index == self.indexOf(elem)
                    }).sort(sortNumber)
            default:
                return ['error','wrongword']
        }
    }
};

test/fizzbuzz-spec.js:
var chai = require('chai');
    expect = chai.expect,
    fizzbuzz = require('../lib/fizzbuzz');

describe('A fizzbuzz', function(){
    describe('will return an error for invalid words: ', function(){
        it('like fuss', function(){
            expect(fizzbuzz('fuss', 10)).to.be.deep.equal(['error','wrongword']);
        });
        it('like biss', function(){
            expect(fizzbuzz('biss', 10)).to.be.deep.equal(['error','wrongword']);
        });
    });

    describe('will return an error when non-positive integer is passed', function(){
        it('like 0', function(){
            expect(fizzbuzz('buzz', 0)).to.be.deep.equal(['error','nonpositive']);
        })
        it('like -2', function(){
            expect(fizzbuzz('buzz', -2)).to.be.deep.equal(['error','nonpositive']);
        })
    })

    describe('will return valid non-error input when positive integers and valid words are passed', function(){
        it('like fizz and 20', function(){
            expect(fizzbuzz('fizz', 20)).not.to.contain('error');
        })
        it('like buzz and 20', function(){
            expect(fizzbuzz('buzz', 20)).not.to.contain('error');
        })
        it('like fizzbuzz and 20', function(){
            expect(fizzbuzz('fizzbuzz', 20)).not.to.contain('error');
        })
    })

    describe('will return valid results for some basic valid test cases', function(){
        it('like fizz and 10', function(){
            expect(fizzbuzz('fizz', 10)).to.be.deep.equal([3,6,9]);
        })
        it('like fizz and 20', function(){
            expect(fizzbuzz('fizz', 20)).to.be.deep.equal([3,6,9,12,15,18]);
        })
        it('like buzz and 10', function(){
            expect(fizzbuzz('buzz', 10)).to.be.deep.equal([5,10]);
        })
        it('like buzz and 25', function(){
            expect(fizzbuzz('buzz', 25)).to.be.deep.equal([5,10,15,20,25]);
        })
        it('like fizzbuzz and 10', function(){
            expect(fizzbuzz('fizzbuzz', 10)).to.be.deep.equal([3,5,6,9,10]);
        })
        it('like fizzbuzz and 25', function(){
            expect(fizzbuzz('fizzbuzz', 25)).to.be.deep.equal([3,5,6,9,10,12,15,18,20,21,24,25]);
        })
        it('like fizz and 2', function(){
            expect(fizzbuzz('fizz', 2)).to.be.deep.equal([]);
        })
        it('like buzz and 4', function(){
            expect(fizzbuzz('buzz', 4)).to.be.deep.equal([]);
        })

    })
});


texts: Fade-in / fade-out effects for several buttons

texts:
The function of this code is to show/hide divs by way of fadeIn/fadeOut, starting with an empty div (home) and fading in one of the other divs (work,cms,contact,) on click, then fading out the last div and fading in the next on click, and then fading out any div and fading in 'panel' (an empty div) when you click on home.

home

work

cms

contact

...

...

...


texts: Permutation 1...N. Answer queries "How many numbers between [X,Y] position are in the interval [L,K]"?

texts:
So I am solving this task:
We have an permutation of the numbers 1..n.
I need to answer m queries:
-How many numbers between X-th and Y-th position are in the interval [L,K] (<=k and >= L)?

So my solution is simple: I create a segment tree and in every node i keep an map -> which numbers are in this interval and the position (when they are sorted).

For example ( 98, 14 , 22, 45, 33) the map for this interval is (14,1)(22,2),(33,3),(45,5)..
Then when i recieve a query (X,Y,l,k) I find the interval in the tree,then I use lower bound (to the map in the node (so i get Log(n) time complexity)) to find the closest element to l and the closest element to k and substract their positions. The solution works, but i exceed the time for some test. Any tips how can i make it faster ? Maybe faster way to create the maps in the nodes ? Or faster search in the tree?

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

#define IntervalsIntersect(left,right,X, Y)  (left <= Y && right >= X)

struct node
{
    map<int, int> m;
};

int getNextIndRight(int ind, int n) // By going right how does the interval changes
    {
    int diff = n - ind;
    if (diff % 2 == 0)
        return n - diff / 2;
    return n - diff / 2 - 1;

}
int getNextIndLeft(int ind, int n)
{
    int diff = n - ind;
    if (diff % 2 == 0)
        return ind + 1 + diff / 2;
    return (ind + diff / 2) + 1;
}
void build(int* a, node* t, int v, int tl, int tr, int left, int right)
{
    if (tl == tr)
    {
        t[v].m.insert(pair<int, int>(a[tl], 1));
    }
    else
    {
        int tm = (tl + tr) / 2;
        build(a, t, v * 2, tl, tm, left, getNextIndRight(left, right));
        build(a, t, v * 2 + 1, tm + 1, tr, getNextIndLeft(left, right), right);
        t[v].m = t[v * 2].m;
        t[v].m.insert(t[v * 2 + 1].m.begin(), t[v * 2 + 1].m.end());
        int i = 1;
        for (auto &p : t[v].m)
        {
            p.second = i++;
        }

    }
}

int countInInterval(map<int, int>& m, int k, int l)
{

    //for (auto &p : m)
    //    cout<<p.first<<" "<<p.second<<endl;
    auto it = m.lower_bound(k);
    auto it2 = m.lower_bound(l);

    bool firstOK = it != m.end();
    bool secondOK = it2 != m.end();
    if (!firstOK && !secondOK)
        return 0;
    else if (firstOK && !secondOK)
        return m.size() - it->second + 1;

    if (it == it2)
    {
        if (k <= it->first&&it->first <= l)
            return 1;
        return 0;
    }

    int res= (it2->second - it->second);
    if (k <= it2->first && it2->first <= l)
        res++;
    return res;

}
bool hasIntersection(int left, int right, int X, int Y)
{
    return left <= Y && right >= X;
}
int f(node* t, int* a, int left, int right, int n, int v, int X, int Y, int k, int l)
{
    if (left >= X && right <= Y)
        return countInInterval(t[v].m, k, l);
    int leftFirst = left;
    int rightFirst = getNextIndRight(left, right);
    int res = 0;
    if (IntervalsIntersect(leftFirst, rightFirst, X, Y))
        res += f(t, a, left, getNextIndRight(left, right), n, v * 2, X, Y, k, l);

    int leftsecond = getNextIndLeft(left, right);
    int rightsecond = right;
    if (IntervalsIntersect(leftsecond, rightsecond, X, Y))
        res += f(t, a, getNextIndLeft(left, right), right, n, v * 2 + 1, X, Y, k, l);;
    return res;
}

int main()
{

    int n, m;
    cin >> n >> m;
    int* a = new int[n];
    for (int i = 0; i < n; i++)
        cin >> a[i];

    node* t = new node[4 * n + 1];

    build(a, t, 1, 0, n - 1, 1, n);

    for (int i = 0; i < m; i++)
    {
        int x, y, k, l;
        cin >> x >> y >> k >> l;
        cout << f(t, a, 1, n, n, 1, x, y, k, l) << endl;

    }

}


texts:
Can you give me some performance advice on how to optimize the time of execution of the following calculation of E?

package calculatee;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class CalculateE {
 static long start1 = System.nanoTime();

 public static BigDecimal factorial(int x) {
    BigDecimal prod = new BigDecimal("1");
    for (int i = x; i > 1; i--) {
        prod = prod.multiply(new BigDecimal(i));
    }
    return prod;
 }

 public static void main(String[] args) {
    BigDecimal e = BigDecimal.ONE;
    for (int i = 1; i < 1000; i++) {
        e = e.add(BigDecimal.valueOf(Math.pow(3 * i, 2) + 1).divide(factorial(3 * i),new MathContext(10000, RoundingMode.HALF_UP)));
    }
    System.out.println("e = " + e);
    long stop = System.nanoTime();
    long diff = stop - start1;
    System.out.println(diff + " ns");
 }

}

The time of execution is about 3055588556 ns.


texts:
I am consuming data from an API that reads from a SharePoint list. The API is basically this:

IList<Dictionary<string,string>> GetListData(string listName);

So the data is a list of dictionaries - each dictionary containing value-pairs (column name, column value) for a "row" in the list.

I need to group over the results, doing a sum over one column.

I have made code that does exactly that - but I am not entirely happy with it.

The code is this:

[Test]
public void TestOfSharePointResult()
{
    //Arrange
    IList<Dictionary<string, string>> sharePointResult = new List<Dictionary<string, string>>
    {
        new Dictionary<string, string> { {"TO", "101"}, { "PA", "123" } },
        new Dictionary<string, string> { {"TO", "202"}, { "PA", "456" } },
        new Dictionary<string, string> { {"TO", "404"}, { "PA", "123" } }
    };

    //Act
    var valuePairs = sharePointResult
        .Select(dict => new KeyValuePair<string, int>(dict["PA"], dict["TO"].FromProjectValueToInt()))
        .GroupBy(d => d.Key)
        .Select(g => new { PA = g.Key, Sum = g.Sum(f => f.Value) })
        ;

    //Assert

    // Result must be:
    //  PA  Sum
    //  --------
    //  123 505
    //  456 202
    var TOValueFor123 = valuePairs.First(i => i.PA == "123").Sum;
    var TOValueFor456 = valuePairs.First(i => i.PA == "456").Sum;
    Assert.AreEqual(505, TOValueFor123);
    Assert.AreEqual(202, TOValueFor456);
}

The "FromProjectValueToInt()" extension basically converts a string to an int.

The reason I am not entirely happy with this code is line 14, where I am doing an explicit extraction of values from the dictionary entries to a KeyValuePair struct.

Is there a more implicit way of looping over the list of dictionaries that I am missing?


texts:
I wrote a function that inserts or updates a Map key value depending on whether the key is already in the map. If it is, then the value gets added to the already existing map's value.

import Data.Map as Map

updateMap :: (Ord k, Num v) => k -> v -> Map k v -> Map k v
updateMap k v map = if member k map then Map.adjust (+ v) k map
                    else Map.insert k v map

Tests

*Main> updateMap 1 1 $ Map.singleton 1 100
fromList [(1,101)]
*Main> updateMap 2 1 $ Map.singleton 1 100
fromList [(1,100),(2,1)]
*Main> updateMap 1 33 $ Map.singleton 1 100
fromList [(1,133)]

Please critique.


texts:
I wrote the functions for opening a file, getting a file size and getting a file contents. I would welcome any suggestions to improve my code.

You might think I'm over-commenting the code. But I do it mostly just for the visual separation of the code parts. I hope to know your opinion about it.

P. S. English isn't my native language, but I try to write all code comments in English. So I would welcome any corrections also!

/*
===============
open_file
===============
*/
FILE *open_file(char const * restrict name, char const * restrict mode) {
    /* Debug: checking the input arguments. */
    assert(name != NULL);
    assert(mode != NULL);

    /* Opening the file and checking if an error occurs. */
    FILE *file = fopen(name, mode);
    if (file == NULL) {
        LOG("Error: the file \"%s\" couldn't be opened (in the \"%s\" mode). "
            "The reason: \"%s\".\n", name, mode, strerror(errno));
    }

    return file;
}

/*
===============
get_file_size
===============
*/
long get_file_size(FILE *file) {
    /* Debug: checking the input arguments. */
    assert(file != NULL);

    /* Setting the file position to the ending of the file. */
    fseek(file, 0, SEEK_END);

    /* Getting the size of the file. */
    const long size = ftell(file);
    if (size == -1) {
        LOG("Error: can't get the current value of the file position. The "
            "reason: \"%s\".\n", strerror(errno));
    }

    /* Setting the file position to the beginning of the file. */
    rewind(file);
    return size;
}

/*
===============
get_file_contents
===============
*/
char *get_file_contents(FILE *file) {
    /* Debug: checking the input arguments. */
    assert(file != NULL);

    /* Getting the size of the file. */
    long const size = get_file_size(file);
    if (size == -1)
        return NULL;

    /* Allocating memory for the contents of the file. */
    char * const contents = calloc(size + 1, 1);
    if (contents == NULL) {
        LOG("Error: can't allocate %ld bytes for a contents of a file. "
            "The reason: \"%s\".\n", size, strerror(errno));
    }

    /* Reading the contents of the file and checking if an error occurs. */
    size_t const read_size = fread(contents, 1, size, file);
    if (read_size < (size_t) size) {
        LOG("Warning: the size of elements successfully read (%zu bytes) is "
            "less than the size of the file (%ld bytes). It also may occurs "
            "if the file uses the CR+LF line endings (it is the Microsoft "
            "Windows system usually).\n", read_size, size);
    }

    return contents;
}


texts:
I have built a basic shopping cart simulator. All it does is add and remove items between two different basket (i.e. aisle vs basket).

While working on the problem I started to think about the approach and would love to hear what people think.

Avoid initializing the state empty state in the constructor. However, I had to initialize shoppingCart: [] in componentDidMount hook to avoid type error. What is the better and cleaner approach?
Is it good practice to keep the logic simple in handleXXXClicks, separation of concern one for handling items and one for shoppingCart?
I feel aisleList and cartList bloated and I could have written itemComponent which is avoidable duplicate code.
Is there any better way to handle the item in setState? I couldn't think of using prevState in my scenario.

Use setState without initializing state:

componentDidMount() {
    // assuming data comes from API fetch
    let items = ["banana", "eggs", "bread", "apple"];
    this.setState({
      items,
      shoppingCart: []  // had to set this empty to avoid typeerror
    });
  }

Handle handleClick and setState:

handleCartClick = event => {
    let newList = this.state.shoppingCart.filter(item => {
      return item !== event.target.value;
    });

    this.setState({
      items: [...this.state.items, event.target.value],
      shoppingCart: [...newList]
    });
  };

Gist link

Demo link


texts: Use Python to determine the repeating pattern in a string (no leftovers)

texts:
As a part of a challenge, I was asked to write a function to determine if there was repetition in a string (if no repetition, output is 1), and if a substring is repeated throughout the string (for example if the string is "abcabc," "abc" is repeated twice 2, if the string is "bcabcabc," the repetition is 0 since we start from the first string (no leftovers)).

My code works and I have submitted it to the challenge, but I am curious if there are ways to improve this code:

def answer(s):
     length = (len(s))
     range_list = (range(1, len(s)+1))
     list_char = list(s)
     divisors = []
     divisors = [x for x in range_list if (length)% (x) == 0]
     max_pieces = []
     for i in range (len(divisors)):
         size = divisors[i]
         split = [list_char[i:i+size] for i in range(0, length, size)]
         if(all(x == split[0] for x in split)):
             max_pieces = int(length/size)
             break
     return max_pieces


texts: Container with allocator copy assignment

texts:
I am trying to write a simple Buffer container class that will behave like std::vector. It should construct only elements that are truly within the buffer, so the rest of the buffer ([size, capacity)) is left uninitialized.

This is my current copy assignment operator:

template <typename Type, typename Allocator>
    Buffer<Type,Allocator>&
        Buffer<Type,Allocator>::operator=(const Buffer<Type,Allocator>& copy)
    {
        if(this != &copy) {
            SizeType old_size = getSize();
            if(getCapacity() != copy.getCapacity()) {
                for(SizeType i = 0; i < old_size; ++i) {
                    Allocator::destruct(_m_membegin+i);
                }
                Allocator::deallocate(_m_membegin);
                _m_membegin = Allocator::allocate(copy.getCapacity());
                _m_memend = _m_membegin+copy.getCapacity();
                _m_end = _m_membegin+copy.getSize();
                SizeType new_size = getSize();
                for(SizeType i = 0; i < new_size; ++i) {
                    Allocator::construct(_m_membegin+i,copy[i]);
                }
            } else {
                _m_end = _m_membegin+copy.getSize();
                SizeType new_size = getSize();
                for(SizeType i = 0; i < old_size; ++i) {
                    _m_membegin[i] = copy[i];
                }
                for(SizeType i = old_size; i < new_size; ++i) {
                    Allocator::construct(_m_membegin+i,copy[i]);
                }
            }
        }
        return *this;
    }

Allocator::allocate is just a wrapper around ::operator new, same thing with deallocate. construct is a wrapper around placement new and destruct is only explicit destructor call on a given type pointer.

How can I clean up this code a little bit? Also, do you see any potential memory leaks?


texts:
After reading this answer to the question "High execution time to count overlapping substrings", I decided to implement the suggested Knuth-Morris-Pratt (KMP) algorithm. I used the pseudo-code listed on Wikipedia for the functions kmp_table and kmp_search.

However, when running it on some corner-cases, I have observed that it is a lot slower than the standard str.find, which apparently uses a modified Boyer-Moore-Horspool algorithm and should thus have worse worst-case performance.

The specific case I looked at is:

$ ipython -i kmp.py
In [1]: text = "A"*1000000 + "B"
In [2]: word = "A"*100 + "B"
In [3]: %timeit kmp_search(text, word)
1 loop, best of 3: 410 ms per loop
In [4}: %timeit text.find(word)
1000 loops, best of 3: 703 µs per loop

So the difference is about a factor 1000 for this input. This is probably due to the fact that the native one is written in C and this is written in Python, but I still wanted to see if I did anything stupid here or missed any obvious optimization.

def kmp_table(word):
    table = [0] * len(word)
    position, candidate = 2, 0
    table[0] = -1

    while position < len(word):
        if word[position - 1] == word[candidate]:
            table[position] = candidate + 1
            candidate += 1
            position += 1
        elif candidate > 0:
            candidate = table[candidate]
        else:
            table[position] = 0
            position += 1
    return table

def kmp_search(text, word):
    m, i = 0, 0
    table = kmp_table(word)
    while m + i < len(text):
        if word[i] == text[m + i]:
            if i == len(word) - 1:
                return m
            i += 1
        else:
            if table[i] > -1:
                m += i - table[i]
                i = table[i]
            else:
                m += 1
                i = 0
    return len(text)


texts: Stable custom alphabetical order using List.Sort

texts:
Background

  This is a problem from a programming contest.

  The Sharonians of planet Sharon, at the far end of our galaxy, have
  discovered various samples of English text from our electronic
  transmissions, but they did not find the order of our alphabet. Being
  a very organized and orderly species, they want to have a way of
  ordering words, even in the strange symbols of English. Hence they
  must determine their own order.

  For instance, if they agree on the alphabetical order:
  UVWXYZNOPQRSTHIJKLMABCDEFG

  Then the following words would be in sorted order based on the above alphabet order:

WHATEVER
ZONE
HOW
HOWEVER
HILL
ANY
ANTLER
COW

The input format is:

<N - number of words> <alphabet order>
<0>
..
<N>

What I Did

I intended to use List<T>.Sort and use a custom Comparator so I don't have to implement a sorting algorithm from scratch. However, the alphabet input and the order is case insensitive and since List<T>.Sort uses an unstable QuickSort, words like "go" and "Go" would be swapped.

My workaround is so dirty but it works by making a copy of the word list to serve as a look-up to preserve the order of equal words.

The Code As Is

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<string> words = new List<string>();
        List<string> wordsCopy = new List<string>();

        string firstLine = Console.ReadLine();

        //assume correct input
        int numOfWords = int.Parse(firstLine.Split(" ".ToCharArray())[0]);
        string alphabet = firstLine.Split(" ".ToCharArray())[1].ToUpper();

        for (int i = 1; i <= numOfWords; i++)
        {
            words.Add(Console.ReadLine());
            wordsCopy.Add(words[words.Count - 1]);//preserve index
        }

        Console.WriteLine();

        //Quicksort is unstable (meaning "equal" elements will still be swapped, e.g. "go" and "Go")
        words.Sort(delegate(String x, String y)
        {
            int max = (x.Length > y.Length) ? y.Length : x.Length;

            if (x.ToUpper().Equals(y.ToUpper()))
            {
                //dirty work-around to stablize the sort
                return wordsCopy.IndexOf(x) < wordsCopy.IndexOf(y) ? -1 : 1;
            }

            for (int i = 0; i < max; i++)
            {
                int indexX = alphabet.IndexOf(x[i].ToString(), StringComparison.InvariantCultureIgnoreCase);
                int indexY = alphabet.IndexOf(y[i].ToString(), StringComparison.InvariantCultureIgnoreCase);

                if (indexX > indexY)
                {
                    return 1;
                }
                else if (indexX < indexY)
                {
                    return -1;
                }
            }

            return 0;
        });

        Console.Write(String.Join("\n", words));
        Console.ReadLine();
    }
}

This code was good enough to win, but what could I have done better?


texts: Reverse the word order in string, without reversing the words

texts:
I was tasked with using C++ to turn this

"Hello Jarryd, do you like socks?"

into:

"socks? like you do Jarryd, Hello";

Edit: The condition was to reverse this in place.

Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!

.h

namespace SentenceFlipNamespace
{
    class SentenceFlip
    {
    public:
        SentenceFlip();
        ~SentenceFlip();

        int FlipSentenceInPlace(char* in_Sentence);
        void SentenceFlip::Move(int in_StartIndex, char in_String[]);

    };
}

.cpp

namespace SentenceFlipNamespace
{
    SentenceFlip::SentenceFlip()
    {
    }

    SentenceFlip::~SentenceFlip()
    {
    }

    int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
    {
        int index = 0;
        int length = strlen(in_Sentence);

        while (index < length)
        {
            int dist = 0;
            int wordSize = 0;

            //Get the characters to the first word
            for (int i = length - 1; i > 0; i--)
            {
                if (in_Sentence[i] == ' ' && i != length - 1)
                {
                    dist = i - index;
                    wordSize = length - i - 1; //exclude the space
                    break;
                }
            }

            //Push everything forwards
            for (int i = 0; i <= dist; i++)
                Move(index, in_Sentence);

            //This leaves a space at the end, push it forward
            if (index + wordSize >= length)
                return 0;

            for (size_t i = 0; i < length - wordSize - index - 1; i++)
                Move(index + wordSize, in_Sentence);

            index += wordSize + 1; //include the space
        }

        return -1;
    }

    void SentenceFlip::Move(int in_StartIndex, char in_String[])
    {
        char temp = in_String[in_StartIndex];
        int length = strlen(in_String);
        for (int j = length - 1; j >= in_StartIndex; j--)
        {
            char temp2 = in_String[j];
            in_String[j] = temp;
            temp = temp2;
        }
    }
}

Test Method, since I don't invoke it in main.

namespace CodeChallengesTests
{
    TEST_CLASS(TextFlip)
    {
    public:
        TEST_METHOD(SentenceFlipInPlace)
        {
            SentenceFlipNamespace::SentenceFlip *testFlip = new SentenceFlipNamespace::SentenceFlip();
            char input[] = "Hello Jarryd, do you like socks?";
            char expectedResult[] = "socks? like you do Jarryd, Hello";
            testFlip->FlipSentenceInPlace(input);

            Assert::AreEqual(expectedResult, input, "Results do not match");
        }
    };

}


texts:
I'm doing a CodingBat exercise and would like to learn to write code in the most efficient way. On this exercise, I was just wondering if there's a shorter way to write this code.

monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {

  if (aSmile && bSmile) {
      return true;
  }

  if (!aSmile && !bSmile) {
      return true;
  }

  return false;

}


texts:
Printing to stdout is thread-safe in many systems when using printf or std::cout, but not in all systems (Windows!). So I decided to make my own thread-safe and type-safe printing function with some help of C++11 variadic templates functions.

#include <iostream>
#include <iomanip>
#include <mutex>

class Mutex:private std::mutex{
public:
    class Lock:private std::lock_guard<std::mutex>{
    public:
        Lock(Mutex& mutex):
        std::lock_guard<std::mutex>(mutex){}
    };
};

class{
private:
    Mutex m_mutex;

    void Print(){}

    template<typename T,typename... Ts>
    void Print(const T& t,const Ts&... ts){
        std::cout<<t<<std::flush;
        Print(ts...);
    }

public:
    template<typename T,typename... Ts>
    void operator()(const T& t,const Ts&... ts){
        Mutex::Lock lock(m_mutex);
        Print(t,ts...);
    }
}Print;

template<typename T>
void PrintLine(){
    Print('\n');
}

template<typename T,typename... Ts>
void PrintLine(const T& t,const Ts&... ts){
    Print(t,ts...,'\n');
}

int main(){
    Print(10," devided by ",3," equals ");
    PrintLine(std::fixed,std::setprecision(5),10.0/3);
    return 0;
}


texts: Good Unit Tests when ReSharper bugs for null checks

texts:
I have the latest version of ReSharper installed and I am trying to write a Unit Test for my MVC controller. I need the Unit Test to:

  Ensure the ViewModel passed to the View is of the correct type.

So here is what I have at the moment:

public void Create_HasCorrectViewModelType()
{
    // arrange
    var controller = new DraftController(_draftFacade);
    // act
    var viewResult = controller.Create() as ViewResult;
    var viewModel = viewResult.Model as DraftViewModel;
    // assert
    Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}

I have issues with this, and would like to know your thoughts on the matter.

the arrange makes sense. I am arranging / setting up my controller.
Only the first line in the act seems logical to me. But me trying to grab the ViewModel isn't really an Act is it? Sounds like // arrange again!
ReSharper complains that I am not doing null checks on viewResult and viewModel.

I can go with ReSharper's recommendation, then my test becomes:

public void Create_HasCorrectViewModelType()
{
    // arrange
    var controller = new DraftController(_draftFacade);
    // act
    var viewResult = controller.Create() as ViewResult;
    var viewModel = viewResult?.Model as DraftViewModel;
    // assert
    if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}

Now ReSharper is happy, but then my Unit Test don't seem clean anymore! I feel like there are too many paths that can be taken for that one unit test.

Anyone else bugged by this? What can I do to improve this? Or is this the best I'm going to get?

Any help would be greatly appreciated.


texts: Identifying which paragraph, if any, is a superset of all words in a document

texts:
Description

need to find out the paragraph number which is containing all the words in the file.

input file java.txt

  What is a JVM?

  What is the most important feature of Java?

  Are JVM's platform independent?

  What do you mean by platform independence? What is the most important
  feature of Java? What is a JVM? Are JVM's platform independent?

Output

paragraph num : 4

Solution code:

 public class WordsOfParagraphWithMap {
        public void findParagraphWithAllWords() throws IOException{

        File file = new File("C:\\Users\\VENKAT\\Documents\\javaquestions.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        int paraNum = 1;
        int count = 0;
        String line;
        int paragraphWithMaxWords = 0;
        int maxWords = 0;

        Map<String, Integer> map = new HashMap<String, Integer>();

        line = nextLine(bufferedReader);

        do {
            if (line != null) {

                if (line.trim().isEmpty()) {
                    if (maxWords < count) {
                        paragraphWithMaxWords = paraNum;
                        maxWords = count;
                    }
                    paraNum++;
                    count = 0;
                    line = nextLine(bufferedReader);
                }

                if(line!=null){
                    String[] words = line.split("\\s");
                    for (String word : words) {
                        if (!map.containsKey(word)) {
                            count++;
                        } else {
                            int paraNumber = map.get(word);
                            if (paraNumber != paraNum) {
                                count++;
                            }
                        }
                        map.put(word, paraNum);
                    }
                }
            }
        } while ((line = bufferedReader.readLine()) != null);

        if (maxWords < count){
            paragraphWithMaxWords = paraNum;
            maxWords = count;
        }

        if (map.size() == maxWords)
            System.out.println("paragraph num : " + paragraphWithMaxWords);
        else
            System.out.println("no such paragraph");

    }

    private String nextLine(BufferedReader bufferedReader) throws IOException{
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.trim().isEmpty()) {
                continue;
            } else {
                break;
            }
        }
        return line;
    }

    public static void main(String[] args) throws IOException {
        WordsOfParagraphWithMap wordsOfParagraphWithMap = new  WordsOfParagraphWithMap ();
        wordsOfParagraphWithMap.findParagraphWithAllWords();
    }
    }


texts: Displaying "C++" in ASCII art with user inputting an integer

texts:
I have a school assignment and would love it if you can criticize or give a couple of pointers/advice about my piece of code (don't give me the answer, breaks the point of the exercise).

Here's my work:

#include <iostream>
#include <iomanip>

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

int main()
{
//Declaring our variables
int number; //Integer input from the user

cout << " Please enter an integer :\n"; //Will display text
cin >> number; //The user's input will now be stored in the variable

//These following lines will compose the ascii art which spells out "c++"

cout << number << number << number << number << number << number << number
<< number << number << number << number << endl; //line 1

cout << number << number << number << setw(17) << number << number <<
setw(17) << number << number << endl; // line 2

cout << number << number << number << setw(17) << number << number <<
setw(17) << number << number << endl; // line 3

cout << number << number << number << setw(12) << number << number << number
<< number << number << number
<< number << number << number << number << number << setw(9) << number <<
number << number << number
<< number << number << number << number << number << number << number <<
endl; //line4

cout << number << number << number << setw(17) << number << number <<
setw(17) << number << number << endl; // line 5

cout << number << number << number << setw(17) << number << number <<
setw(17) << number << number << endl; // line 6

cout << number << number << number << number << number << number << number
<< number << number << number << number << endl; //line 7

return 0;
}


texts: Python insert line in the middle of the file

texts:
I will be inserting a new text line in a setup.py file, this new line will contain text, and is part of the REQUIRED_PACKAGES. I parsed the
file and look for REQUIRED_PACKAGES pattern (REQUIRED_PACKAGES = [ ... ]). Looking for alternatives during file insertion.

A sample setup.py file looks like this:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import fnmatch
import os
import re
import sys

from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution

DOCLINES = __doc__.split('\n')

_VERSION = '1.0.0'

REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'enum34 >= 1.1.6;python_version<"3.4"',
    'gast == 0.3.3',
    'scipy == 1.2.2;python_version<"3"',
]

if sys.byteorder == 'little':
  # grpcio does not build correctly on big-endian machines due to lack of
  # BoringSSL support.
  REQUIRED_PACKAGES.append('io >= 1.0.0')

...

After conversion it will look like this (adding a new line):

...
REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'enum34 >= 1.1.6;python_version<"3.4"',
    'gast == 0.3.3',
    'scipy == 1.2.2;python_version<"3"',
    'test==1.0.0',
]
...

Python code

import re

SEARCH_DICT = {
    'required_packages': re.compile(
        r'REQUIRED_PACKAGES = (?P<required_packages>.*)\n')
}

TEST_LIBRARY = '\t\t\'test==1.0.0\'\n'

def _parse_line(line):
    """
    Do a regex search against all defined regexes and
    return the key and match result of the first matching regex

    """

    for key, rx in SEARCH_DICT.items():
        match = rx.search(line)
        if match:
            return key, match
    # if there are no matches
    return None, None

def parse_file(filepath):
    """
    Parse text at given filepath

    Parameters
    ----------
    filepath : str
        Filepath for file_object to be parsed

    Returns
    -------
    data : file contents

    while True:
        last_pos = fp.tell()
        line = fp.readline()
        new_line = line.upper()
        fp.seek(last_pos)
        fp.write(new_line)
        print "Read %s, Wrote %s" % (line, new_line)

    """

    data = []  # create an empty list to collect the data
    line_index = -1
    # open the file and read through it line by line

    with open(filepath, 'r+') as file_object:
        line = file_object.readline()
        line_index+=1
        while line:
            # at each line check for a match with a regex
            key, match = _parse_line(line)
            if key == 'required_packages':
                required_packages_start = match.group('required_packages')
                if required_packages_start == '[':
                    print('Found REQUIRED_PACKAGES')
                    while line.strip():
                        library = line.rstrip()
                        if library == ']': # End of required packages
                            return line_index
                        line = file_object.readline()
                        line_index+=1

            line = file_object.readline()
            line_index+=1
        file_object.readline()
        line_index+=1

    return line_index

line_index = parse_file('setup.py')
lines = None
if line_index != -1:
    with open('setup.py', 'r+') as fd:
        contents = fd.readlines()
        contents.insert(line_index, TEST_LIBRARY)  # new_string should end in a newline
        fd.seek(0)  # readlines consumes the iterator, so we need to start over
        fd.writelines(contents)  # No need to truncate as we are increasing filesize


texts:
The code below is for Hackerrank competition. Seems that it works correctly but performs very slowly and because of it can't pass some tests.

The task is to find the maximum GCD of all possible pairs of two positive integers \$x, (1 \leq x \leq 10^6)\$ and \$y, (1 \leq y \leq 10^6)\$, where \$x\$ belongs to array \$A\$ and \$y\$ belongs to array \$B\$. Both arrays have the same size, \$(1 \leq \text{size} \leq 10^5)\$. If there is more than one pair with the same GCD, then use the GCD with the maximum sum of its numbers i.e. \$(x + y)\$. Print the sum of elements of this maximum-sum pair.

Input is given in the following way

first line - size of the arrays
second line - elements for the first array
third line - elements for the second array

e.g

5
3 1 4 2 8
5 2 12 8 3

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

inline size_t countGcd( size_t n1, size_t n2 ) {
   return ( n2 != 0 ) ? countGcd( n2, n1 % n2 ) : n1;
}

int main() {

size_t num = 0;
std::cin >> num;
size_t elem = 0;
std::vector< size_t > arr;
for ( size_t i = 0; i < num; ++i ) {
    std::cin >> elem;
    arr.push_back( elem );
}
size_t max_sum = 0;
size_t max_gcd = 0;
for ( size_t i = 0; i < num; ++i ) {
    std::cin >> elem;

    for ( size_t j = 0; j < arr.size(); ++j ) {
        size_t gcd = ( ( elem >= arr.at( j ) ) ? ( elem % arr.at( j ) == 0 ? arr.at( j ) : countGcd( elem, arr.at( j ) ) ) : ( arr.at( j ) % elem == 0 ? elem : countGcd( elem, arr.at( j ) ) ) );
        if ( gcd > max_gcd ) {

            max_sum = elem + arr.at( j );
            max_gcd = gcd;
        } else if ( gcd == max_gcd ) {
            size_t sum = elem + arr.at( j );
            if ( sum > max_sum )
                max_sum = sum;
        }
    }
}
std::cout << max_sum << std::endl;

return 0;
}

I tried different GCD implementations ( Euclidean algorithm ( both recursive and iterative ), Binary GCD algorithm ( both recursive and iterative ) ) but without success. Seems that I have to change something inside main function, maybe rid off the if-else inside the for-loops but actually have no idea how to do this.


texts: Polynomial curve-fitting over a large 3D data set

texts:
I have a list of 4 images, called listfile.list, which looks like this:

image1
image2
image3
image4

Each image has 10 frames containing a 2000 x 2000 array of pixels, so the size of each image is [10,2000,2000]. The pixel value for each frame increases from 0 to 10, so for example for one pixel in image1:

image1[:,150,150] = [435.8, 927.3, 1410. , 1895.1, 2374.6, 2847.1,
                     3340.5, 3804.8, 4291.6, 4756.1]

The other pixels show similar values and a roughly linear increase across the frames. I need to fit several functions to pixel values across the frames for each pixel in each image and then average over the images. The data sets are 3D and very large, so I don't know how to paste them here. My code does exactly what I want it to, the issue is that it can take days (> 3) to run my full script.

One function is frame_fit to return rates and intercepts. There are several other functions. My code is structured as follows:

import itertools
import numpy as np
from scipy.optimize import curve_fit

def frame_fit(xdata, ydata, poly_order):
    '''Function to fit the frames and determine rate.'''

    # Define polynomial function. Here, 'b' will be ideal rate and
    # 'c', 'd', 'e', etc. describe magnitudes of deviation from
    # ideal rate.
    if poly_order == 5:
        def func(t, a, b, c, d, e, f):
            return a+ b*t+ c*(b*t)**2+ d*(b*t)**3+ e*(b*t)**4+ f*(b*t)**5

    elif poly_order == 4:
        def func(t, a, b, c, d, e):
            return a + b*t + c*(b*t)**2 + d*(b*t)**3 + e*(b*t)**4

    # Initial values for curve-fitting.
    initvals = np.array([100, 4.e+01, 7.e-03, -6.e-06, 3.e-08, -8.e-11])

    # Provide uncertainty estimate
    unc = np.sqrt(64 + ydata)

    beta, pcov = curve_fit(func, xdata, ydata,
                           sigma=unc, absolute_sigma=False,
                           p0=initvals[:poly_order+1],
                           maxfev=20000)

    # beta[1] is rate, beta[0] is intercept

    return beta[1], beta[0]

all_rates = np.zeros((number_of_exposures, 2000, 2000),dtype=np.float64)
all_intercepts = np.zeros((number_of_exposures, 2000, 2000),dtype=np.float64)
all_results = np.zeros((2, 2000, 2000),dtype=np.float64)
pix_x_min = 0
pix_y_min = 0
pix_x_max = 2000    # max number of pixels in one direction
pix_y_max = 2000
xdata = np.arange(0,number_of_frames)    # so xdata [0,1,2,3,4,5,6,7,8,9]

# Here is where I need major speed improvements

for exposure in list_of_exposures:

    for i,j in itertools.product(np.arange(pix_x_min,pix_x_max),
                                     np.arange(pix_y_min,pix_y_max)):

        ydata = exposure[:,i,j]

        rate, intercept = frame_fit(xdata,ydata,5)

        # Plus other similar functions ...
        # results2, residuals2 = function2(rate, intercept)
        # results3, residuals3 = function3(results2, specifications)

        all_rates[exposure,i,j] = rate
        all_intercepts[exposure,i,j] = intercept

avg_rates = np.average(all_rates, axis=0)
avg_intercepts np.average(all_intercepts, axis=0)

all_results[0,:,:] = avg_rates
all_results[1,:,:] = avg_intercepts

# all_results is saved to a file after everything is finished.

There are usually at least 4 images with 2000x2000 arrays of pixels in my input list. Besides the frame_fit function, there are several others that I have to run for each pixel. I am a relatively new Python programmer so I often don't know about all available tools or best practices to improve speed. I know a nested for-loop as I've written it is going to be slow. I have considered cython or multiprocessing, but those are complicated to tackle for a new programmer. Is there a better way to perform a function on each pixel and then average over the results? I am hoping to stick with standard python 3.5 modules (rather than installing extra packages).


texts: Ordering colors into a multidimensional list

texts:
The code below works fine but seems really hard coded and I feel like I over-complicated the way it should be, I have a list containing hex and non-hex colors.

example : ['#333333', '#ff034a', 'red']

Basically, hex colors are converted to RGB, the nouns are compared in the database and returns a list of hex if the noun matches a query.

Here's the Output I want to keep (could be a numpy output too) :

[[(38, 30, 38)], [(245, 245, 245)], [(255, 51, 51), (255, 153, 153), (217, 38, 38), (242, 13, 13), (255, 62, 62)]]

Here's the hard coded junk I want to keep short and make faster :

list_of_colors = ['#333333', '#ff034a', 'red'] #can contain from 1 to 3 values

def orderDimentionalRGB(list_of_colors):
    dominant = []
    secondary = []
    complementary = []

    for index, color in enumerate(list_of_colors):
        if Color.objects.filter(color=color).exists(): #check for noun
            colors = Color.objects.filter(color=color)
            lst_colors = numpy.array(colors.first().color_list.replace(',', '').split())

            for lc in lst_colors:
                rgb = hex_to_rgb(lc) #returns from hex string -> to tuple rgb
                if index == 0:
                    dominant.append(rgb)
                elif index == 1:
                    secondary.append(rgb)
                else:
                    complementary.append(rgb)

        else: #check for rgb
            color = hex_to_rgb(color)

            if index == 0:
                dominant.append(color)
            elif index == 1:
                secondary.append(color)
            elif index == 2:
                complementary.append(color)

    colors = [dominant, secondary, complementary]
    set_colors = [x for x in colors if x]

    return set_colors

Maybe using that much if, elif, else and array variables becomes redundant and makes things slower, how can I improve this code ?


texts:
I am trying to compute the surface density profile, given the spherical density profile in 3D for different parameters in order to interpolate and have it as a function of them to use later on for some gravitational lensing modelling. However, looping through all parameters and evaluating the integral over the 2D Radius array R is extremely time consuming (many hours for complicated profiles).

The code that follows describe the procedure I am following in order to do that. Does anyone have a better suggestion to improve the performance of the following code in Python?

def density_profile(r, par_a, par_b, par_c):
    ...
    return ...

def surface_denstiy_profile(R, density_profile, *args):

    surface_density_array = []

    for R_i in R:

        surface_density_array.append( quad(lambda r : 2.0 * density_profile(r , *args, ) * r / np.sqrt(r**2. - R_i**2.), R_i, np.inf, epsabs=1.49e-03, epsrel=1.49e-03)[0] ) )

    return surface_density_array

surface_density = np.zeros((len(par_a_array), len(par_b_array), len(par_b_array)), dtype = object)

for par_a in range(0, len(par_a_array)) :

    for par_b in range(0, len(par_b_array)):

        for par_c in range(0, len(par_c_array)):

            surface_density[par_a, par_b, par_c] = surface_denstiy_profile(np.logspace(-2., 2., 100), density_profile, par_a_array[par_a], par_b_array[par_b], par_c_array[par_c])


texts: Finding Matches and writing results to file C#

texts:
I have a folder that contains around 1000 text files, their sizes varies from few KBs up to 500 MB (Total size is around 60 GB).

I have a text file that contains a 166k lines, each line contains a set of numbers (length up to 11), what I'm doing here is to go through each file in that folder and try to find a match between the 166k and those files, then store the line from the file and print that out to a file.

My approach is working but there are several issues:

It is not fast  (taking a lot of time to go through the files)
Memory consumption, I believe that is because I'm storing everything into a list of strings and then print all of it at once

Please take a look at my code below, and let me know if I can enhance it and improve it in any possible way.

    static void Main(string[] args)
    {
        char splitter = '\u0001';

        //166k file
        string path = "Z:\\subid.txt";

        //Destination file
        string RxPath = "Z:\\matched.txt";

        List<string> subid = File.ReadAllLines(path).ToList();
        List<string> RxClaims = new List<string>();

        string[] lineObject;
        int count = 0;

        //folder location (contains 1000 text files)
        string folderPath = "Z:\\rawfiles";

        foreach (string file in Directory.EnumerateFiles(folderPath))
        {
            Console.WriteLine("Processing " + file);
            foreach (string line in File.ReadLines(file))
            {
                lineObject = line.Split(splitter);

                //Check if that value is equal to any of the numbers in the 166k, if so store in the list to print out later
                if(subid.Contains(lineObject[14]))
                {
                    count++;
                    RxClaims.Add(line);
                }

            }
        }

        File.WriteAllLines(RxPath, RxClaims);
        Console.WriteLine("Done, Number of Claims" + count);

        Console.ReadLine();
    }