texts: Navigating the robot by finding the shortest way

texts:
I have this task where I have to make my robot find the shortest way when I enter a destination point. I've created some functions to assign numbers (distances) for each square and counts its way back to my robot by deleting the other options. Then the robot should only follow the numbers. Here's also a screenshot of the map it navigates in:
<img src="https://i.stack.imgur.com/ZzM52.jpg" alt="Here's also a screenshot of the map it navigates in:
" />
My code works so far, however I think I should be able to reach the same outcome by using less for loops and with a more efficient writing. I believe if I see different ways of thinking in my earlier stages, I can have a broader perspective in the future. So, any ideas on how to reach my goal with a shorter code?
#Your Code Starts Here
"""
for x in range(0, map.width):
    for y in range(0, map.height):
        if map.blocked(x, y):
            map.value[x, y] = -1
        else:
            map.value[x, y] = 0
"""
def fill_around(n,m,number):
    for x in range (n-1,n+2):
        for y in range (m-1,m+2):
            if map.value[x,y] != 0:
                pass
            elif x==n+1 and y==m+1 or x==n-1 and y==m-1 or x==n-1 and y==m+1 or x==n+1 and y==m-1:
                pass
            elif map.blocked(x,y) == True:
                map.value[x,y]= -1
            elif x==n and y==m:
                map.value[x,y]= number
            else:
                map.value[x,y]= number+1

def till_final(final_x,final_y):
    final_x=9
    final_y=1
    fill_around(1,1,1)
    for p in range(2,17):
        for k in range(0, map.width):
            for l in range(0, map.height):
                if map.value[final_x,final_y] ==0 and map.value[k,l]==p:
                    fill_around(k,l,p)

def delete_duplicates(final_x,final_y):
    for k in range(0, map.width):
        for l in range(0, map.height):
            if map.value[k,l] == map.value[final_x,final_y] and k != final_x and l != final_y:
                map.value[k,l] = 0


texts: Reduce or improve Linq query with nested from-where clauses

texts:
I am new to linq to objects in C#. I have the following query which works adequately. Is there someway to reduce or rewrite this query using joins or something else?

var query =
        from container in containers
        let items = container.GetItems()
            from itemA in items
            let tag = CreateTag(itemA)
            where IsInteresting(tag)
                from itemB in items
                let derivedTag = CreateDerivedTag(tag)
                where CreateTag(itemB) == derivedTag
                select new { first = itemA, second = itemB };

To summarize,

there are a set of item sequences
for each item sequench

for each item A that is IsInteresting()

find an item B in the same sequence that matches based on the criteria derived from the item A
create a new item containing a reference to matching items A and B

return a collection of all such matching items


texts: Convert Improper Fraction to Mixed Number with JavaScript

texts:
My function converts an improper fraction to a mixed number (it does not AND should not simplify the fraction).

// Improper fraction to mixed number
// n = numerator
// d = denominator
// i = number
function improperFractionToMixedNumber(n, d) {
    i = (n / d) >> 0;

    n -= i * d;

    return [i, n, d];
}

// Convert 14/4 to mixed number
improperFractionToMixedNumber(14, 4); // 3, 2, 4

Can this be improved or simplified?

I don't care for this part:

i = (n / d) >> 0;

But it's the only way I could figure out how to see how many times a number equally divides into another number.


texts: Idiomatic string from/to integer conversions in Julia (Project Euler #33)

texts:
I am starting to learn Julia. For getting fluent in the syntax, I am solving some of the easier Project Euler challenges. Problem 33 is about so-called curious fractions, which keep their value after canceling out common digits in numerator an denominator (example: removing digit 9 from \$\frac{49}{98}\$ to get \$\frac{4}{8}\$ reduces to the correct result \$\frac{1}{2}\$.

I wanted to ask especially whether I am using non-idiomatic conversions (like num_str = "$num" to convert Integer to string). I am using Julia 0.4.5 right now, in case that matters.

Other than that, recommendations on better structuring the whole program.

"""
Check whether fraction Rational(a, b), when "curiously" shortened by removing
a common digit in numerator and denominator, keeps its value.

# Reference
Definition via Project Euler, Problem 33
https://projecteuler.net/problem=33

# Examples
```
julia> is_curious_fraction(19, 95)
true

julia> is_curious_fraction(24, 27)
false
```
"""
function is_curious_fraction(num, den)
    original_fraction = Rational(num, den)
    num_str = dec(num)
    den_str = dec(den)

    for d in 1:9  # ignore zeros as trivial
        d_char = Char(d + 48)  # convert digit to ASCII character

        # check whether both num and den contain same digit
        if d_char ∈ num_str && d_char ∈ den_str
            # if so, create "curiously" shortend fraction
            # by removing at most one occurence of the digit
            new_numerator = replace(num_str, d_char, "", 1)
            new_denominator = replace(den_str, d_char, "", 1)

            # convert this pair of one-digit strings to Int and
            # create new Rational
            new_fraction = Rational(parse(Int, new_numerator),
                                    parse(Int, new_denominator))

            # for a curious fraction, the value of original and
            # "curiously" shortened fraction are equal
            if new_fraction == original_fraction
                return true
            end
        end
    end
    # in all other cases, it is no curious fraction
    false
end

curious_fractions = []
# loop over all two-digit numinator and denominator
# fractions with value less than one
for num in 10:99
    for den in (num + 1):99
        if is_curious_fraction(num, den)
            push!(curious_fractions, Rational(num, den))
            println("$num / $den")
        end
    end
end
# denominator of product of fractions
# (after reduction to lowest common terms)
println(prod(curious_fractions).den)


texts: Calculate working days and excluding specific dates (Holidays)

texts:
I read some questions/answers related to functions in C# to calculate the working days; some use an extended code to achieve that.

I have a data table with more than 50,000 rows and I required an effective method to calculate this information.

I created the following extension in C# that return a number of days (Integer), between two dates; excluding dates (Based on a list of DateTime)

/// <summary> Get working days between two dates (Excluding a list of dates - Holidays) </summary>
/// <param name="dtmCurrent">Current date time</param>
/// <param name="dtmFinishDate">Finish date time</param>
/// <param name="lstExcludedDates">List of dates to exclude (Holidays)</param>
public static int fwGetWorkingDays(this DateTime dtmCurrent, DateTime dtmFinishDate, List<DateTime> lstExcludedDates)
{
    Func<DateTime, bool> workDay = currentDate =>
    (
        currentDate.DayOfWeek == DayOfWeek.Saturday ||
        currentDate.DayOfWeek == DayOfWeek.Sunday ||
        lstExcludedDates.Exists(evalDate => evalDate.Date.Equals(currentDate.Date))
    );

    return Enumerable.Range(0, 1 + (dtmFinishDate - dtmCurrent).Days).Count(intDay => workDay(dtmCurrent.AddDays(intDay)));
}

Does there exists some way to improve this method.


texts: Extracting XML data from a node in Common Lisp (Closure XML DOM)

texts:
This is a function intended to take an XML element (in closure XML format) and a name and find a piece of simple data by that name (either in a tag or attribute) within that XML element. It works, but I'm still new to LISP - can it be written more elegantly?

(defun find-data-inside-xml (element name)
  ;; Maybe there's an attribute?
  (if (dom:has-attribute element name) (dom:get-attribute element name)
  ;; There isn't, we have to do it the ugly way. Find suitable subnodes.
    (let ((candidate-values (loop for node across (dom:child-nodes element)
                           when (string= (dom:node-name node) name) collect node)))
     ;; Check there was only one of them.
     (cond
        ((> (length candidate-values) 1) (error "XML element has multiple ~S elements." name))
        ((= (length candidate-values) 0) (error "XML element missing ~S element." name))
        (t (let ((cand-children (dom:child-nodes (car candidate-values))))
            ;; Check the one there was, has only one child node.
            (cond
             ((> (length cand-children) 1) (error "XML ~S element has complex content." name))
             ((= (length cand-children) 0) (error "~S element has no content." name))
             (t (let ((content-node (elt cand-children 0)))
                 ;; If that child node is text, that's our value. Otherwise, error.
                 (if (eq (dom:node-type content-node) :text)
                     (dom:node-value content-node)
                     (error "~S element value is not text." name)))))))))))


texts: Customize data types in a generated model with hibernate

texts:
I have a Spring/Hibernate application with the following domain class (irrelevant code stripped for brevity):

@Entity
@Data
public class Program implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long tid;

    @Column
    @Convert(converter = ProgramStatusConverter.class)
    private ProgramStatus status;

    @Column
    @Length(max=64)
    private String containerId;

    @Column
    private String sourceCode;

    @Column
    private String compilationOutput;

    @Column
    @OneToMany(fetch=FetchType.LAZY, mappedBy="program")
    private Set<Execution> executions;
}

The problem is that the database schema (currently an in-memory h2 database) is generated when I startup the application. It works fine in almost all cases, but the "compilationOutput" and "sourceCode" columns are generated as VARCHAR(255), which is too short.

The solution I used was simply to add @Length(max=10000) on the two columns, but I don't like the solution for two reasons:

It's a semantic annotation and I'm using it to solve a purely technical issue. I have absolutely no reason to limit these fields to 10000 characters.
What if I get a sourceCode that's longer than 10000 characters ? This solution is not a real solution.

Is there a better way ?


texts:
I'm a systems programmer teaching myself javascript.  Prototypal inheritance is completely new to me, so I could use some best practices advice here.

I made a simple game (breakout) for my first practice project.  Here is a simple example of a game object.

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
    this.__defineGetter__('width', function() {
        return sprite.width;
    });
    this.__defineGetter__('height', function() {
        return sprite.height;
    });
    this.__defineGetter__('rect', function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    });
}

Every object has an associate sprite and said sprite defines the width and height of the object.  So, coming from C++, I defined a few of getters that depend on the sprite.

Any and all advice is obviously appreciated.  Hopefully this example isn't overly trivial.


texts:
Back in my calculator post, janos suggested I either find a better way to read a double from a StreamReader or else go the whole way and build a double from scratch.  I looked through a few streams, but the only one I found that supported reading a double was the BinaryReader.  This, unfortunately, reads exactly 8 bytes, and the data is stored as a char (or rather, as an int representation of a char), so I could enter the equation "5+5", and it would crash when it read the "+".  If you know of a better solution, I would prefer using it.

private double GetNextNumber(StreamReader dataStream)
{
    double value = 0;
    int decimalLevel = 0;

    while (true)
    {
        if (!"0123456789.".Contains((char)dataStream.Peek()))
        {
            break;
        }
        char token = (char)dataStream.Read();

        if (token == '.')
        {
            if (decimalLevel == 0)
            {
                ++decimalLevel;
                continue;
            }
            throw new InvalidDataException("Invalid number format.");
        }

        int digit = int.Parse(token.ToString());

        value = value * 10 + digit;

        if (decimalLevel != 0)
        {
            ++decimalLevel;
        }
    }

    return value / Math.Pow(10, decimalLevel - 1);  // use "- 1" because value increments just before ending loop
}

Please analyze my code as thoroughly as the compiler does.


texts:
https://leetcode.com/problems/diameter-of-binary-tree/

  Given a binary tree, you need to compute the length of the diameter of
  the tree. The diameter of a binary tree is the length of the longest
  path between any two nodes in a tree. This path may or may not pass
  through the root.

Example:
Given a binary tree
          1
         / \
        2   3
       / \
      4   5

  Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

  Note: The length of path between two nodes is represented by the
  number of edges between them.

 [TestClass]
    public class DiameterOfBinaryTreeTest
    {
        [TestMethod]
        public void DiameterOfBinaryTreeTest1()
        {
                        /* Constructed binary tree is
                       1
                     /   \
                   2      3
                 /  \
               4     5
             */
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.left.left = new TreeNode(4);
            root.left.right = new TreeNode(5);
            root.right = new TreeNode(3);
            DiameterOfBinaryTreeClass diam = new DiameterOfBinaryTreeClass();

            int result = diam.DiameterOfBinaryTree(root);
            Assert.AreEqual(3, result);
        }
}

 //https://leetcode.com/problems/diameter-of-binary-tree/
    public class DiameterOfBinaryTreeClass
    {
        public int DiameterOfBinaryTree(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            int leftDiameter = DiameterOfBinaryTree(root.left);
            int rightDiameter = DiameterOfBinaryTree(root.right);

            int leftHeight = Height(root.left);
            int rightHeight = Height(root.right);
            return Math.Max(leftHeight + rightHeight, Math.Max(leftDiameter,rightDiameter));
        }

        private int Height(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            return Math.Max(Height(root.left) ,Height(root.right)) + 1;
        }
    }

Please review for performance.


texts:
I have the following task:

  Implement a simple command line Java application for booking bus
  seats. For simplicity suppose there is only one bus, initially all
  seats (lets say 50) are free. Users can book one seat at time through
  the application API, the application itself should try to take the
  first available seat from 1 to 50, if any left. Make sure your
  application is thread-safe (i.e. many users can book tickets at the
  same time, but cases such booking the same seat from more than one
  user must be avoided) using the conventional locking mechanisms in
  available in Java.

The program I have written so far looks like this:

public class Bus{

    private final boolean [] seats = new boolean[50];
    private int nextSeat = 0;

    public void bookSeat() throws Exception{
        if(nextSeat<seats.length){
        seats[nextSeat]=true;
        nextSeat++;
        System.out.print("Seat number " +nextSeat+ " booked");
        }else{
            System.out.println("The bus is full sorry");
        }
        }

}

public class Passenger extends Thread{

    Bus bus;
    String passengerName;

    public Passenger(Bus bus, String passengerName){
        this.bus=bus;
        this.passengerName=passengerName;
    }

    public void run(){
        synchronized(bus){
            try {
                bus.bookSeat();
                Thread.sleep(500);
            } catch (Exception ex) {
                Logger.getLogger(Passenger.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("by " + passengerName);

        }
    }

    public String getPassengerName() {
        return passengerName;
    }

    public void setPassengerName(String passengerName) {
        this.passengerName = passengerName;
    }
}

public class Main {
    public static void main(String [] args) throws InterruptedException{
        Bus someCompany = new Bus();

        Passenger p1 = new Passenger(someCompany,"Name1");
        Passenger p2 = new Passenger(someCompany, "Name2");

        p1.start();
        p2.start();

    }
}

Does my solution satisfy the task? I want to make sure to do so and to improve my solution.


texts:
This code is part of a data model used to create keyword records in a database.

if (_queue
    .OrderByDescending(record=>record.Primary)
    .GroupBy(record=>record.Term)
    .Select(record=>record.First())
    .Select(Create)
    .Any(result=>result <= 0))
{
    throw new ModelException("Failed to create keyword record.");
}

While I can understand this, I was also thinking it was a little obfuscated.

Is the intent of this code clearly readable?


texts: Use different contructors of disposable class

texts:
I have a very simple helper class to validate credentials. Sometimes the domain has a value, sometimes not. Depending on this, a different constructor for PrincipalContext must be used. PrincipalContext is disposable, so I am using using. It looks ugly, and recommendations?

public class LDAPManager : ILDAPManager
{
    public bool ValidCredentials(string username, string password, string domain)
    {
        using (var context = string.IsNullOrWhiteSpace(domain) ? new PrincipalContext(ContextType.Domain) : new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(username, password);
        }
    }
}


texts:
Just a fun batch file I have made. I wanted an easy way to loop any arbitrary command several times: loopme.bat

@echo off
SETLOCAL
echo LoopMe v1.0

IF "%~1"=="/?" (GOTO HELP)
IF "%~1"=="" (GOTO HELP)
IF "%2"=="" (SET TIMEOUT=1) ELSE (SET TIMEOUT=%2)
SET COMMAND=%~1
SET COUNTER=0

:RUN
SET /A COUNTER=%COUNTER% + 1
CMD /C "%COMMAND%"
echo.
echo Command  : "%COMMAND%"
echo Times run: %COUNTER%
CHOICE /C QC /N /T %TIMEOUT% /D C /M "Press Q to quit, otherwise wait %TIMEOUT% second(s) to run again."
IF "%ERRORLEVEL%"=="1" (GOTO EOF) ELSE (GOTO RUN)

:HELP
echo Perform the same command in a loop.
echo Commands containing ^& or ^| must be escaped with ^^
echo Commands containing variables must be escaped with ^^ in the varible name
echo Optionally specify loop time. Default is 1 second.
echo.
echo Usage: loopme dir 2
echo               [run dir in current, loop 2 seconds]
echo.
echo        loopme "cls ^& netstat -an ^| find ".109""
echo               [clear screen then run netstat with find filter, loop 1 second]
echo.
echo        loopme "echo %%^time%%"
echo               [display the time, loop 1 second]
echo
echo.

:EOF

Any improvements or suggestions?

p.s this is my new way to annoy colleagues who leave their workstation unlocked:

loopme "color %^time:~9,2% ^&echo. ^& echo. ^&echo. ^& echo YOU HAVE BEEN HACKED!! ^& echo. ^&echo."


texts:
Is there any security threat here?

$con = mysqli_connect("***", "***", "***", "***");
mysqli_query($con, "set names 'utf8'");
$id = $_GET["id"];
$result = mysqli_query($con,"SELECT * FROM document_$id");
while($row = mysqli_fetch_array($result)) {// echo table }

I am curious about my use of the $_GET variable, since that can be altered by a user. If there is a danger here, could something like this work?

If $_GET['id'] is not an integer -> redirect to error page


texts: sh script to open related URL based on possible nicknames

texts:
I'm new to sh and I would like to get feedback on how I can improve my code.
The purpose is simple; I want to open the Jenkins JOB related to a service based on its possible aliases. If I map a service with its aliases, READ_JOB="rj readjob read-job", I want to open it by calling the script opendeploy readjob or opendeploy rj.
The link between aliases and URLS to open was easy; an associative array worked.
But I wanted to link: Service Name, Job URL and Possible Services Aliases.
I Google to see if this can be done. But it looks like sh does not support nested arrays. I have created 2 arrays with the same keys.
#!/bin/bash

__READ_JOB="db-restore"

##Services x Aliases
declare -A SERVICES=(
    ["${__READ_JOB}"]="rj readjob read-job"
)

#Services x Jobs Links
declare -A JOBS_URL=(
    ["${__READ_JOB}"]="https://relatedJobUrl.com"
)

function opendeploy(){
  build=0
  rootJenskinsUrl='https://defaultUrlIfNoParameters.com/'
  urlToOpen=$rootJenskinsUrl
    while [ "$1" != "" ]; do
      __getJobLink "$1"
          if [ "$1" = -b ] || [ "$1" = --build ]; then
            build=1
          fi
          if [ "$1" = -h ] || [ "$1" = --help ]; then
            ##Calling the method that explains how to use if the user use the "-h or -help"
            __usage
            return
          fi
      shift
  done

    ##Checking if -b parameter was filled, so we can append a build parameter at the end of the url
    if [ "$build" = "1" ] && [ "$urlToOpen" != "$rootJenskinsUrl" ]; then
      urlToOpen+='/build?delay=0sec'
    fi

  open $urlToOpen
}

__usage()
{
    ##This is why I need the association with the service name to well display: Service - Possible Aliases
    echo "usage: opendeploy service [[ [-b]] | [-h]]\n (no parameters opens root Jenkins URL)\n"

    echo "Possible Services - Aliases:\n"
    for k in "${(@k)SERVICES}"; do
      echo "$k -" "$SERVICES[$k]"
    done

}

function __getJobLink() {
    for k in "${(@k)SERVICES}"; do
      for alias in $SERVICES[$k]
      do
        if [ "$alias" = "$1" ]; then
          urlToOpen=${JOBS_URL[$k]}
        fi
      done
    done
}

I see points of improvements:

Not to use global variables at the beginning of the script.
Find a way to not create 2 associative arrays.

PS: This is running in a ZSH profile. I needed to adapt because bash was not recognising some things.
I do not wait to someone 'solve it' for me. I want suggestions on what I could do to improve my code.


texts: SQL Stored Procedure to export specified data

texts:
I'm currently using a stored procedure(sproc) to export to Excel. The sproc is being passed two parameters for @month and @year. The parameters are then passed to a dynamic pivot table in order to display all the days of the month for the specified month and year.

It does currently work, however are there better ways I could improve my code in order for it be more efficient? Any help or advice would be greatly appreciated as I'm still a bit of a beginner with SQL (and C# for that matter).

Alter Procedure stpDateRange
-- Add parameters
@month int , @year int
As
Begin
Set NoCount ON

    DECLARE @Dates NVARCHAR(max);

SELECT @Dates = CONCAT(@Dates + ', ', QUOTENAME(BalDate))
FROM tblID
WHERE YEAR(BalDate) = @year
  AND MONTH(BalDate) = @month
GROUP BY BalDate
ORDER BY BalDate;

DECLARE @DynSql NVARCHAR(max);
SET @DynSql = 'SELECT *
FROM
(
 SELECT a1.IDNbr , a2.[CustName] as [Name] , (CAST(a1.BalDate AS date)) as BalDate, a1.Balance
 FROM tblID a1
 RIGHT JOIN tblCust a2 ON (a1.IDNbr = a2.IDNbr)
 WHERE MONTH(a1.BalDate) = @month
   AND YEAR(a1.BalDate) = @year AND a2.CustType != ''Inactive'') as d1
PIVOT (
 Sum(Balance)
 FOR BalDate IN ('+ @Dates +')
) piv';

DECLARE @Params NVARCHAR(500) = N'@year int, @month int';

-- SELECT @DynSql AS DynSql;

 EXECUTE sp_executesql @DynSql, @Params, @year = @year, @month=@month;

End

Test results (dates will continue until the last day of the month):

+-----------------------------------------------------------------+
| IDNbr | Name    | 1/1/2018 | 1/2/2018 | 1/3/2018 | 1/4/2018 | ..|
|-----------------------------------------------------------------|
| 52852 | CustOne | 52028.52 | 52038.59 | 52048.69 | 52058.89 | ..|
| 39512 | CustTwo | 95125.75 | 95225.75 | 95325.75 | 95425.75 | ..|
| 52852 | CustThr | 86225.95 | 87225.95 | 88225.95 | 89225.95 | ..|
| 52852 | CustFor | 12533.12 | 12543.12 | 12553.12 | 12563.12 | ..|
| 52852 | CustFiv | 69585.36 | 69685.36 | 69785.36 | 69885.36 | ..|
| ..... | ....... | ........ | ........ | ........ | ........ | ..|

Readability for the results isn't awful , so that wouldn't be a concern for me, especially with how small the program is that is running this. My main concern is the performance of the stored procedure (sproc).


texts: VBA Copy and Delete Rows loop optimisation

texts:
I'm trying to identify which cells in Column C in a spreadsheet of data are dates and if they are, then check if that date is older than 2 years old. If the second condition is met then the below code should copy the entire row from sheet "DUP_ALL" to a new sheet (Archive) and then delete the copied row from the "DUP_ALL" sheet.

I believe it works but I was wondering if there are any better ways to optimise my code.

Is it more efficient to stay in the first loop and copy and delete the rows at the same time or is it better to copy all the rows, then loop through a second time deleting all the rows that meet the same criteria.

I tried doing a copy and then delete in the same for loop to begin with but it kept producing an error "Run Time 1004: Method 'Range' of Object '_worksheet' failed"

Any help with optimising the below is greatly appreciated

Sub TestArchive()
Dim sh As Worksheet, lr As Long, rng As Range, sh2 As Worksheet, lr2 As Long, c As Range
Set sh = Sheets("DUP_ALL") 'Edit sheet name
Set sh2 = Sheets("Archive") 'Edit Sheet name
lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
Set rng = sh.Range("C2:C" & lr)

For Each c In rng
    If IsDate(c.Value) Then
        If c.Value < Date - 456 Then
            lr2 = sh2.Cells(Rows.Count, 1).End(xlUp).Row + 1
            c.EntireRow.Copy sh2.Range("A" & lr2)
            End If
        End If
    Next
For Each c In rng
    If IsDate(c.Value) Then
        If c.Value < Date - 456 Then
            lr1 = sh.Cells(Rows.Count, 1).End(xlUp).Row + 1
            c.EntireRow.Delete sh.Range("A" & lr1)
            End If
        End If
    Next
End Sub


texts: Try a speculative, concurrent, lock free, atomic update until abort condition matches

texts:
Please let me know if you see any performance improvements, bugs, or anything you'd change and why.

    public static bool TrySpeculativeUpdate(ref int field, out int result,
        Func<int, int> update, Func<int, bool> shouldAbort)
    {
        SpinWait spinWait = new SpinWait();
        while (true)
        {
            int snapshot = field;
            if (shouldAbort(field))
            {
                result = 0;
                return false;
            }
            else
            {
                int calc = update(snapshot);
                if (Interlocked.CompareExchange(ref field, calc, snapshot) == snapshot)
                {
                    result = calc;
                    return true;
                }
            }

            spinWait.SpinOnce();
        }
    }

Can be used like this

    private bool TryIncreaseCapacity(out int newCapacity)
    {
        return TrySpeculativeUpdate(ref _currentCapacity, out newCapacity,
            (currentCapacity) => currentCapacity + 1,
            (currentCapacity) => currentCapacity == _maxCapacity);
    }

    if (this.TryIncreaseCapacity(out newCapacity))
    {
        ...
    }
    else
    {
        ...
    }

What I'm really trying to accomplish is the fastest thread safe version of Interlocked.Increment that will stop incrementing at a max value and I will have some way of detecting it stopped incrementing.


texts:
Ax, Ay, Az: [N-by-N]
B=AA (dyadic product)

means

B(i,j)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)]

B(I,j): a 3x3 matrix.

One way to construct B is:

N=2;
Ax=rand(N); Ay=rand(N); Az=rand(N);
t=1;
F=zeros(3,3,N^2);
for  i=1:N
    for j=1:N
        F(:,:,t)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)];
        t=t+1;      %# t is just a counter
    end
end
%# then we can write
B = mat2cell(F,3,3,ones(N^2,1));
B = reshape(B,N,N)';
B = cell2mat(B);

Is there a faster way than this, especially when N is large?


texts:
I am trying to optimize my reducer code, preferably into one-liner with high-order-functions.

Reducer should return new array with names of groups, with new number.

Below are correct inputs and outputs:

Input:        |          Output:
              |
[]            |          ['A1']
['A1']        |          ['A1', 'A2']
['A1', 'A3']  |          ['A1', 'A2', 'A3']
['WORD', 'A2']|          ['WORD', 'A2', 'A1']

Code below is part of switch-case block:

case DrivesPageActions.DrivesPageActionTypes.AddCustomGroup:
  if (state.customGroups.includes('A1') === false) {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A1']
    };
  } else if (state.customGroups.includes('A2') === false) {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A2']
    };
  } else {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A3']
    };
  }


texts:
I have a function that has, as input, a ranges object which may define from, to and limit. Note that it might have one, two or all three of them.

I want the output to be a saneRanges object, where if partial values are provided, the other ones are inferred.

For example if only limit is provided, from should be 0 and to should be limit-1.

This is the code I wrote during prototyping. I made sure I took zero shortcuts, as I didn't want smarty pants code make debugging harder.

But now... here I am. I have this lame code, and I want to find the bestest way to write it.

How would you rewrite this, so that it doesn't look quite so terrible?

  sanitizeRanges: function( ranges, skipHardLimitOnQueries ){
    var self = this

    var saneRanges = {};
    if( ! self.hardLimitOnQueries ) var hardLimitOnQueries = 0;

    saneRanges.from = 0;
    saneRanges.to = 0;
    saneRanges.limit = 0;

    if( typeof( ranges ) === 'object' && ranges !== null ){

      // Copy values over to saneRanges
      saneRanges.from = ranges.from || -1;
      saneRanges.to = ranges.to || -1;
      saneRanges.limit = ranges.limit || -1;

      var sr = saneRanges;

      // Sorry, no shortcuts here for now. Code will be optimised later
      // (maybe)

      // Case: Nothing is set
      if( sr.from === -1 && sr.to === -1 && sr.limit === -1 ){
         sr.from = 0;
         sr.to = self.hardLimitOnQueries;
         sr.limit = self.hardLimitOnQueries;

      // Case: Only "limit" is set
      // - Set "from" and "to"
      } else if( sr.from === -1 && sr.to === -1 && sr.limit !== -1 ){
        sr.from = 0;
        sr.to = sr.limit - 1;

      // Case: Only "from" is set
      // - Set "to" and "limit"
      } else if( sr.from !== -1 && sr.to === -1 && sr.limit === -1 ){
        sr.limit =  0;
        sr.to  = 0;

      // Case: Only "to" is set
      // - Set "from" and "limit"
      } else if( sr.from === -1 && sr.to !== -1 && sr.limit === -1 ){
        sr.from = 0;
        sr.limit =  sr.to + 1;

      // Case: Only "from" and "limit" are set
      // - Set "to"
      } else if( sr.from !== -1 && sr.to === -1 && sr.limit !== -1 ){
        sr.to =  sr.from + sr.limit - 1;

      // Case: Only "from" and "to" are set
      // - Set "limit"
      } else if( sr.from !== -1 && sr.to !== -1 && sr.limit === -1 ){
        sr.limit =  sr.to - sr.from + 1;

      // Case: Only "to" and "limit" are set
      // - Set "from"
      } else if( sr.from === -1 && sr.to !== -1 && sr.limit !== -1 ){
        sr.from = 0;
      }

      // Make sure "limit" never goes over
      if(  sr.limit != 0 && sr.from + sr.limit - 1 > sr.to ){
        sr.limit =  sr.to - sr.from + 1;
      }

    }

    // Apply hard limit on queries if required to do so. Driver implementations
    // should only pass 'true' for non-cursor queries, to prevent huge toArray() on
    // a million records
    if( ! skipHardLimitOnQueries ){
      if( self.hardLimitOnQueries && ( saneRanges.limit === 0 || sr.limit > self.hardLimitOnQueries ) ){
        saneRanges.limit = self.hardLimitOnQueries;
      }
    }

    return saneRanges;

  },


texts: Django template block name changing function

texts:
I created a reusable function for changing block name in Djago templates. I want to know if the code is good or is there any probable issues in it. I developed the function as a hack for the following issue.

Template Code

{% extends base_name %}

{% block main-contents %}

{{ message_heading }}

        {{ message }}

        {% if btn_1_text and btn_1_url %}
            {{ btn_1_text }}
        {% endif %}

        {% if btn_2_text and btn_2_url %}
            {{ btn_2_text }}
        {% endif %}

{% endblock %}

Function to change block name

def change_block_names(template, change_dict):
    """
    This function will rename the blocks in the template from the
    dictionary. The keys in th change dict will be replaced with
    the corresponding values. This will rename the blocks in the
    extended templates only.
    """

    extend_nodes = template.nodelist.get_nodes_by_type(ExtendsNode)
    if len(extend_nodes) == 0:
        return

    extend_node = extend_nodes[0]
    blocks = extend_node.blocks
    for name, new_name in change_dict.items():
        if blocks.has_key(name):
            block_node = blocks[name]
            block_node.name = new_name
            blocks[new_name] = block_node
            del blocks[name]

tmpl_name = 'django-helpers/twitter-bootstrap/message.html'
tmpl1 = loader.get_template(tmpl_name)
change_block_names(tmpl1, {'main-contents': 'new-main-contents'})
return HttpResponse(tmpl.render(Context()))

This function seems to work for my issue. But I don't know if this breaks any of the Django's functionality. Can anyone verify this and give me some advice?


texts: Is this "unsafe" declaration unnecessary?

texts:
I have a class that I inherited from someone else. It is doing a P/Invoke on CopyFileEx to copy a file (we are using UNC shares if that matters). The code is marked unsafe but I thought you only needed to use that when dealing with raw pointers, if you are using IntPtr only your code does not need to be marked unsafe.

public void Copy()
{
    bool result;

    unsafe
    {
        if (System.Environment.OSVersion.Version.Major > 5)
        {
            //only newer versions of windows support the no buffer flag
            //(this is set because copying large files on a computer with limited ram will pretty much kill the computer)
            result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, CopyFileFlags.COPY_FILE_NO_BUFFERING);
        }
        else
        {
            result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, 0);
        }
    }

    //file copy failed so get the DLL error and throw an exception
    if (result == false)
    {
        Win32Exception exc = new Win32Exception(Marshal.GetLastWin32Error());
        throw exc;
    }
}

//xcopy file progress event handler
private CopyProgressResult CopyProgressEvent(Int64 TotalFileSize, Int64 TotalBytesTransferred, Int64 StreamSize, Int64 StreamBytesTransferred, uint dwStreamNumber,
                                                   XCopy.CopyProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
{
    //chunk of a file finished copying
    if (dwCallbackReason == XCopy.CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)
    {
        int currentFilePercent = Convert.ToInt32(Math.Round(TotalBytesTransferred * 100.0 / TotalFileSize));

        //only send a new message when something changes (prevents flooding of messages)
        if (currentFilePercent != LastFilePercent)
        {
            LastFilePercent = currentFilePercent;

            //Report back the progress
            ProgressCallback.Report(currentFilePercent);
        }
    }

    //stop the copy?
    if (Cancelflag == 1)
        return XCopy.CopyProgressResult.PROGRESS_CANCEL;
    else
        return XCopy.CopyProgressResult.PROGRESS_CONTINUE;

}

//win32 API call
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName,
    CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel,
    CopyFileFlags dwCopyFlags);

//xcopy event handler
public delegate CopyProgressResult CopyProgressRoutine(
                    Int64 TotalFileSize,
                    Int64 TotalBytesTransferred,
                    Int64 StreamSize,
                    Int64 StreamBytesTransferred,
                    uint dwStreamNumber,
                    CopyProgressCallbackReason dwCallbackReason,
                    IntPtr hSourceFile,
                    IntPtr hDestinationFile,
                    IntPtr lpData);

I think the unsafe is not needed but the person who wrote this originally claims he was getting intermittent errors during run-time when in production environments when it was not marked unsafe.

Was he right about needing unsafe or did he have a problem elsewhere that was just fixed at the same time that made it look like unsafe fixed the issue?


texts: what is Null Test in java? and how to rewrite the code to do the same by avoiding null test

texts:
I would like to know what is null test in java? How to rewrite the below code by  avoiding null test. I was asked this question in an online test. I'll be grateful for any help offered.

String mystere() throws IOException {
      InputStream input = null;
      try {
        input = new InputStream(new File("foo.txt"));
        return new Scanner(input).nextLine();
      } finally {
        if (input != null)
          input.close();
      }
    }


texts: Truncating text with jQuery but keep the HTML formatting

texts:
I repeat here this answer on Stack Overflow.

I first posted an answer with not finalized code, as a simple description of the solution I could think, without any test. But later I remained interested, so I worked to make it (hopefully) perfectly functional.

To precisely define what it is meant to do, let me cite my previous answer:

  This is a classic dilemma for any CMS or blog, where the teaser should present the begin of an article: often the solution is either stripping text from its tags and cut at a precise count OR keep tags but cut approximately because the tags are counted too...

So here the intent is to take an HTML element with any number of children, and any nesting level and return:

the "same" element (i.e. keeping its tag and attributes)
where resulting text content (i.e. visible as characters in the resulting page) is limited to a given count
where resulting text is built from successive text nodes in their natural order
where encountered tags are keeped intact and at their natural place

Here is my actual solution:

function cutKeepingTags(elem, reqCount) {
  var grabText = '',
      missCount = reqCount;
  $(elem).contents().each(function() {
    switch (this.nodeType) {
      case Node.TEXT_NODE:
        // Get node text, limited to missCount.
        grabText += this.data.substr(0,missCount);
        missCount -= Math.min(this.data.length, missCount);
        break;
      case Node.ELEMENT_NODE:
        // Explore current child:
        var childPart = cutKeepingTags(this, missCount);
        grabText += childPart.text;
        missCount -= childPart.count;
        break;
    }
    if (missCount == 0) {
      // We got text enough, stop looping.
      return false;
    }
  });
  return {
    text:
      // Wrap text using current elem tag.
      elem.outerHTML.match(/^<[^>]+>/m)[0]
      + grabText
      + '</' + elem.localName + '>',
    count: reqCount - missCount
  };
}

And here is a working example. (I kept the HTML example posted by the previous question OP)


texts: Check if two numbers are the same in a box

texts:
I am making a Sudoku game and I have managed to add random numbers, add numbers, and to checklines (if there is 2 numbers on the same line). I am trying to check the 3x3 boxes if the number is twice or more in the same box. I have managed to do it one way, but is this the easiest way? In that case I need to do this 81 more times, or is there a better way?

 bool checkBox(){
int box1[3][3];

for (int i = 0; i <= 2; i++){
    for (int j = 0; j <= 2; j++){
        box1[i][j] = board[i][j];
    }
}

if (box1[0][0] != 0){
    if (box1[0][0] == box1[0][1] || box1[0][0] == box1[0][2] || box1[0][0] == box1[1][0] || box1[0][0] == box1[1][1]
        || box1[0][0] == box1[1][2] || box1[0][0] == box1[2][0] || box1[0][0] == box1[2][1] || box1[0][0] == box1[2][2]){
        return true;
    }
}


texts: Route structure for multiple associations in Rails

texts:
I'm doing a site at the moment (first Rails site, learning as I code) and I'm concerned that I'm over complicating the routes.

My associations boil down to:

class Recipe < ActiveRecord::Base
    has_and_belongs_to_many :categories
    belongs_to :book
end

class Category < ActiveRecord::Base
    belongs_to :category_type
    has_and_belongs_to_many :recipes
end

class Book < ActiveRecord::Base
  has_many :recipes
end

I want to end up with URLs like this:

/books/3/recipes  #to show all recipes from book 3
/category/12/recipes #to show all categories from category 12
/recipes/3  #to show recipe 3

The good news is I have this all working, but in the course of doing so I feel like I may have strayed a little from "the Rails way" and I was wondering if someone could take a look and let me know if I've gone wrong. The bits I'm particularly concerned about are my routes.rb file (because I appear to be repeating myself):

resources :books do
  resources :recipes
end

resources :categories do
  resources :recipes
end

In particular, the recipes#index action, which seems a little verbose:

def index

  if(params[:category_id])
    @recipes = Recipe.find_by_category(params[:category_id])
  elsif(params[:book_id])
    @recipes = Recipe.where(:book_id => params[:book_id])
  else
    @recipes = Recipe.find(:all)
  end
end

Now, it might be that this is all absolutely fine, but I just want to check before I get too much further in!


texts:
I'm writing simple jQuery script for updating one field on another field's change. It's working, but I'm trying to write good code and use best practices. Can you please tell me what my mistakes and 'bad' things in this code?

Maybe I should use getTotalUserScore() in updateTotalUserScore(), not in $('.js-question-score').change() function, or I shouldn't use 2 functions for so simple piece of logic, or my variables names are bad. Tell me anything you feel about this code. Also, I've realized that my total-score field sometimes updates with delay.

$('.js-question-score').change(function () {
    var totalScore = getTotalUserScore();
    updateTotalUserScore(totalScore);
});

function updateTotalUserScore(totalScore) {
    $('.js-total-user-score').text(totalScore)
}

function getTotalUserScore() {
    var totalScore = 0;
    $('.js-question-score').each(function() {
        totalScore += parseInt($(this).val());
    });
    return totalScore;
}

<form>
  <input class="js-question-score" name="first" min="0" max="20"  value="0" type="number"/>
  <input class="js-question-score" name="second" min="0" max="20"  value="0" type="number"/>
  <input class="js-question-score" name="third" min="0" max="20"  value="0" type="number"/>
</form>

  User total score:

    0


texts: Displaying TimeSpan as largest interval (with units) - Part II

texts:
[This is a follow-up question to: Displaying TimeSpan as largest interval (with units). The code listed here has been refactored since the original question was posed. Please note that the scope of this question is limited to the declaration and implementation of the listed method.]

The method listed below is used in a call center application to display an approximation of remaining time. For example, a call center telephone operator might inform a caller that they could perform their desired action after N time has elapsed, e.g., "Yes, that's right, you can order samples again in 2 days." Some arbitrary rules revolving around the interpretation of time are embedded within the method, e.g., an interval greater than 50 minutes is considered to be one hour; these business rules need to remain as is.

With that in mind, are there any suggestions on how this routine might be further enhanced and/or made more efficient?

public static string LargestIntervalWithUnits(TimeSpan interval)
{
    if (interval < TimeSpan.Zero)
    {
        throw new ArgumentOutOfRangeException("interval",
                                              "Negative Timespans are not supported.");
    }

    // Numeric literals defined per business rules
    const double MinimumHoursDeemedOneDay = 22.0;
    const double MinimumMinutesDeemedOneHour = 50.0;
    const double MinimumSecondsDeemedOneMinute = 40.0;
    const double MinimumMillisecondsDeemedOneSecond = 500.0;

    int timeValue;
    string timeUnits;

    if (interval.TotalHours > MinimumHoursDeemedOneDay)
    {
        timeValue = (int)Math.Ceiling(interval.TotalDays);
        timeUnits = "day";
    }
    else if (interval.TotalMinutes > MinimumMinutesDeemedOneHour)
    {
        timeValue = (int)Math.Ceiling(interval.TotalHours);
        timeUnits = "hour";
    }
    else if (interval.TotalSeconds > MinimumSecondsDeemedOneMinute)
    {
        timeValue = (int)Math.Ceiling(interval.TotalMinutes);
        timeUnits = "minute";
    }
    else if (interval.TotalMilliseconds > MinimumMillisecondsDeemedOneSecond)
    {
        timeValue = (int)Math.Ceiling(interval.TotalSeconds);
        timeUnits = "second";
    }
    else
    {
        return "now";
    }

    return string.Format("{0:#,##0} {1}{2}",
                         timeValue,
                         timeUnits,
                         (timeValue == 1 ? string.Empty : "s"));
}


texts: Sum of nodes at a given depth of a binary tree (String representation)

texts:
Given a binary tree of integers and a depth, the goal is to find the sum of all node values at the depth in the tree. The root is considered depth 0, and the tree is given as a string in the format: (<node-value>(<left subtree>)(<right subtree>)). For example, treeLevelSum("(5(42)(-37(28)()))", 1) should return 5.

int treeLevelSum(String tree, int k) {
    int sum   = 0;

    int depth = 0;
    int value = 0;
    int sign  = 1;
    for (int i = 1; i < tree.length(); i++) {
        if (tree.charAt(i) == '(') {
            depth += 1;
        } else if (tree.charAt(i) == ')') {
            sum   += value * sign;
            value  = 0;
            sign   = 1;
            depth -= 1;
        } else if (depth == k) {
            if (tree.charAt(i) == '-') {
                sign = -1;
            } else {
                value = value * 10 + (tree.charAt(i) - '0');
            }
        }
    }

    return sum;
}

I was just wondering if there was a better way of parsing this, or if there was any way of improving efficiency? Is there a known "best solution" for this kind of problem?


texts: Can this date-validation function can be simplified further or is it the correct approach?

texts:
I am doing a date validation. I have no. of pages, which have the date field. User can input the date like "220875" or "22AUG75" - I need to test both and check the length as well.

function isValidDate(newDate) {

    newDate[1] = newDate[1]-1;
    newDate[2] = (parseInt(newDate[2]) < 50) ? 2000 + parseInt(newDate[2]) : 1900 + parseInt(newDate[2]);

    var testDate = new Date(newDate[2], newDate[1], newDate[0]);

    if (testDate.getDate()!=newDate[0] || testDate.getMonth()!=newDate[1] || testDate.getFullYear()!=newDate[2]) {
        return false;
    } else {
        return {valid : true, date : testDate};
    }

}

var sandBox = {
    init:function(params){
        this.element = $(params.element),
        this.value = params.value,
        this.mode = params.num;
    },
    isNotEmpty:function(){
        if(!this.value.length) {
           this.errorHandler(this.emptyMsg);
        } else {
            this.errorHandler(true);
            return true;
        }
    },
    errorHandler: function (msg) {
        var errorHolder = this.element.siblings('span');
        if(msg !== true)
            errorHolder.html(msg).show();
        else errorHolder.html("").hide();
    },
    emptyMsg : "Date field should not be empty",
    digitLengthMsg : "The Length of the value should be ",
    onlyNumber : {
        num : /\D/,
        str : /^\d{2}[a-zA-Z]{3}\d{2}$/,
        mon : /[a-zA-Z]{3}/,
        msg : "Only Digits allowed"
    },
    getMonthFromString : function(mon){
        var month =  new Date(Date.parse(mon +" 01, 12")).getMonth()+1;
        month = month < 10 ? '0'+ month : month;
        return month;
    },
    isValidData : function () {

        var result =  this.onlyNumber.str.test(this.value);

        if(this.mode && result) {
            this.errorHandler(this.onlyNumber.msg)
            return false;
        }
        else if (!this.mode && result) {
            var currentMonth = this.getMonthFromString(this.value.match(this.onlyNumber.mon)[0]);
            this.value = this.value.replace(/([a-zA-Z]){3}/g, currentMonth);
            return true;
        }
        else if (this.mode && this.value.length !== 6) {
            this.errorHandler(this.digitLengthMsg + '6');
            return false;
        }
        else if (!this.mode && this.value.length !== 7) {
            this.errorHandler(this.digitLengthMsg + '7');
            return false;
        }
        else {
            this.errorHandler(true);
            return true;
        }
    },

    DateIsOk:function() {
        if(this.isNotEmpty() && this.isValidData()) {
            var verifyDate = this.value.match(/.{1,2}/g);
            return isValidDate(verifyDate);
        }
    }

};

var dateValidator = function (e) {
    var value = e.target.value;
    sandBox.init({
        value : value,
        element : e.target,
        num : true //set month status true means validation by digits, false means digits with string
    });

   var fieldValue = sandBox.DateIsOk();

   if(fieldValue) {
    console.log(fieldValue);
   }

};

var dateField = $('input');
dateField.on('keyup focusout', dateValidator);

Live Demo


texts:
I'm new learning python and image processing with python. For this reason, I took a project called "Classification of breast cancer images with deep learning".

I applied the following techniques: 1)Threshold, 2)K-Means

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

img = cv2.imread('n001.tif', 0)
_, blackAndWhite = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV)

nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(blackAndWhite, None, None, None, 8, cv2.CV_32S)
sizes = stats[1:, -1] #get CC_STAT_AREA component
img2 = np.zeros((labels.shape), np.uint8)

for i in range(0, nlabels - 1):
    if sizes[i] >= 100:   #filter small dotted regions
        img2[labels == i + 1] = 255

res = cv2.bitwise_not(img2)

cv2.imwrite('n001New.tif', res)
########################################################################

img = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)

Z = img.reshape((-1,3))
Z = np.float32(Z)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 250 , 1.0)

K=2
ret, label, center= cv2.kmeans(Z, K, None, criteria, 250,
                                  cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
output = res.reshape((img.shape))

plt.imshow(output)

plt.show()

Data set consists of tif extension image: benign, inSitu, invasive and normal

Output images:

I have a few questions:

Are my methods correct?
Are the outputs correct? Do I find the right areas?
Did I use the K-Means algorithm correctly?

I would appreciate it if you could answer the questions above.


texts: Multiple View Controllers in a Single Window (Swift on OS X)

texts:
As an exercise I want to have a single window application (in Swift on Mac OS X) with 4 views, each controlled by an independent view controller and have their own XIB file. I have working code, but I feel I've done it the wrong way, so the question is have I used a bad design pattern?

My main concern is the empty views in the main window (see first image). I want these replacing with the target views (from VC1,2,3,4), as opposed to adding the target views as subviews to the empty views.

//  MainWindowController.swift

import Cocoa

class MainWindowController: NSWindowController {
    @IBOutlet weak var viewForVC1: NSView!
    @IBOutlet weak var viewForVC2: NSView!
    @IBOutlet weak var viewForVC3: NSView!
    @IBOutlet weak var viewForVC4: NSView!

    override func windowDidLoad() {
        super.windowDidLoad()

        let vc1 = VC1()
        let vc2 = VC2()
        let vc3 = VC3()
        let vc4 = VC4()

        viewForVC1.addSubview(vc1.view)
        viewForVC2.addSubview(vc2.view)
        viewForVC3.addSubview(vc3.view)
        viewForVC4.addSubview(vc4.view)
    }

    override var windowNibName: String? {
        return "MainWindowController"
    }
}

//  AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var mwc: MainWindowController!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        mwc = MainWindowController()
        mwc.showWindow(self)
    }
}

There is a Swift file and XIB for each view controller and view.

//  VC1,2,3,4

import Cocoa

class VC1: NSViewController {
    override var nibName: String? {
        return "VC1" // <-- swap the number here, (for VC1,2,3,4.swift)
    }

}

The end result is:


texts: Why is my function timing out when run with a larger data set?

texts:
I am working on a Code Kata

// There is a queue for the self-checkout tills at the supermarket.
// Your task is write a function to calculate the total time
// required for all the customers to check out!
// input
// customers: an array of positive integers representing the queue.
//    Each integer represents a customer, and its value is the amount
//    of time they require to check out.
// n: a positive integer, the number of checkout tills.

A common solution is

function queueTime(customers, n) {
  // create a new array to represent each till
  // start each till at 0 minutes
  const tills = new Array(n).fill(0);
  // loop through the customers
  for (let i = 0; i < customers.length; i++) {
    // find till with least minutes
    const shortestTill = Math.min(...tills)
    // find index of shortest till
    const index = arr.indexOf(shortestTill)
    // increase shortest till mins with current customer
    arr[index] += customers[i];
  }
  // return the longest till
  return Math.max(...tills);
}

My first solution, although longer, seems to work however it times out when I run it in node with a large data set.  I am sure there is probably some time complexity issue or infinite loop that I am creating but can not identify.

Where in my code should I refactor to fix this issue?

function queueTime(customers, n) {
  // checking edge case
  if (customers.length === 0) return 0
  // initial time
  let time = 0
  // create a lookup to see if each till is open, where each
  //key is the till number and the val is the time needed for each to finish
  memo = {}
  for (let i = 1; i <= n; i++) {
    memo[i] = customers.shift()
  }
  // not necessarily needed because I'm using returns in the while loop,
  // but the intention is to break the loop
  let completed = false
  // solving the problem was taking two different approaches so
  // this variable allows me to check which approach to use
  let moreTillsThanCustomers = false
  // len = memo.length
  let len = Object.keys(memo).length
  for (let i = 1; i <= len; i++) {
    // if any didn't have a customer to fill the spot, then moreTillsThanCustomers = true
    if (memo[i] === undefined) {
      moreTillsThanCustomers = true
    }
  }
  if (!moreTillsThanCustomers) {
    while (!completed) {
      let found = false
      // if there are any open spots and customers left, we 'found' a spot to fill and can break out of the loop
      for (let i = 1; i <= len; i++) {
        if (memo[i] === 'open') {
          if (customers.length) {
            memo[i] = customers.shift()
              found = true
              break
          }
        }
      }
      // if no spot was found, increase the time by one  and reduce all
      // till times by 1 or to 'open
      if (!found) {
        time++
        for (let i = 1; i <= len; i++) {
          if (memo[i] === 1) {
            memo[i] = 'open'
          } else {
            memo[i]--
          }
        }
      }
      // if every value is 'open' and there are no customers left, we're done
      if (Object.values(memo).every(value => value === 'open')&& !customers.length) {
        completed = true
        return time
      }
    }
    // if there are more tills than customers
  } else {
    while (!completed) {
      // if a  memo is at 0, it's done, otherwise reduce it by one
      for (let i = 1; i <= len; i++) {
        if (memo[i] === 0) {
          memo[i] = undefined
        } else if (memo[i] !== undefined) {
          memo[i]--
        }
      }
      // if all are done, we're done
      if (Object.values(memo).every(value => value === undefined)) {
        completed = true
        return time
      }
      //increase time
      time++
    }
  }
  return time
}

Times out in node

console.log(
  queueTime([28, 9, 27, 37, 12, 33, 20, 31, 19, 18, 3, 8, 39, 40, 49], 5)
)


texts: Use of templates with templated Deck class

texts:
I have previous revisions of my deck of cards project, but I may not need to link them here since the emphasis is on the use of templates.

I've never used them before until now, and I like how intuitive my implementation has become.  However, I'm also aware that there are many pitfalls in C++ templates.  Although I don't think this implementation uses them heavily, I'd still like to know if I'm at a good start before I use them again.

I'm also a bit unsure about some of my naming now, considering this is a template class.  For instance, I've changed add()'s parameter from card to item because it cannot be assumed that the user will only use cards.  Although it makes sense to just use cards (or anything representing cards), it would not seem practical to limit the implementation to just that usage.  I would prefer this to be reusable.

Of course, I'm okay with any other improvements that can be made.

Deck.hpp

#ifndef DECK_HPP
#define DECK_HPP

#include <algorithm>
#include <stdexcept>
#include <vector>

template <class T> class Deck
{
private:
    std::vector<T> original;
    std::vector<T> playable;

public:
    typedef typename std::vector<T>::size_type SizeType;

    void add(T const&);
    T draw();
    void reset();
    void shuffle();
    SizeType size() const { return playable.size(); }
    bool empty() const { return playable.empty(); }
};

template <class T> void Deck<T>::add(T const& item)
{
    original.push_back(item);
    playable.push_back(item);
}

template <class T> T Deck<T>::draw()
{
    if (playable.empty())
    {
        throw std::out_of_range("deck empty");
    }

    T top(playable.back());
    playable.pop_back();
    return top;
}

template <class T> void Deck<T>::reset()
{
    playable = original;
}

template <class T> void Deck<T>::shuffle()
{
    if (!playable.empty())
    {
        std::random_shuffle(playable.begin(), playable.end());
    }
}

#endif


texts:
A function that prints out the values of each of the bytes of a variable, which value is given from stdin.
Consists of size detector and a loop.

#include <stdio.h>
#include <math.h>

int main(void)
{
    unsigned char uint_8;
    unsigned short uint_16;
    unsigned long uint_32;
    unsigned long long uint_64, n = 0;

    int i;
    size_t size;

    printf("Enter a number: ");
    scanf("%lld", &n);

    if(n < 257) size = 1;
    if(n < 256*256 && n > 256) size = 2;
    if(n < 256*256*256 && n > 256*256) size = 3;
    if(n < pow(256, 4) && n > pow(256, 3)) size = 4;

    for(i = 0; i < size; i++)
    {
        unsigned char* p = (((unsigned char*)&n) + i);
        printf("byte(%i) : %i\n", i, *p);
    }

    return 0;
}

I don't like the size detection though, it could be more safely coded with one line of bit operations I believe.


texts:
I wrote the following JPA method that queries a database to return a distinct list of a String field (called mtfcc) of a Location object. I then took the list of strings to query for the associated name for that MTFCC.

Could I just modify the first query to get the results, without having to use the for loop to get the associated name field?

@Override
public Map<String, String> getAvailableBorderTypes() {

    // create empty map to store results in. If we don't find results, an empty hashmap will be returned
    Map<String, String> results = new HashMap<String, String>();

    EntityManager em = entityManagerFactory.createEntityManager();

    // get the distinct mtfcc's
    String jpaQuery = "SELECT DISTINCT location.mtfcc FROM Location location";

    // get the distinct mtfcc codes
    List<String> mtfccList = (List<String>) em.createQuery(jpaQuery).getResultList();

    // cycle through the mtfcc list and get the name to associate with it
    for (String mtfcc: mtfccList) {
        String nameQuery = "SELECT DISTINCT location.name FROM Location location WHERE location.mtfcc = ?1";
        String name = (String) em.createQuery(nameQuery).setParameter(1, mtfcc).getSingleResult();
        results.put(mtfcc, name);
    }

    return results;
}


texts: Convert date time string with non standard timezone offset in C#

texts:
I couldn't find a .NET date format type to handle dates in format I need to process, they sometimes have time zone offset with +/- prefix followed by 3 digits for the number of minutes timezone is offset by. i.e. +11:00 is written as +660

Usage Example:

GetDateTime("20161124181215.000000+660")

The function:

private DateTime GetDateTime(string input)
    {
        int timezoneIndex = input.IndexOf('+');
        if (timezoneIndex < 0) { timezoneIndex = input.IndexOf("-"); }

        if (timezoneIndex >= 0)
        {
            string utcTime = input.Substring(0, timezoneIndex - 1);
            string timezoneOperator = input.Substring(timezoneIndex, 1);
            string timezoneOffset = string.Format(
                    "{0}{1}",
                    timezoneOperator,
                    TimeSpan.FromMinutes(Convert.ToDouble(input.Substring(timezoneIndex + 1))).ToString("hh\\:mm"));

            return DateTime.ParseExact(
                string.Format("{0}{1}", utcTime, timezoneOffset),
                "yyyyMMddHHmmss.FFFFFFK",
                CultureInfo.InvariantCulture);
        }
        else
        {
            return DateTime.ParseExact(
                input,
                "yyyyMMddHHmmss.FFFFFF",
                CultureInfo.InvariantCulture);
        }
    }


texts:
The problem is to find the minimum number of moves that a knight will take to go from one square to another on a 'n' cross 'n' chessboard. The code below is based on backtracking. It works well until n equals 5 but from n equals 6 the time limit is exceeded on ideone. How can I make the code more efficient?

#include <stdio.h>

int minimum(int a, int b)
{
    /* Returns the minimum of two numbers */
    if (a <= b) {
        return a;
    } else {
        return b;
    }
}

int minmoves(int r1, int c1, int r2, int c2, int array[10][10], int n)
{
    int moves;

    /*
     * If the place is already occupied dont go to it otherwise it will
     * lead to a infinite loop so we return a large value so that the
     * knight does not take this path
     */
    if (array[r2][c2] == 1) {
        return 32764;
    }

    /* We cannot go outside the board */
    if ((r2 < 0) || (r2 > n - 1) || (c2 < 0) || (c2 > n - 1)) {
        return 32764;
    }

    /* Condition to check if the path is complete */
    if ((r1 == r2) && (c1 == c2)) {
        return 0;
    }

    /* We add the point with coordinates r2, c2 to the path */
    array[r2][c2] = 1;

    /* All the possible moves that a knight can make */
    moves = 1 + minmoves(r1, c1, r2 - 2, c2 - 1, array);
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 2, c2 + 1, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 1, c2 - 2, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 1, c2 + 2, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 1, c2 - 2, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 1, c2 + 2, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 2, c2 - 1, array));
    moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 2, c2 + 1, array));

    array[r2][c2] = 0;

    return moves;
}

int main()
{
    int r1, c1, r2, c2, x, i, j, n;
    int array[10][10];

    scanf("%d\n%d\n%d\n%d\n%d", &r1, &c1, &r2, &c2, &n);

    /* All the elements of array are initialised to zero */
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            array[i][j] = 0;
            printf("0 ");
        }
    }

    x = minmoves(r1, c1, r2, c2, array, n);

    printf("%d",x);
    return 0;
}


texts:
The following code allows users to enter multiple optional quantity fields after first filling in a value of the current quantity input. If the input field contains a value it will then display the next quantity field, if not, it will remove/not display it.

The code is currently working as intended but I don't believe that it follows the DRY principle very well. Is there a way to make this more succinct?

function quantityCheck() {
    var q1 = document.getElementById("Quantity1Value").value;
    if (q1 !== "") {
        document.getElementById("Quantity2").style.display = "";
    } else {
        document.getElementById("Quantity2").style.display = "none";
    }

    var q2 = document.getElementById("Quantity2Value").value;
    if (q2 !== "") {
        document.getElementById("Quantity3").style.display = "";
    } else {
        document.getElementById("Quantity3").style.display = "none";
    }

    var q3 = document.getElementById("Quantity3Value").value;
    if (q3 !== "") {
        document.getElementById("Quantity4").style.display = "";
    } else {
        document.getElementById("Quantity4").style.display = "none";
    }
}

    Quantity 1
    <input type="number" id="Quantity1Value" oninput="quantityCheck()" required>

    Quantity 2
    <input type="number" id="Quantity2Value" oninput="quantityCheck()">

    Quantity 3
    <input type="number" id="Quantity3Value" oninput="quantityCheck()">

    Quantity 4
    <input type="number" id="Quantity4Value">


texts:
I want to import in python some ascii file ( from tecplot, software for cfd post processing).
Rules for those files are (at least, for those that I need to import):
-The file is divided in several section
-Each section has two lines as header like:

VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen"
ZONE T="Window(s) : E_W_Block0002_ALL",  I=29,  J=17,  K=25, F=BLOCK

Each section has a set of variable given by the first line. When a section ends, a new section starts with two similar lines.
For each variable there are I*J*K values.
Each variable is a continous block of values.
There are a fixed number of values per row (6).
When a variable ends,the next one start in a new line.
Variables are "IJK ordered data".The I-index varies the fastest; the J-index the next fastest; the K-index the slowest. The I-index should be the inner loop, the K-index shoould be the outer loop, and the J-index the loop in between.

Here an example of data:

VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen"
ZONE T="Window(s) : E_W_Block0002_ALL",  I=29,  J=17,  K=25, F=BLOCK
-3.9999999E+00 -3.3327306E+00 -2.7760824E+00 -2.3117116E+00 -1.9243209E+00 -1.6011492E+00
[...]
0.0000000E+00 #fin first variable
-4.3532482E-02 -4.3584235E-02 -4.3627592E-02 -4.3663762E-02 -4.3693815E-02 -4.3718831E-02 #second variable, 'y'
[...]
1.0738781E-01 #end of second variable
[...]
[...]
VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen" #next zone
ZONE T="Window(s) : E_W_Block0003_ALL",  I=17,  J=17,  K=25, F=BLOCK

I am quite new at python and I have written a code to import the data to a dictionary, writing the variables as 3d numpy.array . Those files could be very big, (up to Gb).  How can I make this code faster?(or more generally, how can I import such files as fast as possible)?.

import numpy as *
from numpy.linalg import norm
import re

def vectorr(I, J, K):
    arr = empty((I*J*K, 3), int)
    arr[:,0] = tile(arange(I), J*K)
    arr[:,1] = tile(repeat(arange(J), I), K)
    arr[:,2] = repeat(arange(K), I*J)
    return arr

def all_data(pathfilename,NumberCol = 6):
    with open(pathfilename) as a:
        filelist = a.readlines()
        Count = 0
        data = dict()
        leng = len(filelist)
        Countzone = 0
        while Count < leng:
            strVARIABLES = re.findall('VARIABLES', filelist[Count])
            variables = re.findall(r'"(.*?)"',  filelist[Count])
            Countzone = Countzone+1
            data[Countzone] = {key:[] for key in variables}
            Count = Count+1
            strI = re.findall('I=....', filelist[Count])
            strI = re.findall(r'\d+', strI[0])
            I = int(strI[0])
            strJ = re.findall('J=....', filelist[Count])
            strJ = re.findall(r'\d+', strJ[0])
            J = int(strJ[0])
            strK = re.findall('K=....', filelist[Count])
            strK = re.findall(r'\d+', strK[0])
            K = int(strK[0])
            data[Countzone]['indmax'] = array([I, J, K])
            pr = prod(data[Countzone]['indmax'])
            lin = pr // NumberCol
            if pr % NumberCol != 0 :
                lin = lin+1
            vect = vectorr(I, J, K)
            for key in variables:
                init = zeros((I, J, K))
                for ii in range(0, lin):
                    Count = Count+1
                    temp = [ float(x.replace('D', 'E')) for  x in filelist[Count].split() ]
                    for iii in range(0, len(temp)):
                        init.itemset(tuple(vect[ii*NumberCol+iii]), temp[iii])
                        data[Countzone][key] = init
            Count = Count+1
    return data


texts:
I am using RxJava with retrofit to get data from an API then filtering the data with a for loop in the onNext Method.  Is there any way not to use the for loop and just use RxJava to filter or improve the code?

 _subscriptions.add(
                jamSpeakServiceApi.getAllWords()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<List<WordApi>>() {
                            @Override
                            public void onCompleted() {
                                Log.d("retroffit Completed", "Completed");
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.d("retroffit error", e.toString());
                            }

                            @Override
                            public void onNext(List<WordApi> wordApis) {
                                /*Observable.from(wordApis)
                                        .filter(s -> Word.getWordFormDatabase(s.getWord()) != null)
                                        .filter(s -> s.getCountry().toLowerCase().equals("jamaica"))
                                        .filter(s -> Word.getWordLikeFormDatabase(s.getWord()) != null)
                                        .subscribe();*/

                                for (WordApi x: wordApis){
                                    if(x.getCountry().toLowerCase().equals("jamaica")== true){
                                        Word.saveWordFromApi(x);
                                        Log.d(x.getWord(),x.getWord());
                                    }
                                }

                            }
                        })
        );


texts:
I have a function in App Engine Java where I compare two patterns stored in an int array:

public static int patternMatch(int [] pattern1, int [] pattern2, int range) {

    int max = range * pattern1.length;

    int match = (pattern1.length - pattern2.length) * range;

    for(int i = 0; i < pattern2.length; i++) {
        match += Math.abs(pattern1[i] - pattern2[i]);
    }

    return (max - match) * 100 / max;
}

I am facing very weird problems with respect to performance of this function between the development server and deployment on app engine as listed below:

This function is called in a loop with the intention of finding best match(es).
Performance for a single iteration is critical as there are lot of iterations.
If I were to not have any logic in this code and directly return any integer, my overall code takes 100 ms to complete on an average.
The above code takes anywhere between 200 - 600 ms.
On the development server, if I replace

int match = (pattern1.length - pattern2.length) * range;

by

int match = Math.abs(pattern1.length - pattern2.length) * range;

somehow the performance improves bringing the time taken down to 200 - 300 ms only. No impact on deployment server.
If I remove Math.abs, the performance improves, bringing the average to 150 ms.
I tried replacing Math.abs with bit operations to derive absolute value. I see huge performance improvement on development server ~160 ms. On deployment server it makes things worse ~700 ms.

What I would like to know here is:

Why and how differently do Development server (Windows 7/eclipse/JDK6) and Deployment server behave in terms of performance tweaks?
Is there any better algorithm to the match?


texts: Smallest difference of pair in String-array

texts:
Let's say I have the following array of Strings:

String[] rows = new String[]{
  "",
  "A",
  "B C C",
  "",
  "B D E",
  "E F G H"
};

As well as the following pairs:

String[] pairs = new String[]{
  "H F",
  "A B",
  "A E",
  "G B"
};

How can I calculate the smallest difference between the two pairs in the array? So the output would be the following for the pairs:

"H F" -> 0   // (both in the 6th item of the array)
"A B" -> 1   // (2nd and 3rd items of the array)
"A E" -> 3   // (2nd and 5th items of the array; 2nd and 6th would be larger)
"G B" -> 1   // (5th and 6th items of the array; 3rd and 6th would be larger)

I have been able to accomplish this with the following code, but I have the feeling this can be done better/shorter instead of the three nested for-loops..

int[] calculateMinDistanceOfPairs(String[] rows, String[] pairs){
  // Result int-array:
  int rowLength = rows.length,
              c = 0,
              d = rowLength,
              i,j;
  int[] result = new int[pairs.length];
  // Loop (1) over the pairs:
  for(String pair : pairs){
    // Inner loop (2) over the rows
    for(i=1, d=rowLength; i<rowLength; i++){
      // If the current row contains the first item of the pair:
      if(rows[i].contains(pair.split(" ")[0])){
        // Inner loop (3) over the rows again
        for(j=1; j<rowLength; j++){
          // If the current row contains the second item of the pair:
          if(rows[j].contains(pair.split(" ")[1])){
            // Change `d` to:
            d =
                j-i > 0 ?   // If j-i is larger than 0:
                 j-i < d ?  //  If j-i is smaller than `d`:
                  j-i       //   `d` is now j-i
                 :          //  Else:
                  d         //   `d` remains the same
               :            // Else (i-j is larger than or equal to 0):
                 i-j < d?   //  If i-j is smaller than `d`:
                  i-j       //   `d` is now i-j
                 :          //  Else:
                  d;        //   `d` remains the same
          }
        } // End of inner loop (3)
      }
    } // End of inner loop (2)
    // Add `d` to the result-array:
    result[c++] = d;
  } // End of loop (1)
  return result;
}

Try it in this online compiler.


texts: String reverse and pairing reversed words

texts:
These are questions from an interview:

Reverse a string
Find matching anagrams in a word list

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

namespace ConsoleApplication2
{
public class ReverseString
{
    public ReverseString()
    {
        string str = "Gilad";
        string res = Reverse(str);

        List<string> wordsList = new List<string>();
        wordsList.Add("batel");
        wordsList.Add("Gilad");
        wordsList.Add("daliG");
        wordsList.Add("enon");
        wordsList.Add("none");
        wordsList.Add("letab");
        var pairs = PairAnagramWords(wordsList);
    }

    public string Reverse(string str)
    {
        StringBuilder s = new StringBuilder();
        for (int i = str.Length - 1; i >= 0; i--)
        {
            s.Append(str[i]);
        }
        return s.ToString();
    }

    Dictionary<string, string> PairAnagramWords(List<string> wordsList)
    {
        wordsList.Sort();
        Dictionary<string, string> res = new Dictionary<string, string>();
        foreach (var item in wordsList)
        {
            if (res.ContainsValue(item))
            {
                continue;
            }

            foreach (var item2 in wordsList)
            {
                if (item == item2 || item.Length != item2.Length)
                {
                    continue;
                }
                var reversed = Reverse(item2);
                int i;
                for (i = 0; i < item.Length; i++)
                {
                    if (item[i] != reversed[i])
                    {
                        break;
                    }
                }
                if (i == item.Length)
                {
                    res.Add(item, item2);
                }
            }
        }
        return res;
    }
}

}

I don't like the fact that I'm doing it in \$ O(n^2) \$, although I am checking for no repetitions.

Please review my code's complexity and algorithm. I did the testing inside the constructor just for convenience, although I usually will use unit tests.


texts:
A couple of weeks I had a coding interview and the problem to solve was very simple: reverse the words order of a string. What did I do wrong here?

public static String reverse(String phrase) {
        String[] words = phrase.split(" ");
        StringBuffer sb = new StringBuffer();
        for (String word : words) {
            String reversed = new String();
            for (int j = word.length() - 1; j >= 0; j--) {
                reversed += word.charAt(j);
            }
            sb = sb.append(reversed).append(" ");
        }

        return sb.toString().substring(0, sb.toString().length() - 1);
    }


texts: SynchronizedArrayList implemented using reader writer synchronization

texts:
I am trying to understand the workings of reader writer locks. For the sake of learning, I implemented reader writer synchronization by my own. I implemented SynchronizedArrayList with reader writer synchronization.

I set out with following objective:

There can be many readers.
There can only be just one writer.
Fairness among writers. In other words, writers should be served in FIFO manner.

I request reviewers to provide feedback on following:

Correctness of code by considering the above set objectives.
Efficiency of code.
Any other improvements.

import java.util.ArrayList;

public class SynchronizedArrayList {
    private ArrayList<Object> list = new ArrayList<Object>();
    private int readerCount = 0;

    public void add(int index, Object obj)
    {
        synchronized(this) {
            while (readerCount != 0)
                waitForSignal();

            addInternal(index, obj);
        }
    }

    public Object get(int index) {
        synchronized(this) {
            readerCount++;
        }

        Object toReturn = getInternal(index);

        synchronized(this) {
            readerCount--;
            if (readerCount == 0) {
                this.notify();
            }
        }

        return toReturn;

    }

    private Object getInternal(int index) {
        return list.get(index);
    }

    private void addInternal(int index, Object obj) {
        list.add(index, obj);
    }

    private void waitForSignal() {
        //not yet implemented
    }
}


texts: Making a ul list element animation on hover

texts:
I have an experimental script that makes an animation of a ul list element background-position, when the list element is hovered. Is there another way to manage this task or just optimize this code?

I want to make a menu that has elements with an animated background and have an idea about rotoscope style design or something in that direction. I'm thinking in cross-browser compatibility way too. In this stage this code runs fine in Opera, Internet Explorer 6, Chrome, Firefox 2.0, and Firefox 4.0.

jsFiddle

$(document).ready(function(){
  $("li.animate").hover(
    function () {

      var param = '0 0';
      ids = setInterval(function() {
        if ( c >= 5 ) {
          c = 1;
          $('.animate').css('backgroundPosition', '0 0');
        }
        else {
          param = (-100 * c++ )+'px 0';
          //alert(param);
          $('.animate').css('backgroundPosition', param);
          if ( c > 4 ) $('.animate').css('backgroundPosition', '0 0');
        }
      }, 40);
    },
    function () {
      $('.animate').css('backgroundPosition', '0 0');
      clearInterval(ids);
    }
  );
});


texts:
This is my first PowerShell script. It reads the event logs of several computers in the local network and lists error/warning messages written to them in the last 24 hours, if any.

I'll appreciate any suggestion to improve my code.

$computers = 'COMP1','COMP2','COMP3','COMP4'
$logs = 'Log1','Log2','Log3','Log4'
$yesterday = (Get-Date).AddDays(-1)

foreach ($comp in $computers) {
    try {
        $events = Get-WinEvent @{logname=$logs; starttime=$yesterday; level=2,3} -ComputerName $comp -ErrorAction Ignore;

        if ($events.count -gt 0) {
            $count = $events.count;
            "$comp $count event(s):";
            $events | select logname, providername, timecreated, leveldisplayname, message `
                    | Format-Table -AutoSize;
        } else {
            "$comp no events";
        }
    }
    catch {
        "$comp error!!! $_";
    }
}


texts: Python rsync to copy the logs from multiple remote servers

texts:
I have the below code which i'm working to copy(using rsync) the contents From remote host labserver01 and dumps those into the directory /var/log/infoSec/ on the base system from where scripts runs and this works correctly and sends e-mail to the recipients, However i'm also figuring out to include a way to send e-mail even if it fails.

I'm Just wondering if there is better way do this, i'm sure there will be more elegant ways.

Appreciate any idea and review in advance.

#!/usr/bin/python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import subprocess
import argparse
import sys
import os

#Dir Structure
dest_dir = "/infralogs/external_dns_logs"
rsync_user = "root"

email_sender = "dnslogger@udalt.com"
email_receiver = "gusain@udalt.com"
msg = ""

parser = argparse.ArgumentParser()
parser.add_argument("-n","--hosts",dest="hosts",help="enter remote host/hosts name, comma seperated",metavar="HOSTS")
parser.add_argument("-s","--src",dest="source",help="source file/directory",metavar="SOURCE")
parser.add_argument("-e","--exclude",dest="exclude",help="Exclude files/Directories, comma seperated list",metavar="EXCLUDE")

if len(sys.argv) < 7:
    print(len(sys.argv))
    parser.print_help()
    parser.exit()

args = parser.parse_args()

def sync(host,dest_dir):
    exclude = ""
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)
    if ',' in args.exclude:
        for excl in args.exclude.split(','):
            exclude = exclude + " --exclude " + excl
        cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz %s %s@%s:%s %s/"%(exclude,rsync_user,host,args.source,dest_dir)
    else:
        cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz --exclude %s %s@%s:%s %s/"%(args.exclude,rsync_user,host,args.source,dest_dir)
    cmd_content = cmd
    p = subprocess.Popen(cmd,shell=True)
    p.wait()
    print("DONE")
    return cmd_content + " Rsync process completed."  # returns the msg to the caller

msglist = []             # a list to store the cmd_contents for the mail body

if ',' in args.hosts:
    for host in args.hosts.split(','):
        dest = dest_dir + "/" + host
        msglist.append(sync(host,dest))
else:
    dest = dest_dir + "/" + args.hosts
    msglist.append(sync(args.hosts,dest))

msg = "\n".join(msglist)                 # combine all cmd_contents, one per line

try:
    Mail = smtplib.SMTP('mailserver.global.udalt.com', 25, 'localhost.udalt.com')
    mail_obj = MIMEMultipart('alternative')
    mail_obj["From"] = email_sender
    mail_obj["To"] = email_receiver
    mail_obj["Cc"] = "gusain@udalt.com"
    mail_obj["Subject"] = "Rsync process completed Successfully."
    mail_obj.attach(MIMEText(msg, 'plain'))
    Mail.sendmail(from_addr=[email_sender], to_addrs=[email_receiver],msg=mail_obj.as_string())
    print("Mail Sent to %s" % (email_sender))
except Exception as error:
    print("Mail Failed - {}".format(error))

Command Execution method:

  $ /usr/bin/dns_rsync.py  -n labserver01 -s /var/log/infoSec/ -e "null"


texts:
I have developed the following javascript code for creating "widgets" that a third party site can paste onto their page and load content from our web application. Everything is working, and I am in the process of thoroughly testing before we present it for use to our clients (as we don't want any issues to occur that would negatively affect their sites, or any changes to be required on our end that would cause them to have to re-paste the code).

The code which a client includes on their page is:

And the code contained within widget-script.js is as followed (this is just a basic template void of any business logic):

var UniqueWidgetName = UniqueWidgetName || (function(window, document){ "use strict";

    var _args = {};
    var jQuery, $;
    var url = "https://yoursite.com";

    function main(){

        // load required css
        loadCSS(url + "/widgets/your.css");

        // business logic here including usage of loaded jquery version,
        // usually involves doing an ajax call to obtain some data
        // and place it within the 'unique-widget-name-container' div

    }

    function loadCSS(url){
        var css_link = $('<link>',{
            rel: "stylesheet",
            type: "text/css",
            href: url
        });
        css_link.appendTo('head');
    }

    function loadScript(url, callback){
        var scriptTag = document.createElement('script');
        scriptTag.setAttribute("src", url);
        if(typeof callback !== 'undefined'){
            if(scriptTag.readyState){ // for older ie versions
                scriptTag.onreadystatechange = function(){
                    if(this.readyState === 'complete' || this.readyState === 'loaded'){
                        callback();
                    }
                };
            } else {
                scriptTag.onload = callback;
            }
        }
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
    }

    return {
        init: function(Args){
            _args = Args;
            loadScript("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js", function(){
                // restore $ and window.jQuery to their previous values and store the
                // new jQuery in our local jQuery variables
                $ = jQuery = window.jQuery.noConflict(true);
                main();
            });
        }
    };

/* END OF LIBRARY
*******************************************************************************/
})(window, document);

My main concern at this point is dealing with jquery conflicts. I believe the way I have implemented jQuery.noConflict() should resolve this potential issue, but
I wanted someone else to confirm this before a production deployment.

Also, does anything else jump out as being a potential issue? Is there anything you would do differently?


texts: Golang unbuffered channel - Correct Usage

texts:
Here is an example where I'm trying to understand the concepts of buffered channels> I have three functions and create a buffered channel of length 3. And also passed a waitgroup to nofiy when all the goroutines are done. And finally collecting the values through range.
Could you please help me in reviewing this code? And where I could improve?
package main

import (
    "fmt"
    "sync"
)

type f func(int, int, chan int, *sync.WaitGroup)

func add(x, y int, r chan int, wg *sync.WaitGroup) {
    fmt.Println("Started Adding function....")
    r <- (x + y)
    wg.Done()
}

func sub(x, y int, r chan int, wg *sync.WaitGroup) {
    fmt.Println("Started Difference function")
    r <- (x - y)
    wg.Done()
}

func prod(x, y int, r chan int, wg *sync.WaitGroup) {
    fmt.Println("Started Prod function")
    r <- (x * y)
    wg.Done()
}

func main() {
    var operations []f = []f{add, sub, prod}
    ch := make(chan int, len(operations))
    wg := sync.WaitGroup{}

    x, y := 10, 20

    wg.Add(len(operations))
    for _, i := range operations {
        go i(x, y, ch, &wg)
    }
    wg.Wait()
    close(ch)
    for val := range ch {
        fmt.Println(val)
    }

}


texts:
I'm messing around with JavaScript and am trying out objects, functions & arrays.  I'd like to know if someone has tips about making it better, shorter, or has a better solution for what I have thought about for now. What I've tried to do is just do simple math (+ and -) using arrays as input for numbers.  It all works, but I'm just wondering if it could be even better and/or cleaner.

//Write the result
function ap(n) {
    $(".value").append(n);
}

// Make sure the input is a number
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function doMath(options) {
    var defaults = {
        method: 'add'
    };
    var options = $.extend({}, defaults, options);

    // Add
    if(options.method == 'add') {
        var n = 0;
        for(var i=0; i<options.numbers.length; i++) {
            if(isNumber(options.numbers[i])) {
                n = n + options.numbers[i];
            }
            if(i===options.numbers.length-1) {
                ap(n);
            }
        }
    }

    // Subtract
    if(options.method == 'subtract' ) {

        for (var i=0; i<options.numbers.length; i++) {
            if(i===0) {
                n = options.numbers[0];
            } else {
                if(isNumber(options.numbers[i])) {
                    n = n - options.numbers[i];
                }
            }

            if(i===options.numbers.length-1) {
                ap(n);
            }
        }
    }
}

//Print the result
doMath({'numbers': [10,5,2,2], 'method':'subtract'});


texts:
I know questions with this text has been asked and already answered, but my question is mainly limited to only one method of this flow and where it should be.

I have an assembly for Shape's area calculation (ShapeAreaCalculator) and this functionality is exposed to client program:

public enum ShapeType
{
    SquareShape,
    CircleShape,
    TriangleShape,
}
public interface IShape
{
    void CalculateArea();
    void ShowArea();
}
public class Square : IShape
{
    public void ShowArea()
    {
        Console.WriteLine("Logic For ShowArea of Square");
    }
    public void CalculateArea()
    {
        Console.WriteLine("Logic For CalcualteArea of Square");
    }
}
public class Circle : IShape
{
    public void ShowArea()
    {
        Console.WriteLine("Logic For ShowArea of Circle");
    }
    public void CalculateArea()
    {
        Console.WriteLine("Logic For CalculateArea of Circle");
    }
}
public class Triangle : IShape
{
    public void ShowArea()
    {
        Console.WriteLine("Logic For ShowArea of Triangle");
    }
    public void CalculateArea()
    {
        Console.WriteLine("Logic For CalculateArea of Triangle");
    }
}

Factory class:

public interface IShapeFactory
{
    IShape GetShape(ShapeType shapeType);
}
public class ShapeFactory : IShapeFactory
{
    public IShape GetShape(ShapeType shapeType)
    {
        switch(shapeType)
        {
            case ShapeType.SquareShape:
                return new Square();
            case ShapeType.CircleShape:
                return new Circle();
            case ShapeType.TriangleShape:
                return new Triangle();
            default :
                throw new ArgumentException();

        }
    }
}

And I'm using this at client side like this:

static void Main(string[] args)
{
    ShapeType selectedShape;
    while (true)
    {
        Console.WriteLine("Enter your choise");
        foreach (ShapeType shapeType in Enum.GetValues(typeof(ShapeType)))
        {
            Console.WriteLine((int)shapeType + " For " + Enum.GetName(shapeType.GetType(), shapeType));
        }
        int selection;
        if (int.TryParse(Console.ReadLine(), out selection) && Enum.IsDefined(typeof(ShapeType), selection))
        {
            selectedShape = (ShapeType)selection;
            break;
        }
    }
    CalculateAndShowAreaOfShape(selectedShape);
}
static void CalculateAndShowAreaOfShape(ShapeType selectedShape)
{
    IShapeFactory shapeFactory = new ShapeFactory();
    IShape currentShape = shapeFactory.GetShape(selectedShape);
    currentShape.CalculateArea();
    currentShape.ShowArea();
}

But now I am concerned about this method CalculateAndShowAreaOfShape(). If in the future some functionality added in the procedure of area calculation, client code will be needed to be modified. It is unnecessary coupling.

Should it be implemented at client end or somewhere in ShapeAreaCalculator assembly?

Also, is it good practice to ask for user input from assembly? (I think it will limit this assembly to be used in console application only.)


texts: Search for names in a hard-coded list of contacts

texts:
I am currently taking a class at my local community college for java programming as well as trying to learn as much as I can on my own time. I would like your opinion on a program I wrote that would display any results matching a user inputted search term. It works, but I feel like it could be written better or even be made more effective, I'm not sure as I am still kind of new to Java. Could you please let me know if I am doing anything wrong like bad coding habits, doing things that are more easily done with better code, or suggest anything you think I should improve upon.

package controller;
import java.util.Scanner;

public class PhoneListDemo {

    public static void main(String[] args) {

        promptUser();

    }
    public static void promptUser() {

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter a name or characters to search for: ");
        String userSearch = keyboard.nextLine();
        keyboard.close();
        searchAndDisplay(userSearch);
    }
    public static void searchAndDisplay(String userSearch) {

        String[] names = {"Harrison, Rose", "James, Jean", "Smith, William", "Smith, Brad"};
        String[] phone = {"555-2234", "555-9098", "555-1785", "555-9224"};

        for(int i = 0; i < names.length; i++) {

        if(names[i].toLowerCase().contains(userSearch.toLowerCase())) {

            System.out.println(names[i] + ":  " + phone[i]);

            }
        }
    }
}


texts: Extremely long if-or-or statement just feel wrong

texts:
I'm sure this is wrong, but I can't think of a cleaner way to do this. I'm looping through a set of column to identify which column identifies the company name, the test is true if one of a large number of tests are true.

if (heading.ToLower().Contains("organisation") ||
            heading.ToLower().Contains("business") ||
            (heading.ToLower().StartsWith("address.") && heading.ToLower().EndsWith(".surname")) || // A and B
            heading.ToLower().Contains("name") && !(nextHeading.ToLower().Contains("organisation") || // A and not any of B
                                                    nextHeading.ToLower().Contains("company") ||
                                                    nextHeading.ToLower().Contains("firm")) ||
 .......This goes on FAR to long (e.g. A == B, but (C != D and E != F)
 {
      test = true;
 }

The way I've currently coded it smells wrong (code smell is a bad sign), but using if-elseif-elseif.... feels just as wrong.

Is there a pattern that I'm missing that can simplify this?

Thanks,
Kevin


texts: Python Find All Adjacent Subsets of Set of Coins Which Have a Tails Minority

texts:
Given a sequence of heads and tails I want to find how many significant subsequences are in this sequence where the number of heads is not less than the number of tails. I want to achieve this in \$O(N \log N)\$ time.

Example input:
[ 'H', 'T', 'H', 'T', 'T', 'H' ]

Example output:

11

Explanation:

{H} {H} {H}
{H, T} {T, H} {H, T} {T, H}
{H, T, H}
{H, T, H, T}
{H, T, T, H}
{H, T, H, T, T, H}

I believe my current algorithm is \$O(N^2)\$. I solve the problem recursively, iterating with the list of coins sliced on either end.

Here is my current algorithm. Am I correct that this is \$O(N^2)\$ and is not \$O(N \log N)\$?

def count_sequences( data ):
    print go(range(0,len(data)),data)
seen = set()
def go(rang,data):
    if tuple(rang) in seen: return 0
    seen.add(tuple(rang))
    h = 0
    summ = 0
    if len(rang)==0: return 0
    for i in rang:
        if data[i] == 'H': h += 1
        summ += go(rang[1:],data)
        summ += go(rang[:-1],data)
    if len(rang) == 1:
        if h ==1: return 1
        else: return 0
    if h > (len(rang)-1)/2 :
        return 1 + summ
    else: return summ