texts:
Write the implementation for generating pattern part, and did some testing, seems good to me. But not sure if any functional bugs? If anyone find a functional bug, appreciate for the insights.

def findPattern(pattern):

    j = -1
    next = [-1] * len(pattern)
    i = 0 # next[0] is always -1, by KMP definition

    while (i+1 < len(pattern)):
        if (j == -1) or (pattern[j] == pattern[i]):
            i += 1
            j += 1
            if pattern[i] != pattern[j]:
                next[i] = j
            else:
                next[i] = next[j]
        else:
            j = next[j]

    return next

if __name__ == "__main__":

    print findPattern("aaaab")
    print findPattern("abaabc")


texts:
I have the following code that our users will use to embed a widget on their page:

var ttp_number = "1Z123489754897";
var ttp_key = "1234567890123457890123";
var ttp_width = 850;
var ttp_height = 650;
var ttp_m_width = 260;
var ttp_m_height = 200;

(function(){
    document.write('

');
    s=document.createElement('script');
    s.type="text/javascript";
    s.src="//example.com/embed.js";
    setTimeout("document.getElementById('ttp').appendChild(s);",1);
})();

Is there a way to reorganize or make this more compact (other than minifying)?

Right now the big list of variables feels inefficient just declaring them one at a time, but I'm not sure what the alternate would be.

NOTE: I need to keep the script as compact as possible as the people who are copy/pasting this code many times know very little (if any) javascript, so if they some massive block of code, they'll freak out or stand a bigger chance of screwing it up.


texts: Handler for an Android form to calculate a cross product

texts:
Button crossButton = (Button) findViewById(R.id.crossButton);
crossButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (!x1.getText().toString().equals("")) {
            if (!x2.getText().toString().equals("")) {
                if (!x3.getText().toString().equals("")) {
                    if (!y1.getText().toString().equals("")) {
                        if (!y2.getText().toString().equals("")) {
                            if (!y3.getText().toString().equals("")) {
                                double x1no = Double.parseDouble(x1.getText().toString());
                                double x2no = Double.parseDouble(x2.getText().toString());
                                double x3no = Double.parseDouble(x3.getText().toString());
                                double y1no = Double.parseDouble(y1.getText().toString());
                                double y2no = Double.parseDouble(y2.getText().toString());
                                double y3no = Double.parseDouble(y3.getText().toString());
                                double z1 = (x2no * y3no) - (x3no * y2no);
                                double z2 = (x3no * y1no) - (x1no * y3no);
                                double z3 = (x1no * y2no) - (x2no * y1no);
                                resultText.setText(getString(R.string.decimal_vector_output, z1, z2, z3));
                            } else { y3.setError("Needs value"); y3.requestFocus(); }
                        } else { y2.setError("Needs value"); y2.requestFocus(); }
                    } else { y1.setError("Needs value"); y1.requestFocus(); }
                } else { x3.setError("Needs value"); x3.requestFocus(); }
            } else { x2.setError("Needs value"); x2.requestFocus(); }
        } else { x1.setError("Needs value"); x1.requestFocus(); }
    }
});

How would I go about cleaning up these if statements and whatnot?

I've tried a few OR conditions and it seemed to break.

Help would be appeciated.


texts:
I am trying to create a method that reverses a string that will handle every case. So far the cases I have come up with are

""
"abcdef"
"abbbba"
null

I haven't been able to handle these conditions however

escape characters

"\n"
"\t"

Not sure how to make \n or \t into a string

special characters such as

áe

code:

public static String reverseStr(String str) {
    if ( str == null ) {
          return null;
    }
    int len = str.length();
    if (len <= 0) {
        return "";
    }
    char[] strArr = new char[len];
    int count = 0;
    for (int i = len - 1; i >= 0; i--) {
        strArr[count] = str.charAt(i);
        count++;
    }
    return new String(strArr);
}


texts: 3 textboxes with multiple value combinations to one output

texts:
I would like if someone who has more experience in JavaScript reviewed this. I went through and tried to minimize this as much as possible, but I still feel this could be smaller and more compact.

I am really just looking to see if my way of making a low-level solution in JavaScript needs to be a bit more polished.

function sum() {
    var b1 = document.getElementById('Text1').value;
    var b11 = parseInt(b1);
    var b2 = document.getElementById('Text2').value;
    var b22 = parseInt(b2);
    var b3 = document.getElementById('Text3').value;
    var b33 = parseInt(b3);

    var a = b11 || b22 || b33;
    var b = (b11 + b22) || (b11 + b33) || (b22 + b11) || (b22 + b33) || (b33 + b11) || (b33 + b22);
    var c = b11 + b22 + b33;

    if (a > 0) {
        document.getElementById('result').innerHTML = a;
    }
        else if (a < 1) {
            document.getElementById('result').innerHTML = "";
        }
    if (b > 0) {
        document.getElementById('result').innerHTML = b;
    }
    if (c > 0) {
        document.getElementById('result').innerHTML = c;
    }
}

CodePen Demo


texts:
I just want to ask if its okay to create many aspx pages. What i did was, i made a guitar store website that has 6 brands and each of them have their own webpage. The code is like this:

The aspx.cs code

public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
public List<guitarItem> guitarItemList { get; set; }
public string gBrand = "Ibanez";
protected void Page_Load(object sender, EventArgs e)
{
    guitarItemList = new List<guitarItem>();
    guitarItemList = ConnectionClassGuitarItems.GetGuitarItems(gBrand);

}

}

The aspx code

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="GuitarItems1.aspx.cs" Inherits="Pages_GuitarItems1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

 <% foreach (guitarItem gItem in guitarItemList) { %>

        <img src="<%= gItem.itemimage1 %>"/>

<%= gItem.brand %> <%= gItem.model %>

 <% } %>

</asp:Content>

The given code above will display the items of a guitar brand called "ibanez". The other brand would have the same code except for the string that was passed in the variable gBrand from the aspx.cs code. The second item would be in Pages_GuitarItems2 and i would pass a string called "Fender" for the second brand(so on and so forth).

And also for example if you click the brand called "Ibanez", it would have 8 guitar products in it and each have their own web page as well. I really have alot of aspx pages, thats the reason why i wanted to know if its okay to have many aspx pages or do i need to think of a way where i would just use a single webpage as template and supplement that to all brands(which i haven't really figured out yet).

Please feel free to suggest any solutions for this.


texts: Is this Recursion + Linq example inefficient?

texts:
I have a hierarchy of of groups, and I want to get a collection of all the lowest level groups (or leaves if we'll look at this as a tree).

I wrote the following code. Is it inefficient?

public static class FeatureWeightGroupExtensions
{
    public static IEnumerable<IFeatureWeightGroup> GetLeafGroups(this IFeatureWeightGroup featureWeightGroup)
    {
        return GetLeafGroupsRecursive(featureWeightGroup).ToList();
    }

    private static IEnumerable<IFeatureWeightGroup> GetLeafGroupsRecursive(IFeatureWeightGroup featureWeightGroup)
    {
        if (!featureWeightGroup.ChildGroups.Any())
            return Enumerable.Repeat(featureWeightGroup, 1);

        return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty<IFeatureWeightGroup>(),
                                                        (allGroups, group) =>
                                                        allGroups.Concat(GetLeafGroupsRecursive(group)));
    }
}


texts:
I have an array $autoload:

$autoload['models'] = array();
$autoload['libraries'] = array();
$autoload['helpers'] = array('url', 'lang');

and in my controller I call each model / library / helper in autoload with this function:

private function auto_register() {
        global $autoload;

        foreach ($autoload as $type => $names) {
            foreach ($names as $name) {
                switch ($type) {
                    case 'libraries':
                        $this->{$name . '_library'} = call_user_func_array(array($this->load, "library"), array($name));
                        break;
                    case 'models':
                        $this->{$name . '_model'} = call_user_func_array(array($this->load, "model"), array($name));
                        break;
                    case 'helpers':
                        call_user_func_array(array($this->load, "helper"), array($name));
                        break;
                    default: '';
                        break;
                }
            }
        }
    }

Is there simple way to refactor this function? This is working as it is, but I'm looking for a more elegant solution.


texts: Maximise adjacent numbers in a functional style (PE#11)


texts:
This bubble sort code is very slow compared to the original.

import time
import random
def bubble_sort(a):
    #setting my variables
    yes=0
    d=0
    #making a switch
    while yes==0:
        if d>=last_thing-1:
            d=0
        if a[0+d]>a[1+d]:

            #switching the order
            a[0+d],a[1+d]=a[1+d],a[0+d]

        d+=1
        if correct_order(a):
            #turning off the switch
            yes=1

    return(a)
def correct_order(a):
    for i in range(len(a)):
        if i != a[i]:
            return(False)
    return(True)
if __name__ == '__main__':
    #setting your range
    last_thing=1000+1
    #making the random list
    a= list(range(0,last_thing))
    random.shuffle(a)

    #easier setting
    currentsortingmethod=bubble_sort(a)
    #prints your sorted list
    print("--------------------------------------------------------------------------------\n",str(currentsortingmethod).strip('[]').replace(" ", "").replace("'",""))


texts:
We are implementing a Tree structure and came up with two possible Tree Implementations. Implementation-1 is a straight forward class while Implmentation-2 uses a nested Static Class.

  My Question to reviewers is what are the advantages/disadvantages of
  each of the methods below and what is the preferable way ?

Tree Implementation -1

 public class TreeNode<T> implements Serializable, Iterable<TreeNode<T>> {
      private static final long serialVersionUID = 1L;

      private T name;
      private TreeNode<T> parent;
      private List<TreeNode<T>> children;

    public TreeNode(T data) {
        this.name = data;
        this.children = new ArrayList<TreeNode<T>>();
    }

    public TreeNode<T> addChild(T child) {
        TreeNode<T> childNode = new TreeNode<T>(child);
        childNode.parent = this;
        this.children.add(childNode);
        return childNode;
    }

 }

Tree Implementation-2: Here, we use a Static Nested Class

 public class Node {

    public static class TreeNode1<T>  implements Serializable {

            private static final long serialVersionUID = 1L;

            private String name;
            private TreeNode1<T> parent;
            private List<TreeNode1<T>> children;

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

            public void addChild(TreeNode1<T> node) {
                if (children == null)
                    children = new ArrayList<TreeNode1<T>>();
                children.add(node);
                 node.parent = this;
            }

          }
    }


texts:
It looks like this is a really classical question, but I'd like to ask it one more time as all those solutions look quite long and complicated for me (maybe because I am dumb :) )

So this is a Graham convex hull algorithm from the very beginning of the "Real World Haskell" book. And a perimeter function just for the sake of implementing it.

Why did the authors define the Direction datatype when it only acts like
Ordering?

Is there any more elegant way to traverse through lists considering pairs?

Any suggestions would be appreciated

import Text.Printf
import Data.List (sortBy)
data Point = Point Int Int deriving (Show, Eq, Ord)

turn :: Point -> Point -> Point -> Ordering
turn (Point x2 y2) (Point x1 y1) (Point x3 y3) = compare ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)) 0

polarSort :: [Point] -> [Point]
polarSort points = sorted where
    pivot = minimum points
    sorted = pivot:(sortBy (\a b -> turn b pivot a) . filter (pivot /=)) points

grahamScan :: [Point] -> [Point]
grahamScan points = grahamScan' rest [p2, p1] where
    (p1:p2:rest) = polarSort points
    grahamScan' [] l = l
    grahamScan' (p:pointsLeft) (s1:s2:selectedPoints) = case turn s2 s1 p of
                                        GT -> grahamScan' (p:pointsLeft) (s2:selectedPoints) -- the turn is right, so we discard last selected point
                                        _  -> grahamScan' pointsLeft (p:s1:s2:selectedPoints) -- the turn is left, so we add another point to the list of selected ones

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt (fromIntegral ((x2 - x1)^(2 :: Int) + (y2 - y1)^(2 :: Int)))

perimeter :: [Point] -> Double
perimeter points@(p0:_) = dist p0 pn + rest where
    walk :: [Point] -> (Double, Point)
    walk [a] = (0, a)
    walk (p1:p2:ps) = (dist p1 p2 + next, lastPoint) where
        (next, lastPoint) = walk (p2:ps)
    (rest, pn) = walk points

main = do
    _ <- getLine
    content <- getContents
    putStrLn $ printf "%.1f" ((perimeter . grahamScan . map ((\([x, y]) -> Point x y) . map read . words) . lines) content)


texts: Summing digits of an alphanumeric string

texts:
I am going through the Java CodingBat exercises. Here is the one I have just completed:

  Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.

Here is my code:

public int sumDigits(String str) {

    StringBuilder strAppend = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            strAppend.append(str.charAt(i));
        }
    }

    int total = 0;
    String strDigits = strAppend.toString();

    for (int i = 0; i < strDigits.length(); i++) {
        total += Integer.parseInt(strDigits.substring(i, i+1));
    }

    return total;

}

My questions are:

Should I be using one for loop instead of two?
Is it correct to be converting to StringBuilder to avoid concatenating a string?
Is it right to convert from string to int towards the end of the method, or convert as the digits are found?


texts: Partition TPL Tasks in ASP.NET 4.0 for WCF Service

texts:
I would like to know if using partition code like this is ok to do to partition tasks in ASP.NET 4.0 inside of a WCF service.  My goal with this code is to try to do non-blocking calls without spinning up too many concurrent tasks on the server.

public static async Task<IEnumerable<string>> ExecuteTasks(IEnumerable<string> files)
    {
        ConcurrentBag<string> bag = new ConcurrentBag<string>();

        await Task.Factory.ContinueWhenAll(Partitioner.Create(files).GetPartitions(5).Select(partition => Task.Factory.StartNew(() =>
       {
           using (partition)
           {
               while (partition.MoveNext())
               {
                    string test = string.Format("File {2} is executing in thread {0} and {3} in background at {1}",
                                               Thread.CurrentThread.ManagedThreadId,
                                                DateTime.Now, partition.Current,
                                                Thread.CurrentThread.IsBackground);
                   Console.WriteLine(test);
                   bag.Add(test);
               }
           }
        }, TaskCreationOptions.LongRunning)).ToArray(), _ => { });

        return bag.ToList();
    }


texts: Searching for Duplicates in SQL Table with Confidence Score

texts:
Sometimes I'm not sure if my questions should be here or StackOverflow, so I appologize if this is the wrong place.

I have a SQL (MS SQL 2016) stored procedure that is evaluating data looking for duplicates.  Since not all data is present missing fields are blank ('') not NULL.  I compare the data and give a confidence score.

It works for the most part, however, it doesn't process any of the entries with a blank Company.  Ideally I think I'd want the blank company to be processed just like the other companies.  I'm not entirely confident that it is calculating correctly to catch everything.

SELECT
    ranking AS score,
    RankMapping.description AS code,
    'CUST' AS tablename,
    Duplicate.uid AS tableID,
    originalCustNo

  FROM (
        SELECT
            FirstCompany.uid AS originalCustNo,
            Duplicate.*,
            CASE WHEN FirstCompany.uid = Duplicate.uid THEN 1 ELSE 0 END
              + CASE WHEN FirstCompany.company = Duplicate.company THEN 1 ELSE 0 END
              + CASE WHEN FirstCompany.fname = Duplicate.fname AND FirstCompany.lname = Duplicate.lname THEN 1 ELSE 0 END
              + CASE WHEN FirstCompany.add1 = Duplicate.add1  AND FirstCompany.city = Duplicate.city THEN 1 ELSE 0 END
              + CASE WHEN FirstCompany.phone1 = Duplicate.phone1 THEN 1 ELSE 0 END
              + CASE WHEN FirstCompany.email = Duplicate.email THEN 1 ELSE 0 END
            AS ranking
          FROM
          (
            SELECT uid, company, fname, lname, add1, city, phone1, email
              FROM (
                    SELECT uid, company, fname, lname, add1, city, phone1, email,
                        ROW_NUMBER() OVER (PARTITION BY company ORDER BY uid) AS ordering
                      FROM #tmpCoreData
                   ) FC
              WHERE ordering = 1
          ) AS  FirstCompany
            JOIN #tmpCoreData Duplicate
              ON Duplicate.uid >= FirstCompany.uid
                AND Duplicate.company = FirstCompany.company) Duplicate
            JOIN (VALUES
                (6, 'Original'),
                (5, 'Duplicate'),
                (4, 'Duplicate'),
                (3, 'Likely Dupe'),
                (2, 'Possible Dupe'),
                (1, 'Not Likely Dupe'),
                (0, 'Individual')
  ) RankMapping(score, description)
    ON RankMapping.score = Duplicate.ranking
ORDER BY Duplicate.originalCustNo, Duplicate.ranking DESC

I put my data table and code into SQL Fiddle
I'd appreciate some fresh eyes and suggestions to improve.

Thanks!


texts: Let's "Iterator" through Fibonacci, forever and ever

texts:
Following-up to my previous question, this class is now based on an iterator. The class, instead of forcing the programmer to use up a bunch of memory just to get each progressive number once, they can now use an iterator. The class itself is also now based on an iterator, which makes my life easier too. No more initFirst()!

Edit note: the main method was there to test, and is there for no other reason.

import java.math.BigInteger;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 *
 */
public class InfiniteFibonacci {

    public static void main(String[] args) {
        InfiniteFibonacci i = new InfiniteFibonacci();
        System.out.println(i.getNumberAt(0));
        System.out.println(i.getNumberAt(100));
    }

    /**
     * The default starting amount of numbers in the sequence to be generated.
     */
    public static final int DEFAULT_STARTING_CAP = 64;

    private final Iterator<BigInteger> iterator = new FibonacciIterator();

    private List<SequencePart> parts;

    private int currentSize = 0;

    /**
     * Creates a new InfiniteFibonacci object, with the default
     * amount of numbers.
     */
    public InfiniteFibonacci() {
        this(DEFAULT_STARTING_CAP);
    }

    /**
     * Creates a new InfiniteFibonacci object, with the specified
     * amount of numbers.
     *
     * @param startCap
     *            The amount of numbers to generate. It will be rounded up to
     *            the nearest 16.
     */
    public InfiniteFibonacci(int startCap) {
        parts = new LinkedList<>();
        initTo(startCap);
    }

    private void initTo(int index) {
        for (; currentSize <= index; currentSize += SequencePart.SIZE) {
            SequencePart part = new SequencePart();
            for (int i = 0; i < SequencePart.SIZE; i++) {
                part.values[i] = iterator.next();
            }
            parts.add(part);
        }
    }

    /**
     * Gets the nth number in the sequence, zero-based.
     *
     * @param index
     *            the n as described
     *
     * @return the specified in the sequence, zero-based.
     */
    public BigInteger getNumberAt(int index) {
        if (index > currentSize) {
            initTo(index);
        }
        return parts.get(index / SequencePart.SIZE).values[index
                % SequencePart.SIZE];
    }

    /**
     * Provides a faster Iterator for code that uses only each
     * number once.
     *
     * @return An Iterator that iterates through each of the
     *         numbers.
     */
    public static Iterator<BigInteger> getIterator() {
        return new FibonacciIterator();
    }

    private class SequencePart {

        private static final int SIZE = 16;

        private BigInteger[] values = new BigInteger[SIZE];

        private SequencePart() {

        }

    }

    private static final class FibonacciIterator implements
            Iterator<BigInteger> {

        private BigInteger current = BigInteger.ONE;
        private BigInteger previous = BigInteger.ZERO;

        private FibonacciIterator() {

        }

        @Override
        public boolean hasNext() {
            // Always has next
            return true;
        }

        @Override
        public BigInteger next() {
            BigInteger temp = current;
            current = previous.add(current);
            previous = temp;
            return temp;
        }

    }

}

Concerns:

Was implementing Iterator<BigInteger> a good idea?
Was the changes an improvement, or was it "poison"?


texts:
Is there a more efficient way of writing this? It seems like so much redundancy that this can be greatly reduced. Basically the only difference is if isNodeWebkit is true then run a function using key code 113 or 112

    if (isNodeWebkit) {
        $(document).keyup(function (e) {
            if (e.which == 113) {
                $.ajax({
                    type: "POST",
                    url: "/submit/role/",
                    data: {},
                    dataType: "json",
                    success: function (admin) {
                        if (admin == true) {
                            window.location = urllink;
                        }
                    }
                });
            };
        });
    }
    else {
        $(document).keyup(function (e) {
            if (e.which == 112) {
                $.ajax({
                    type: "POST",
                    url: "/submit/role/",
                    data: {},
                    dataType: "json",
                    success: function (admin) {
                        if (admin == true) {
                            window.location = urllink;
                        }
                    }
                });
            };
        });
    };


texts: Join strings split with the python [::n] method into one string as they were before in one line

texts:
If you split a string like foobar with something like [::3], [1::3], [2::3] it will give you ['fb','oa','or']. I needed to then be able to rejoin that into foobar and I got given a challenge to make it in one line. This is my solution:

split_join = lambda t:''.join(''.join([s.ljust(len(max(t,key=len))) for s in t])[i::len(max(t,key=len))] for i in range(len(max(t,key=len)))).replace(' ','')

and I was wondering if there was any neater or shorter way to make this.

EDIT: I also want it to be able to deal with strings of uneven lengths


texts:
I could not find a solution from my book's website (student-level access) but I feel that I am missing something that I'm supposed to learn from this exercise.

Instructions: Balls are dropped from the opening of the board. Every time a ball hits a nail, it has a 50% chance of falling to the left or to the right. The piles of balls are accumulated in the slots at the bottom of the board.

Book's example:

Enter the number of balls to drop: 5
Enter the number of slots in the bean machine: 7

LRLRLRR

RRLLLRR

LLRLLRR

RRLLLLL

LRLRRLR

        0
        0
      000

My attempt:

import java.util.*;

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

        System.out.print("Enter number of balls to drop: ");
        int numberOfBalls = input.nextInt();
        System.out.print("Enter the number of slots in the bean machine: ");
        int numberOfSlots = input.nextInt();

        //Simulate drops
        int[] slots = new int[numberOfSlots];
        for (int i = 0; i < numberOfBalls; i++) {
            simulateDrop(slots);
        }

        //Display histogram
        for (int i = numberOfBalls; i > 0; i--) {
            for (int j = 0; j < slots.length; j++) {
                if (slots[j] >= i) {
                    System.out.print("0");
                }
                else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    public static void simulateDrop(int[] slots) {
        StringBuilder path = new StringBuilder(slots.length);
        int slotIndex = 0;
        int numberOfNails = slots.length - 1;
        for (int i = 0; i < numberOfNails; i++) {
            int direction = (int)(Math.random() * 2);

            if (direction == 0) {
                path.append("L");
            }
            else {
                path.append("R");
                slotIndex++;
            }
        }

        System.out.println(path.toString());
        slots[slotIndex]++;
    }
}


texts: Using functions to separate code for Fahrenheit to celsius conversion

texts:
I'm relatively new to programming, and I've been wondering about a problem such as this. How can I think about decomposing the code into its constituent functions? I went the simplest route I could, just putting the formula in its own function. I believe this makes the code more readable, but there's also a part of me that wants to put the while loop into a function as well.

Is there a good rule of thumb for separating my code into functions?

#include <stdio.h>

int fahr_to_celsius(int f);

/* print Farhenheit-Celsius table
   for fahr = 0, 20, ..., 300 *;
   use a function for conversion */
int main(void)
{
  int fahr, celsius;
  int lower, upper, step;

  lower = 0; /* lower limit of the temperature table */
  upper = 300; /* upper limit */
  step = 20; /* step size */

  fahr = lower;
  while (fahr <= upper) {
    celsius = fahr_to_celsius(fahr);
    printf("%d\t%d\n", fahr, celsius);
    fahr = fahr + step;
    }
}

int fahr_to_celsius(int fahr)
{
  int celsius = 5 * (fahr-32) / 9;
  return celsius;
}


texts:
Exercise 2.20.
The procedures +, *, and list take arbitrary numbers of arguments. One way to define such procedures is to use define with dotted-tail notation. In a procedure
definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any)
will have as values the initial arguments, as usual, but the final parameter's value will be a list of any remaining arguments. For instance, given the
definition

(define (f x y . z) )

the procedure f can be called with two or more arguments. If we evaluate

(f 1 2 3 4 5 6)

then in the body of f, x will be 1, y will be 2, and z will be the list (3 4 5 6). Given the definition

(define (g . w) )

the procedure g can be called with zero or more arguments. If we evaluate

(g 1 2 3 4 5 6)

then in the body of g, w will be the list (1 2 3 4 5 6).

Use this notation to write a procedure same-parity that takes one or more integers and returns a list of all the arguments that have the same even-odd
parity as the first argument. For example,

(same-parity 1 2 3 4 5 6 7)
(1 3 5 7)

(same-parity 2 3 4 5 6 7)
(2 4 6)

source
Please review my code.
I have implemented a helper procedure, called predmap (Note: I am not aware of (filter) before writing this exercise). It's identical to map, but the function argument is a predicate. The item will be added in the new list if the predicate is true.
(define (predmap pred lst)
    (if (null? lst) '()
        (let ((carst (car lst))
            (next (predmap pred (cdr lst))))
            (if (pred carst)
                (cons carst next)
                next))))

Here is the same-parity procedure:
(define (same-parity . lst)
    (if (null? lst) '()
        (cons
            (car lst)
            (predmap (if (even? (car lst)) even? (lambda (x) (not (even? x))))
            (cdr lst)))))

In the second argument to cons, I put the if statement in the function argument directly to avoid repeating the call to predmap in the code. But it seems to look complicated now.
How can I make this code better and faster? Is there a better solution? Perhaps one where we would not need procedures like predmap?


texts:
How can I improve and optimise this code?

#include <iostream>
#include <vector>

std::vector<bool> sieve_of_eratosthenes(int n)
{
    std::vector<bool> primes(n+1, true);
    primes[0] = false;
    primes[1] = false;

    for (int i = 2; i <= n; i++)
    {
        if (primes[i] == true)
        {
            for (int j = i * 2; j <= n; j += i)
            {
                primes[j] = false;
            }
        }
    }
    return primes;
}

int main()
{
    int n;
    std::cout << "Enter number :\n";
    std::cin >> n;
    std::vector<bool> result = sieve_of_eratosthenes(n);
    std::cout << "Prime numbers upto " << n << " is :\n";
    for (int i = 0 ; i < result.size(); i++)
    {
        if (result[i] == true)
        {
            std::cout << i << " ";
        }
    }
    std::cout << '\n';
}


texts: Code snippet for a method dealing with IDs from multiple threads

texts:
I have multiple threads calling a method, passing in an ID and value.

I have two constraints I need to place on this method:

Only one of the same ID can be processed at a time. Additional threads with the same ID must wait.
Subsequent calls with the same ID must be processed in the order they were received.

Here's an Example.

Method is called by four different threads with the parameters

ID 1 Value a
ID 2 Value b
ID 1 Value c
ID 1 Value d

Program should be able to process [ID 1 Value a] and [ID 2 Value b] immediately, * while [ID 1 Value c] and [ID 1 Value d] wait for [ID 1 Value a] to finish.
Once [ID 1 Value a] finishes, then the method runs for [ID 1 Value c] while [ID 1 Value d] waits.
When [ID 1 Value c] finishes the method runs for [ID 1 Value d].
If the method wrote the value to the console then I'd expect the output to be either a, b, c, d or b, a, c, d.

I've had a quick go at it but it's messy. I'm writing this post in hopes of getting an improved and abstracted code snippet for doing this.

Here is my attempt:

static object _lockObj = new object();
static Dictionary<int, Queue<ManualResetEvent>> runningIds = new Dictionary<int, Queue<ManualResetEvent>>();

public async Task TheMethod(int id, string val)
{
    ManualResetEvent enquedResetEvent = null;
    lock (_lockObj)
    {
        if (runningIds.ContainsKey(id))
        {
            enquedResetEvent = new ManualResetEvent(false);
            runningIds[id].Enqueue(enquedResetEvent);
        }
        else
        {
            runningIds.Add(id, new Queue<ManualResetEvent>());
        }
    }
    if (enquedResetEvent != null)
        enquedResetEvent.WaitOne();
    try
    {
        // DO LONG RUNNING TASK
        await Task.Delay(3000);
        Console.WriteLine(id + " " + val + " at time " + DateTime.Now.ToString("m:ss"));
    }
    finally
    {
        lock (_lockObj)
        {
            if (runningIds[id].Count > 0)
            {
                var dequedResetEvent = runningIds[id].Dequeue();
                dequedResetEvent.Set();
            }
            else
            {
                runningIds.Remove(id);
            }
        }
    }
}

Sample input and output would be:

List<Task> ts = new List<Task>();
ts.Add(Task.Run(() => new Test().TheMethod(1, "a")));
Thread.Sleep(10);
ts.Add(Task.Run(() => new Test().TheMethod(2, "b")));
Thread.Sleep(10);
ts.Add(Task.Run(() => new Test().TheMethod(1, "c")));
Thread.Sleep(10);
ts.Add(Task.Run(() => new Test().TheMethod(1, "d")));
Task.WaitAll(ts.ToArray());
// Output:
// 1 a at time 25:53
// 2 b at time 25:53
// 1 c at time 25:56 // note 3 second delay
// 1 d at time 25:59
// 1 e at time 26:02
// 1 f at time 26:05


texts:
I implemented a MVC Framework with Generic DAO and I would like know if is correct. I did not have developed yet the MySQLDAO.

My controller class

class ClienteController {
  public function __construct() {  }

  public function actionSubmit(){
      $objCliente = new Cliente();
      $objCliente->setNome($_POST['nome']);
      $objCliente->setCodigo($_POST['codigo']);
      $objCliente->getDAOFactory()->insert();
  }
}

DAO Class for client, persistence.

class ClienteDAO implements IRecord {
  const TABLE = 'cliente';

  private $campos = array(
                         "codigo" => "cliCod",
                         "nome"   => "cliNom"
                         );

  private  $DAOFactory;

  public function __construct() {
      $this->DAOFactory = new DAOFactory($this);
  }

  public function getDAOFactory() {
      return $this->DAOFactory->getInstance();
  }
}

Model class

class Cliente extends ClienteDAO {
  private $codigo;
  private $nome;

  public function __construct(){  }

  public function getCodigo() {
      return $this->codigo;
  }

  public function setCodigo( $codigo ) {
      if ( $codigo > 0 ) {
          $this->codigo = $codigo;
      }
  }

  public function getNome() {
      return $this->nome;
  }

  public function setNome( $nome ) {
      $this->nome = $nome;
  }
}

Database class

class MySQLDao implements iDAO {
    public function insert() {

    }

    public function update() {

    }

    public function delete() {

    }

    public function limit() {

    }

    public function orderBy() {

    }

    public function findAll() {

    }

    public function addColumns() {

    }

    public function addGroupBy() {

    }

    public function addOrderBy() {

    }

    public function addHaving() {

    }

    public function addCustomizedHaving() {

    }

    public function addColumSubQuery() {

    }

    public function addAnd() {

    }

    public function addOr() {

    }

    public function checkExistanceColumn() {

    }
}

Factory class

class DAOFactory {
  private $objeto;
  private $factory;

  public function __construct($obj, $banco = null) {
      $this->factory = $banco;
      $this->objeto = $obj;
  }

  public function getFactory() {
      return $this->factory;
  }

  public function setFactory($factory) {
      $this->factory = $factory;
  }

  public static function getInstance() {
      if ($this->getFactory() == null) {
          return new MySQLDAO($this->getObjeto());
      }
  }

  public function getObjeto() {
      return $this->objeto;
  }
}

Interfaces

interface IDAO {
  public function insert();
  public function update();
  public function delete();
  public function limit();
  public function orderBy();
  public function findAll();
  public function addColumns();
  public function addGroupBy();
  public function addOrderBy();
  public function addHaving();
  public function addCustomizedHaving();
  public function addColumSubQuery();
  public function addAnd();
  public function addOr();
  public function checkExistanceColumn();
}

interface IRecord {
  public function getDAOFactory();
}


texts: Adding a specific list of numbers to an array

texts:
I need to add a range of numbers to a list based on specific conditions. The method recieves a String, and based on value of the String, specific list of values should be added to the list.

Name variable has name of the selected product and numbers are serial number of products that are similar to the selected product.

I am wondering if there is any better approach to do it.

ArrayList numbers = new ArrayList<Integer>();
switch (name) {
 case "A":
    for (int i = 1; i <= 100; i++) {
        if ((i >= 46 && i <= 50) || (i >= 60 && i <= 73) || i == 91
                || i == 96 || i == 97) {
            continue;
        } else {
            numbers.add(i);
        }
    }
    break;
 case "B":
    for (int i = 1; i <= 100; i++) {
        if ((i >= 50 && i <= 55) || (i >= 65 && i <= 88) || i == 90
                || i == 98 || i == 99) {
            continue;
        } else {
            numbers.add(i);
        }
    }
    break;

}

  return numbers;


texts:
Implement a function meetingPlanner that given the availability, slotsA and slotsB, of two people and a meeting duration dur, returns the earliest time slot that works for both of them and is of duration dur. If there is no common time slot that satisfies the duration requirement, return null.

Examples:

input:  slotsA = [[10, 50], [60, 120], [140, 210]]
        slotsB = [[0, 15], [60, 70]]
        dur = 8
output: [60, 68]

input:  slotsA = [[10, 50], [60, 120], [140, 210]]
        slotsB = [[0, 15], [60, 70]]
        dur = 12
output: null # since there is no common slot whose duration is 12

This is my approach to the solution:

    import java.io.*;
    import java.util.*;
    import java.lang.*;

    class Solution {

      static int[] meetingPlanner(int[][] slotsA, int[][] slotsB, int dur) {
        // your code goes here
        int i = 0,j = 0;
        int maxStartDur,minEndDur, overlap;
        int [] optTime = new int[2];
        int [] nullArr = new int[0];
        for( i = 0; i < slotsA.length; i++)
        {
          for(j = 0; j < slotsB.length; j++ )
          {
            //Calculate the overlap between corresponding times
              maxStartDur = Math.max(slotsA[i][0],slotsB[j][0]);
              minEndDur = Math.min(slotsA[i][1], slotsB[j][1]);
              overlap = minEndDur - maxStartDur;

              if( overlap >= dur )
              {
                optTime[0] = maxStartDur;
                optTime[1] = maxStartDur + dur;
                return optTime;
              }
             /* minDur = Math.min((slotsA[i][1] - slotsA[i][0]),(slotsB[j][1] - slotsB[j][0]));
              if( minDur >= dur)
              {
                optTime[0] = slotsA[i][0];
                optTime[1] = slotsA[i][0] + dur;
              }
              else
                break;
            }
            */
          }

      }

        return nullArr;
      }
// Time complexity:  O(slotsA.length*slotsB.length)
//Space complexity: O(array of size [2])
      public static void main(String[] args) {

      }

    }

These are some of the questions regarding this code:

Can I further optimize this code to have an improved time and space complexity?
Is there a smarter approach to solve this question?
Are there better data structures available which I can use to solve this question more appropriately?

Reference


texts: Suggestions for improvement on Project Euler #7

texts:
Here is a solution for Project Euler Problem #7.

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13. What is the 10,001st prime number?

I've used the pseudo code from the Wikipedia page for the Sieve of Eratosthenes.

  Input: an integer n > 1

  Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.

for i = 2, 3, 4, ..., not exceeding √n:
     if A[i] is true:
         for j = i^2, i^2+i, i^2+2i, ..., not exceeding n :
             A[j] := false

Any suggestions would be much appreciated.

import java.util.*;

public class FindPrimesHashMap {
    public static void getPrime(int x) {
        int n = (x * ((int)Math.sqrt(x) / 10)) + x;
        int nSqrt = (int)Math.floor(Math.sqrt(n));
        int j = 0;
        int k = 0;
        Map<Integer, Boolean> primeMap = new HashMap<Integer, Boolean>();
        Set<Map.Entry<Integer, Boolean>> primes = primeMap.entrySet();
        ArrayList<Integer> primeArray = new ArrayList<Integer>();

        for (int a = 2; a < n; a++) {
            primeMap.put(a, true);
        }

        for (int i = 2; i <= nSqrt; i++) {
            if (primeMap.get(i)) {
                while (true) {
                    j = (i * i) + (k * i);
                    k++;

                    if (j > n) {
                        break;
                    }
                    primeMap.put(j, false);
                }
                j = 0;
                k = 0;
             }
        }

        for (Map.Entry<Integer, Boolean> entry : primes) {
            if (entry.getValue()) {
                primeArray.add(entry.getKey());
            }
        }
        Collections.sort(primeArray);
        System.out.println(primeArray.get(x - 1));
}


texts: Vehicle, Components and Car relationship

texts:
I am writing Vehicle - Components - Car relationship.
I have to separate cars that use the diesel, petrol and electric engines because each of them produce their own results (but methods of each are the same).

For example, if car is using diesel engine (which obviously should have only diesel exhaust system) then it produces higher pollution than electric car's engine.

It is very important that after I could set the engine, for example my Car has diesel engine and now I want to use electric instead because of lower pollution.

Right now, I have an abstract class Vehicle. Vehicle has-a components such as Engine and Tires. Car is-a (extends) Vehicle.

Vehicle.class

public abstract class Vehicle {
    private Engine engine;
    private Tire tires;

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public Tire getTires() {
        return tires;
    }

    public void setTires(Tire tires) {
        this.tires = tires;
    }

    public MotorVehicle() {
        super();
    }

    public Vehicle(Engine engine, Tire tires) {
        this.engine = engine;
        this.tires = tires;
    }
}

Car.class

public class Car extends Vehicle {
    private Engine engine;
    private Tire tires;
    private ExhaustSystem system;

    public Car() {
        super();
    }

    public Car(Engine engine, Tire tires) {
        super(engine, tires);
    }
}

Where Engine.class is an interface

public interface Engine {
    String getType();
    ExhaustSystem getExhaustSystem();
}

and, for example, DieselEngine.class implements it

public class DieselEngine implements Engine {
    private String type;
    private DieselExhaustSystem system;

    public DieselEngine(String type, DieselExhaustSystem system) {
        this.type = type;
        this.system = system;
    }

    @Override
    public String getType() {
        return type;
    }
    @Override
    public ExhaustSystem getExhaustSystem() {
        return system;
    }
}

Similar to Engine - ExhaustSystem.class is an interface

public interface ExhaustSystem {
    double getGasExits();
}

and DieselExhaustSystem.class implements it.

public class DieselExhaustSystem implements ExhaustSystem {

    /**
     *
     * @return CO2 emission units.
     */
    @Override
    public double getGasExits() {
        return 3;
    }
}

I also will have Truck which will extend Vehicle.

After I wrote this, I have some doubts about its correctness.

The main question is:

Is relationship and classes logic correct?

If not or partially not, then:

What can be done better?
Maybe I do not understand polymorphism?
Maybe I do not understand has-a / is-a relationships?
Maybe I should use another desing pattern for my task (for example, bridge pattern)?
Perhaps it is better to make Engine abstract and other engines extend it?


texts:
I'm working on an application that turns a raw camera image into a binary (pure black/white) image and I need this to happen as fast as possible for swift further processing. This is what my code currently looks like:

public static boolean[][] createBinaryImage( Bitmap bm )
{
    int[] pixels = new int[bm.getWidth()*bm.getHeight()];
    bm.getPixels( pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight() );
    int w = bm.getWidth();

    // Calculate overall lightness of image
    long gLightness = 0;
    int lLightness;
    int c;
    for ( int x = 0; x < bm.getWidth(); x++ )
    {
        for ( int y = 0; y < bm.getHeight(); y++ )
        {
            c = pixels[x+y*w];
            lLightness = ((c&0x00FF0000 )>>16) + ((c & 0x0000FF00 )>>8) + (c&0x000000FF);
            pixels[x+y*w] = lLightness;
            gLightness += lLightness;
        }
    }
    gLightness /= bm.getWidth() * bm.getHeight();
    gLightness = gLightness * 5 / 6;

    // Extract features
    boolean[][] binaryImage = new boolean[bm.getWidth()][bm.getHeight()];

    for ( int x = 0; x < bm.getWidth(); x++ )
        for ( int y = 0; y < bm.getHeight(); y++ )
            binaryImage[x][y] = pixels[x+y*w] <= gLightness;

    return binaryImage;
}

As you can see, it uses a global threshold to tell apart the black and white pixels. I recently switched from bm.getPixel to bm.getPixels and this yielded a speed improvement of ~33%. Now my question is if there is anything else I can do to speed things up?

It currently takes <0.5 seconds to process 558x256 image and this is reasonable for my application, but I wonder if there's room for any other simple optimizations.


texts:
This is basically the beginnings of a battleship game. There is only 1 ship which takes up 3 of six locations on a 1 x 6 grid. The locations are created by finding a random location on the grid and then taking the next two points as the other 2 locations.

I basically just make sure the the guess is between 1 and 6, make sure the number has not been guessed before by comparing it to guessarr (an array that contains all the valid guesses), then compare the guess to the random locations to determine if it's a hit or miss. After guessing all 3 random locations, the user wins.

How would I go about making this code object-oriented?

var guess;
var guesses = 0;
var hits = 0;
var isSunk = false;
var  guessCheck=-1;
var guessarr = [];
var valid = true;
var randomeloc = Math.floor(Math.random () * 5);
var location1 = randomeloc
var location2 = randomeloc + 1;
var location3 = randomeloc +2;

while (isSunk == false) {
    guess = prompt("Enter a guess between 1 and 6");
    if (guess < 0 || guess > 6) {
        alert("Enter a valid number between 0 and 6");
    }else if(guess > 0 || guess < 6) {
        guessCheck= guessarr.indexOf(guess);
        if (guessCheck >= 0) {
        valid = false;
        alert("You've already entered this number. Try again");
        } else if (valid = true){
            guesses = guesses +1;
            if (guess == location1 ||
                guess == location2 ||
                guess == location3) {
                hits = hits + 1;
                alert ("You got a hit!");
                guessarr.push(guess);
            }
            else {alert("miss");
            }
            if (hits == 3) {
            isSunk= true;
            alert("you won!");
            }
        }
    }
}


texts:
I've got the following query.

SELECT xcli.ID_X_Table, cli.ID, cli.Presentation, COALESCE(cli.MobilePhone, cli.BusinessPhone, cli.HomePhone), EmailAddress, cli.Descr
FROM B_Client cli
INNER JOIN X_Table xcli ON xcli.TableName = 'B_Client' AND ISNULL(cli.Flg_Deleted, 0) = 0
WHERE cli.EmailAddress LIKE '%'+@SearchText+'%'
UNION
SELECT xcli.ID_X_Table
      , cli.ID
      , cli.Presentation
      , ISNULL(cli.MobilePhone, ISNULL(cli.BusinessPhone, cli.HomePhone))
      , cli.EmailAddress
      , cli.Descr
FROM B_Client cli
INNER JOIN X_Table xcli ON xcli.TableName = 'B_Client'
                        AND ISNULL(cli.Flg_Deleted, 0) = 0
WHERE RTRIM(ISNULL(cli.ClientName, '')) + ' ' + LTRIM(ISNULL(cli.FirstMiddleName, '')) LIKE '%'+@SearchText+'%'
    OR RTRIM(ISNULL(cli.FirstMiddleName, '')) + ' ' + LTRIM(ISNULL(cli.ClientName, '')) LIKE '%'+@SearchText+'%'
    OR SUBSTRING(RTRIM(ISNULL(cli.FirstMiddleName, '')), 0, PATINDEX('% %', RTRIM(ISNULL(cli.FirstMiddleName, '')))) + ' ' + LTRIM(ISNULL(cli.ClientName, '')) LIKE '%'+@SearchText+'%'
UNION
SELECT xcli.ID_X_Table
       , cli.ID
       , cli.Presentation
       , dbo.Get_B_Car_RegNum(car.ID, GETDATE()) as RegNum
       , car.Presentation
       , cli.Descr
FROM B_Car car
INNER JOIN X_Table xcli on xcli.TableName = 'B_Client'
INNER JOIN B_Client cli on cli.ID = [dbo].[Get_B_Car_ID_B_Client](car.ID, GETDATE())
WHERE car.CarPotential = 0
    AND (car.Descr LIKE '%'+@SearchText
        OR (SELECT TOP 1 RegNum FROM B_Car_RegNum
            WHERE ID_B_Car = car.ID
                AND Dte_Start <= GETDATE() ORDER BY Dte_Start DESC) LIKE '%'+@SearchText+'%')

This query searches for user-provided text across multiple tables (it's a sort of primitive search engine).
The unions overlap because they are added programmatically if the input is appropriate. For example if the input contains letters it won't search for telephone numbers and so on.

The query is quite slow in production. It takes minutes to retrieve the query. The tables contain hundreds of thousands entries. I'm not sure if this query performs poorly due to its design, or because of the magnitude of data.

Tips and critique are welcome.


texts:
I have written a PDO wrapper and a class file like a model.  It's looking good so far, but I'm just confuseed on where I should put the try/catch block.  Would it be better to place it in the PDO wrapper (pdoDatabase.php), mobile.php (model) or test.php?

pdoDatabase.php

class pdoDatabase {

public $db;
private $sth;
private static $instance;
private $error;

private function __construct() {
    $dsn = "mysql:dbname=" . config::read("db.database") . ";host=localhost";
    $username = config::read("db.username");
    $password = config::read("db.password");
    $this->db = new PDO($dsn, $username, $password);
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

public static function getInstance() {
    if (!isset(self::$instance)) {
        self::$instance = new static();
    }
    return self::$instance;
}

public function fetchData($sql, $params = array(), $fetchMode = 'all') {
    // Should try...catch block be here?
    try {
        $this->sth = $this->db->prepare($sql);
        if (count($params) > 0)
            $this->setBind($params);

        $this->sth->execute();
        $fetch = ($fetchMode == 'single') ? "fetch" : "fetchAll";
        return $this->sth->$fetch();
    } catch (PDOException $e) {
        $this->error = array(
            'status' => 'error',
            'message' => $e->getMessage()
        );
        return false;
    }
}

public function setBind($params) {
    if (is_object($this->sth)) {
        foreach ($params as $key => $value) {
            $this->sth->bindValue(":$key", $value);
        }
    }
}

public function error() {
   return $this->error;
}
public function beginTransaction() { }
public function commit() { }
public function rollBack() { }

mobile.php

class Mobile {

    public $db;

    public function __construct() {
        $this->db = pdoDatabase::getInstance();
    }

    public function findPhoneAffiliate($phoneId = null, $affiliateId = null, $affiliatePhoneId = null) {
     // or should try...catch block be here?
        $bindAr = array();
        if ($phoneId !== null)
            $whereAr[] = "phone_id = " . $phoneId;

        if ($affiliateId !== null)
            $whereAr[] = 'affiliate_id = ' . $affiliateId;

        if ($affiliatePhoneId !== null) {
            $whereAr[] = 'affiliate_phone_id = :affiliate_phone_id';
            $bindAr['affiliate_phone_id'] = $affiliatePhoneId;
        }

        $where = count($whereAr) > 0 ? 'WHERE ' . implode(' AND ', $whereAr) : '';

        $sql = "SELECT * FROM phone_affiliate $where";
        return $this->db->fetchData($sql, $bindAr, 'single');
    }
}

test.php

$mobileResult = $mobile->findPhoneAffiliate(null, 'f', "ASEF33");
if ($mobileResult) {
    // Data Found!
    print_r($mobileResult);
} else {
    if ($mobile->db->error()) {
        print_r($mobile->db->error());
        exit();
    }
    if ($mobile->db->rowCount() == 0)
        echo "Data Not Found";
}

As you can see, it will need to check if there any error or no data found in the else statement. Is this how it should be done?  If now, what can be improved to reduce the code from the test.php sample?


texts: Parsing XML to get all elem.tag: elem.text pairs

texts:
I am parsing ICD-10 codes and have achieved a result that satisfies my base case, but I'm worried about how fragile my method is:

import xml.etree.ElementTree as ET

# A sample of the larger XML file I'm parsing
data = '''<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
  <name>A00.0</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
  <inclusionTerm>
    <note>Classical cholera</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.1</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
  <inclusionTerm>
    <note>Cholera eltor</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.9</name>
  <desc>Cholera, unspecified</desc>
</diag>
</diag>'''

# Create the tree
tree = ET.ElementTree(ET.fromstring(data))

# the `iter` method returns all tags in a given tree
# I'm just grouping the tags and texts here
def get_all_elements(tree):
    return [(elem.tag, elem.text) for elem in tree.iter()]

# This will return the desired elements from my tree
def parse_elements(tree):

    # First, get all of the elements in the tree
    elements = get_all_elements(tree)

    to_return = {}

    # This is what I think is too fragile. I'm basically looking
    # ahead for each element to see whether the next two elements
    # match the diag -> name -> desc sequence. But this indexing seems
    # to be too fragile at scale.
    for idx, elem in enumerate(elements):
        if 'diag' in elem and 'name' in elements[idx+1] and 'desc' in elements[idx+2]:
            name = elements[idx+1]
            desc = elements[idx+2]
            to_return[name[1]] = desc[1]
    return to_return

res = parse_elements(tree)

Let's see what's in res:

for k,v in res.items():
    print("name (code): ", k, "\n  desc: ", v)

name (code):  A00.9
  desc:  Cholera, unspecified
name (code):  A00.0
  desc:  Cholera due to Vibrio cholerae 01, biovar cholerae
name (code):  A00
  desc:  Cholera
name (code):  A00.1
  desc:  Cholera due to Vibrio cholerae 01, biovar eltor

So, I achieve my desired output, but I keep thinking there much be a better way to parse this XML. Unfortunately there's no <diag><subdiag></subdiag></diag>-type of hierarchy. Even subdiagnoses are labeled with the <diag> tag. I suppose the above is my attempt at recursion -- although I have found true recursion tough with the current tag-naming. At the end of the day, I just need the name: desc pairs.

Edit:

There's also this approach:

names = [x.text for x in ET.fromstring(data).findall('.//name')]
descs = [x.text for x in ET.fromstring(data).findall('.//desc')]

res = zip(names, descs)

But I don't think this approach scales well, as the number of elements in names and descs differed by about 1000 when I tested this on the larger XML file. There were mismatches between codes and descriptions when I validated on actual codes.


texts: Recode algorithm for merged cells on HTML table

texts:
Is there any way to improve this algorithm maybe making it so faster avoid using foreach? Maybe with a recursion?
The output of my algorithm is a table with 3 merged columns, each row will have its own rowspan.

$matrix=array("person1"=>array("wifes"=>array("diana"=>array("born"=>1982,"last_name"=>"chapelle"),"carla"=>array("born"=>1983,"last_name"=>"michael"),"serena"=>array("born"=>1984,"last_name"=>"mickelson")
            ,"king"=>array("born"=>1980,"last_name"=>"jordan")))
    ,"person2"=>array("husbands"=>array("charles"=>array("born"=>1983,"last_name"=>"rambo")
    ,"minglen"=>array("born"=>1973,"last_name"=>"rian"),"serrano"=>array("born"=>1914,"last_name"=>"kingside"))));

$htmlx="
";
    $htmlx.="
";
    $htmlx.="object	type	names	detail_names	values_detail	";
    $html_p=NULL; $p=0;
    foreach ($matrix as $pkey => $pvalue) {
        $t=0;   $html_t=NULL;
        foreach ($pvalue as $tkey => $tvalue) {
            $n=0;   $html_n=NULL;   $rs_general=0;
            foreach ($tvalue as $nkey => $nvalue) {
                $d=0;   $html_d=NULL;   $rs_general+=count($nvalue);
                foreach ($nvalue as $dkey => $dvalue) {

                    $d++;
                    if($d==1){
                        $html_d="".$dkey."	".$dvalue."	";
                    }else{
                        $html_d.="
".$dkey."	".$dvalue."
";
                    }
                }
                $n++;
                if($n==1){
                    $html_n.="".$nkey."	".$html_d;
                }else{
                    $html_n.="
".$nkey."	".$html_d."
";
                }
            }
            $t++;
            if($t==1){
                $html_t="".$tkey."	".$html_n;
            }else{
                $html_t.="
".$tkey."	".$html_n."
";
            }
        }
        $p++;
        if($p==1){
            $html_p.="".$pkey."	".$html_t;
        }else{
            $html_p.="
".$pkey."	".$html_t."
";
        }

    }
    $htmlx.="
".$html_p;
$htmlx.="
";
echo $htmlx;

I have been thinking about recursion function but I don’t get the solution yet, so any help will be welcome.


texts: Dynamically change attribute value with split() (JavaScript)

texts:
What I want to do

Make my code cleaner.

What my code does

Thanks to Stack overflow, I finally wrote a code which creates option tags dynamically (OptionTime). The value of data-range attribute for Year was static. I wanted to set the years range dynamically, and I did it (See between //start and //End). However, I feel my code is lengthy. Can anyone make my code better, please?

Here is my code

// Start
/* Fetch DOM */
const selectYear = document.querySelector('select[name="Year"]');

/* Set years */
const now = new Date();
const year = now.getFullYear();
const startYear = year - 50;
const endYear = year - 18;

/* Change Year's data-range */
function overwriteYears() {
  let dataRange = selectYear.dataset.range;
  let [start, end, unit] = dataRange.split(' ');
  start = startYear;
  end = endYear;
  selectYear.setAttribute('data-range', `${start} ${end} ${unit}`);
}
overwriteYears();
// End

/* Create <option> tags */
class OptionTime extends HTMLSelectElement {
  constructor() {
    super();
  }
  connectedCallback() {
    let [start, end, unit] = this.dataset.range.split(' ');

    for (let i = start; i <= end; i++) {
      this.add(new Option(`${i}${unit}`, `${i}${unit}`));
    }
  }
};
customElements.define('option-time', OptionTime, {
  extends: 'select'
});
<select is="option-time" name="Year" data-range="%startYear% %endYear% 年">
  <option value="" disabled selected>Year</option>
</select>
<select is="option-time" name="Month" data-range="1 12 月">
  <option value="" disabled selected>Month</option>
</select>
<select is="option-time" name="Day" data-range="1 31 日">
  <option value="" disabled selected>Day</option>
</select>


texts: Fetching a number of data tables from a stored procedure

texts:
Within a method, this code is calling a SPROC that is doing a 'select *' from 9 different views. This method then goes on to access the returned DataTableCollection array by the index specified here (0-9). If the order of the stored procedure select statements ever changed, this would also need changing round here.

This seriously looks dodgy to me. Does anyone have any opinions?

if (_dataSet != null)
            {
                _applicationContext = new ApplicationContext();

                //build the object for System Mode.
                _applicationContext.SystemMode = BuildSystemMode(CheckDataTableScope(_dataSet.Tables,0));

                //build the object for data parameters.
                _dataParameters = BuildDataParameters(CheckDataTableScope(_dataSet.Tables, 1));

                //build the object for data columns.
                _dataColumns = BuildDataColumns(CheckDataTableScope(_dataSet.Tables, 2));

                //build the object for data command.
                _applicationContext.DataCommand = _dataCommand = BuildDataCommand(CheckDataTableScope(_dataSet.Tables, 3));

                //build the object for screens.
                _screenConfig = BuildScreen(CheckDataTableScope(_dataSet.Tables, 4));

                //build the object for user menus.
                _applicationContext.UserMenus = BuildUserMenu(CheckDataTableScope(_dataSet.Tables, 5));

                //build the object for application menus.
                _applicationContext.ApplicationMenus = BuildApplicationMenus(CheckDataTableScope(_dataSet.Tables, 6));

                //build the object for system messages.
                _applicationContext.SystemMessages = BuildSystemMessages(CheckDataTableScope(_dataSet.Tables, 7));

                //build the object for widget configuration.
                _applicationContext.WidgetConfigs = BuildWidgetConfig(CheckDataTableScope(_dataSet.Tables, 8));
            }


texts:
Algorithm which returns a number which is divisible by all the numbers from \$1\$ to \$n\$ without remainders.

public static void smallestMultiple(long l){
    int count = 1;
    boolean flag = true;
    while(true){
        flag = true;
        for(int i=1; i<=l; i++){
            if( count % i != 0){
                count++;
                flag = false;
                break;
            }
        }
        if(flag){
            break;
        }
    }
    System.out.println(count);
}

Any better approach is there?


texts:
I'm new to JavaScript, and decided to learn the language by running through as many of the Project Euler problems as I have time to do. I just finished the first one, and am looking for some feedback, specifically on language specific features I could use to do this faster, and faster performance overall (it seems to run a little slow) after some edits to fit the problem, it runs much faster, the document.write seemed to be really slowing the code down (probably from directly editing the page once every division of 3 or 5), and writing once value makes a huge difference.

Working fiddle here.

document.write = function (val) {
    document.body.insertAdjacentHTML("beforeend", val);
}

//If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

//Find the sum of all the multiples of 3 or 5 below 1000.

var ans = [];
var k = 0;

for (var i = 1; i < 1000; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
        ans[k] = i;
        k++;
    }
}

var sum = 0;

for (var i = 0; i < ans.length; i++) {
    sum += ans[i];
}

document.write(sum);

//If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

//Find the sum of all the multiples of 3 or 5 below 1000.

var ans = [];
var k = 0;

for (var i = 1; i < 1000; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
        ans[k] = i;
        k++;
    }
}

var sum = 0;

for (var i = 0; i < ans.length; i++) {
    sum += ans[i];
}

document.write(sum);


texts: Form that reveals more fields as each step has been completed

texts:
I'm new to JavaScript and jQuery and need input about how to optimize my script:

(document).ready(function() {

    var inputs_1 = $("form#myForm .case1 input, form#myForm .case1 select");
    var inputs_2 = $("form#myForm .case2 input, form#myForm .case2 select");
    var inputs_3 = $("form#myForm .case3 input");

    $("form#myForm .case2").addClass("disabled");
    $("form#myForm .case3").addClass("disabled");
    $("form#myForm .case2 input, form#myForm .case2 select").prop('disabled', true);
    $("form#myForm .case3 input").prop('disabled', true);

    var validateInputs = function validateInputs(inputs) {
      var validForm = true;
      inputs.each(function(index) {
        var input = $(this);
        if (!input.val()) {
            $("#subnewtide").prop('disabled', true);
            validForm = false;
        }
      });
      return validForm;
    }

    inputs_1.change(function() {
      if (validateInputs(inputs_1)) {
          $("form#myForm .case2").removeClass('disabled');
          $("form#myForm .case2 input, form#myForm .case2 select").prop('disabled', false);
      }
    });

    inputs_2.change(function() {
      if (validateInputs(inputs_2)) {
          $("form#myForm .case3").removeClass('disabled');
          $("form#myForm .case3 input").prop('disabled', false);
      }
    });

    inputs_3.change(function() {
      if (validateInputs(inputs_3)) {
          $("#subnewtide").prop('disabled', false);
      }
    });

});

It is a registration form. After a user has inserted all inputs from step1 the next step should be shown. so far so good. My solution works, but I guess it is not the best way to solve my issue.

How can I abstract this more to increase maintainability?

I need a way to use one XY.change(function) handler, not for everyone a single solution.


texts:
I have functions nested here in setTimeout

function startWorker (obj) {
  if (!code) {
    return setTimeout(2000, () => {
      startWorker(obj)
    });
  }

  console.log('worker started')
}

How do I correctly use startWorker as the callback without using more functions than needed.

What I'm trying to do:

I'm trying to run the same function with the same argument as the callback to a setTimeout inside without duplicating function calls.


texts: Implement Factory pattern with multiple parameters and each parameters are interface

texts:
I am a little bit confused on Factory Method with multiple parameters in which all parameters can change from GUI by user as seen below picture.

For each combobox item I have an interface and concrete implementations.
I have a SignalProcessor class which gets parameters as this 3 interfaces as below:
public interface ISignalProcessor
{
    double[] Process(double[] data);
}

public class SignalProcessor : ISignalProcessor
{
    private IFft _fft;

    private IWindowing _windowing;

    private IInverseSpectrum _inverseSpectrum;

    private IDecimation _decimation;

    public SignalProcessor(IWindowing windowing, IFft fft,  IInverseSpectrum inverseSpectrum, IDecimation decimation)
    {
        _windowing = windowing;
        _fft = fft;
        _inverseSpectrum = inverseSpectrum;
        _decimation = decimation;
    }

    public double[] Process(double[] data)
    {
        var windowingResult = _windowing.Calculate(data);
        var fftResult = _fft.Calculate(windowingResult);
        var inverseSpectrumResult = _inverseSpectrum.Calculate(fftResult);
        return _decimation.Calculate(inverseSpectrumResult);
    }
}

I decided to produce and use concrete classes according to the selected combobox values so the following factory class created.
  public static class FactorySP
{
    public static ISignalProcessor Create(string windowingType, int fftSize, bool isInverse, string decimationType)
    {
        return new SignalProcessor(CreateWindowing(windowingType), CreateFft(fftSize), CreateInverseSpectrum(isInverse), CreateDecimation(decimationType));
    }

    private static IWindowing CreateWindowing(string windowingType)
    {
        switch (windowingType)
        {
            case "Triangular":
                return new Triangular();
            case "Rectangular":
                return new Rectangular();
            case "Hanning":
                return new Hanning();
        }
    }

    private static IFft CreateFft(int fftSize)
    {
        switch (fftSize)
        {
            case 128:
                return new Fft128();
            case 256:
                return new Fft256();
            case 512:
                return new Fft512();
            default:
                return new FftNull();
        }
    }
    private static IInverseSpectrum CreateInverseSpectrum(bool isInverse)
    {
        if (isInverse)
            return new InverseSpectrumTrue();

        return new InverseSpectrumFalse();
    }

    private static IDecimation CreateDecimation(string decimationType)
    {
        if (decimationType == "RealTimeDecimation")
            return new RealTimeDecimation();

        return new SweepDecimation();
    }
}

Then used as follows:
_signalProcessor = FactorySP.Create(WindowingType, FftSize, InverseSpectrum, DecimationType);
result = _signalProcessor.Process(Enumerable.Range(0, 100).Select(a => (double)a).ToArray());

Is there a better way to get what I want than that? I feel there is something missing in the method I use :) I know Factory method is not like that but otherwise I have to create all combinations and permutations of overload of factory classes. Should I use the builder pattern to create the SignalProcessor object?


texts: Using VBA Copying from one ,master sheet to other workbooks based on the file names provided in master book

texts:
Pretty new to this hence taking it as challenge. I have a master sheet in which Column A have all the file names( complete file name with .xls extensions). I need to copy data of column b in this sheet and paste it in all the files in a particular folder in a particular tab. There can be multiple items for one name. Sample Data

Australia.xlsx  XX
Austria.xlsx    YY
Austria.xlsx    DD
Belgium.xlsx    OO
Brazil.xlsx     MM
Brazil.xlsx     NN

Here is the code i tried to write:

Sub Macro1()
    Application.DisplayAlerts = False
    Dim Country As String
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer

    k = 2
    For i = 2 To 50

        Windows("try 1 split to combines").Activate
        Country = Worksheets("Sheet3").Cells(i, 1).Value
        Workbooks("try 1 split to combines").Sheets("Sheet3").Range(Cells(i, i + 1)).Copy

        Workbooks.Open Filename:= _
        "C:\Users\abhayl.INDIA\Desktop\For Primary Team\For Primary Team\" & Country & " "
        'Workbooks("Name").Activate
        ActiveWorkbook.Sheets("Specific Questions").Activate
        ActiveWorkbook.Sheets("Specific Questions").Cells(k, 2).xlPasteValues
        finalrow2 = 42 + k
        k = finalrow2 + 1
        Workbooks(Country).Sheets("Specific Questions").Activate
        Workbooks(Country).Close SaveChanges:=False
    Next i
End Sub

This is pretty basic but need some improving, can anyone help me out to better rewrite this code?


texts: Is my first MVC architecture set up to standards?

texts:
I just started learning about the MVC architecture. And I started to create my own MVC framework to how I like it the most.

Here I've got the index.php, indexcontroller.php and view.php. I'm not too sure if what I am doing is right, or with best practices. So I would like to know if there is anything I missed so far, or what I could improve?

Index.php (updated)

//report all php errors
error_reporting(E_ALL);

//define site root path
define('ABSPATH', dirname(__FILE__));

//include functions
foreach(glob(ABSPATH . '/functions/*.php') as $filename) {
    require $filename;
}

//set config array
$config = parse_ini_file(ABSPATH . '/config.ini', true);
$config = json_decode(json_encode($config));

//auto load classes
spl_autoload_register('autoloadCore');
spl_autoload_register('autoloadController');
spl_autoload_register('autoloadModel');

//url to class router
Glue::stick((Array) $config->routes);

IndexController

class IndexController extends BaseController {
    private $_view;

    public function GET() {
        $this->index();
    }

    public function POST() {
        //don't handle post
    }

    public function __construct() {
        $this->_view = new View();
    }

    public function index() {
        $this->_view->welcome = 'Welcome!';
        $this->_view->render('index');
    }
}

View

class View {
    private $_vars = [];

    public function __set($index, $value) {
        $this->_vars[$index] = $value;
    }

    function render($fileView) {
        $path = ABSPATH . '/view/' . $fileView . '.php';
        if(!file_exists($path)) {
            throw new Exception('View not found: '. $path);
        }
        foreach($this->_vars as $key => $value) {
            $$key = $value;
        }
        include ($path);
    }
}


texts:
I find myself using subject blocks in my tests to setup example because it is succinct. However is this considered bad form and can it have undesired  consequences?

require 'spec_helper'

describe "stations/index" do

  before(:each) do
    stub_user_for_view_test
    assign(:stations, [
      stub_model(Station),
      stub_model(Station)
    ])

  end

  context "when not an admin" do
    subject {
      render
      rendered
    }

    it { should match /[s|S]tations/ }
    it { should have_selector('.station', :minimum => 2) }
    it { should_not have_link 'Edit' }
    it { should_not have_link 'Delete' }
  end

  context "when an admin" do

    subject {
      @ability.can :manage, Station
      render
      rendered
    }

    it { should have_link 'Edit' }
    it { should have_link 'Delete' }
  end

end


texts: Build embedded XML based on string containment

texts:
I have a list of strings that represent a path. These are unique, unsorted values that look like this:

li = ['1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/']

It can also be assumed that every path has a parent, e.g. 1/2/ has parent 1/.

The goal is to organise these items in a structured XML format, where the parent-relation is clear, i.e. where deeper elements are part of their parents, mimicking a directory tree. Desired output for the list above would be:

<root>
  <include path="1/">
    <include path="1/1/">
      <include path="1/1/3/"/>
    </include>
    <include path="1/2/">
      <include path="1/2/3/">
        <include path="1/2/3/4/"/>
      </include>
      <include path="1/2/4/"/>
    </include>
    <include path="1/23/">
      <include path="1/23/4/"/>
    </include>
  </include>
</root>

The following works (run it here), but I am not sure about efficiency. The actual list can be thousands of values long. I am also curious about memory management, because I am writing all XML nodes in-memory. The eventual goal is to print the final XML to a file.

from xml.etree import ElementTree as ET
import re

li = ['1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/']
li = sorted(li)
# In Python >= 3.6 dicts maintain order
# Sets don't? So use best of both worlds, dict: speed and order
di = {l: False for l in li}

root = ET.Element('root')

# First build the root nodes, remove them from dict
for p in list(di.keys()):
  if len(list(filter(None, p.split('/')))) == 1:
    del di[p]
    root.append(ET.Element('include', {'path': p}))

# Because dict (and so keys()) are ordered, we can assume that the nodes higher
# in the include tree are created before the more in-depth ones
for p in list(di.keys()):
  parent_path = re.sub('\d+\/$', '', p)
  try:
    parent = root.find(f'.//include[@path="{parent_path}"]')
    parent.append(ET.Element('include', {'path': p}))
  except Exception:
    print(f"parent not found for {p}")

print(ET.tostring(root))

This indeed returns the expected output (not pretty-printed). I am wondering if there is a better option and whether there are flaws in my approach. I'll only be using Python >= 3.6, which is quite important for the order of the dictionary.

Update

I noticed a bug with the sorting of the list/dict because actually the sorting was done on the strings which isn't what we want. (e.g. 1001/ would be before 134/) I rewrote part of the code, and use sets assuming these are faster.

from xml.etree import ElementTree as ET
import re

def get_xml(paths):
    root = ET.Element('paths')

    root_paths = set()
    for p in paths:
        # If only one item, use as first-level node - e.g. 1/
        if len(list(filter(None, p.split('/')))) == 1:
            root_paths.add(p)
            root.append(ET.Element('include', {'path': p}))

    # Remove root_paths from set
    paths = paths.difference(root_paths)

    # We can't use regular sort because that'll sort by string
    # Instead, sort by array of ints representation. E.g. `12/1001/14/` -> [12, 1001, 14]
    sorted_paths = sorted(paths, key=lambda item: [int(n) for n in list(filter(None, item.split('/')))])
    for p in sorted_paths:
        # Find parent_path by removing last part of string
        parent_path = re.sub('\d+\/$', '', p)
        try:
            parent = root.find(f'.//include[@path="{parent_path}"]')
            parent.append(ET.Element('include', {'path': p}))
        except AttributeError:
            print(f"parent {parent_path} not found for {p}", flush=True)

    return root

s = {'1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/'}

xml = get_xml(s)

print(ET.tostring(xml))


texts: Squaring an integer by repetitive addition

texts:
I've written two functions:

is_integer(), which tries to get a positive or a negative integer as input and returns the same value.
square(), which takes this returned value as parameter and returns square of the same.

The code in square() uses a for-loop that squares the integer by 'repetitive addition.' Finally, the script prints out the square of the integer returned by square().

Please review my code, point out errors of any kind and make suggestions.

# Squares an integer by repetitive addition
# Uses a for-loop
def square(integer):
    result = 0

    for element in range(1, abs(integer)+1):
        result += abs(integer)
    return 'Square of ' + str(integer) + ' is ' + str(result)

# Makes sure the input is an integer
def is_integer():
    number = raw_input('Enter an integer: ')

    if number.isdigit():
        number = int(number)
        return number
    elif number[0] == '-' and number[1:].isdigit():
        number = int(number)
        return number
    else:
        print '%r is not an integer' % number
        print 'To try again, press Enter key'
        print 'Otherwise, press Ctrl+C keys to abort'
        raw_input('>>> ')

        return is_integer()

# Square() takes as parameter the value returned by is_digit()
# Print the result returned by square()
print square(is_integer())


texts:
I'm trying to implement 8 puzzle problem using A Star algorithm. The goal state is: 0 1 2 3 4 5 6 7 8 and the heuristic used is Manhattan distance. Here's the code:

from copy import deepcopy

class puzzle:
    def __init__ (self, starting, parent):
        self.board = starting
        self.parent = parent
        self.f = 0
        self.g = 0
        self.h = 0

    def manhattan(self):
        inc = 0
        h = 0
        for i in range(3):
            for j in range(3):
                h += abs(inc-self.board[i][j])
            inc += 1
        return h

    def goal(self):
        inc = 0
        for i in range(3):
            for j in range(3):
                if self.board[i][j] != inc:
                    return False
                inc += 1
        return True

    def __eq__(self, other):
        return self.board == other.board

def move_function(curr):
    curr = curr.board
    for i in range(3):
        for j in range(3):
            if curr[i][j] == 0:
                x, y = i, j
                break
    q = []
    if x-1 >= 0:
        b = deepcopy(curr)
        b[x][y]=b[x-1][y]
        b[x-1][y]=0
        succ = puzzle(b, curr)
        q.append(succ)
    if x+1 < 3:
        b = deepcopy(curr)
        b[x][y]=b[x+1][y]
        b[x+1][y]=0
        succ = puzzle(b, curr)
        q.append(succ)
    if y-1 >= 0:
        b = deepcopy(curr)
        b[x][y]=b[x][y-1]
        b[x][y-1]=0
        succ = puzzle(b, curr)
        q.append(succ)
    if y+1 < 3:
        b = deepcopy(curr)
        b[x][y]=b[x][y+1]
        b[x][y+1]=0
        succ = puzzle(b, curr)
        q.append(succ)

    return q

def best_fvalue(openList):
    f = openList[0].f
    index = 0
    for i, item in enumerate(openList):
        if i == 0:
            continue
        if(item.f < f):
            f = item.f
            index  = i

    return openList[index], index

def AStar(start):
    openList = []
    closedList = []
    openList.append(start)

    while openList:
        current, index = best_fvalue(openList)
        if current.goal():
            return current
        openList.pop(index)
        closedList.append(current)

        X = move_function(current)
        for move in X:
            ok = False   #checking in closedList
            for i, item in enumerate(closedList):
                if item == move:
                    ok = True
                    break
            if not ok:              #not in closed list
                newG = current.g + 1
                present = False

                #openList includes move
                for j, item in enumerate(openList):
                    if item == move:
                        present = True
                        if newG < openList[j].g:
                            openList[j].g = newG
                            openList[j].f = openList[j].g + openList[j].h
                            openList[j].parent = current
                if not present:
                    move.g = newG
                    move.h = move.manhattan()
                    move.f = move.g + move.h
                    move.parent = current
                    openList.append(move)

    return None

#start = puzzle([[2,3,6],[0,1,8],[4,5,7]], None)
start = puzzle([[5,2,8],[4,1,7],[0,3,6]], None)
# start = puzzle([[0,1,2],[3,4,5],[6,7,8]], None)
#start = puzzle([[1,2,0],[3,4,5],[6,7,8]], None)
result = AStar(start)
noofMoves = 0

if(not result):
    print ("No solution")
else:
    print(result.board)
    t=result.parent
    while t:
        noofMoves += 1
        print(t.board)
        t=t.parent
print ("Length: " + str(noofMoves))

For the given test case it finds a solution but it's very slow and I'm doutbful about the implementation of the heuristic function. Please suggest on how it can be improved. Thanks


texts: A function that returns all letters in the Alphabet except the ones in a pre-defined list

texts:
This function should return a string that is comprised from all the letters in the Alphabet except the letters in a pre-defined list in alphabetical order.

Assuming all letters in the pre-defined list are all lowercase;

I came up with two ways to do this and I would like to know which way is more efficient or more 'Pythonic'.
Thanks in advance.

The first way:

import string

def get_remaining_letters(list_of_characters):
    # casting the Alphabet to a list so that it becomes mutable

    list_of_all_letters = list(string.ascii_lowercase)
# looping for each character in the pre-defined list
    for char in list_of_characters :
        if char in list_of_all_letters: # to avoid possible errors caused by the .remove in case of a duplicate charcter in the pre-defined list
            list_of_all_letters.remove(char)
    return ''.join(list_of_all_letters) # returns a string

# ----------------------------------------------------------- #

pre_defined_list = ['a', 'b', 'b']

test = get_remaining_letters(pre_defined_list)
print(test)

output :

>>> cdefghijklmnopqrstuvwxyz

The second way:

import string

def get_remaining_letters(list_of_characters):

    if list_of_characters == []:
        return string.ascii_lowercase
    else:
        remaining_letters = ''
        for char in string.ascii_lowercase:
            if char not in list_of_characters:
                remaining_letters += char
        return remaining_letters

pre_defined_list = ['a', 'b', 'b']

test = get_remaining_letters(pre_defined_list)
print(test)

output :

>>> cdefghijklmnopqrstuvwxyz


texts: Reimplementing Python's enum.auto() for compatibility

texts:
In Python >= 3.6 there is an enum.auto() function.

The auto() function can be used like this:

import enum
from enum import auto

class Fruits(enum.Enum):
  APPLE = auto()
  ORANGE = auto()
  BANANA = auto()

I want to use it, but i cannot be sure if i am on Python >= 3.6 so I implemented it like this:

import enum

try:
  from enum import auto
except ImportError:
  __my_enum_auto_id = 0
  def auto() -> int:
    global __my_enum_auto_id
    i = __my_enum_auto_id
    __my_enum_auto_id += 1
    return i

class Fruits(enum.Enum):
  APPLE = auto()
  ORANGE = auto()
  BANANA = auto()

It works afaik, but it seems ugly to me. Any suggestions on how to improove it/make it better? or is it ok?

Is there some side effect I may have overlooked?


texts:
I tried to implement round robin in java please check and help me to
improve it Thanks:

package trial.java;

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

public class Roundrobin1 {
//common interval for all process.
static int commonInt=3;
//to store a list of queued process
Map<String, Integer> waitingMAp=new LinkedHashMap<>();
List<Integer>waitingTimeList=new ArrayList<>();
//to Store elapsed time.
int timepassed=0;

public  void mainL(){
    //input process name and time in order.
    waitingMAp.put("p0", 3);
    waitingMAp.put("p1", 3);
    waitingMAp.put("p2", 3);
    waitingMAp.put("p3", 9);
    //first time getting the list of process.
    List<String>process=new ArrayList<>();
    //it will call recursively till no process is waiting.
    while(!waitingMAp.isEmpty()){
        process.addAll(this.getRoundRobin(waitingMAp));
    }
    System.out.print(process);
    System.out.println();
    System.out.print(waitingTimeList);
}

    public List<String> getRoundRobin(Map<String, Integer>
    processMap){
    Map<String, Integer> Local=new LinkedHashMap<>();
    Local.putAll(processMap);
    waitingMAp.clear();
    List <String>curr=new ArrayList<>();
    for(Map.Entry<String, Integer> entry :Local.entrySet()){
        curr.add(entry.getKey());

   waitingTimeList.add(entry.getValue()>3?timepassed=timepassed+3:     (timepassed=timepassed+entry.getValue()));

        if(entry.getValue()>commonInt){
            waitingMAp.put(entry.getKey(),entry.getValue()-commonInt);
        }
        }

    return curr;

    }
    public static void main(String[] a){
    new Roundrobin1().mainL();

    }

}

it will return below result:
first row is order and second row is time elapsed.
[p0, p1, p2, p3, p3, p3]
[3, 6, 9, 12, 15, 18]

I would like to add couple of questions here

Do I need to take priorities of  the process as well in the input.If yes how it going to solve starvation problem.
How to scale up this algorithm for multiprocessor or multi-core systems


texts:
I made a sidebar that has a slide-out feature. When you click on it, it shows more items. I made it with JS and HTML but I think the code can be done more efficiently. How can I clean the code up?

$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if($(this).data(data)) {
        let item = $('.slide-out-' + $(this).data(data));
        if(item.hasClass('slideout-active')) {
            item.hide("slide", { direction: "left" }, 250);
            item.removeClass('slideout-active');
            $('.slide-out-overlay').fadeOut()
        } else {
            item.show("slide", { direction: "left" }, 250);
            item.addClass('slideout-active');
            $('.slide-out-overlay').fadeIn()
        }
    }
});

$('.slide-out-overlay').on('click', function () {
    let items = ['content', 'system', 'account', 'other'];
    let item = '.slide-out-';
    for (i = 0; i < items.length; i++) {
        if($(item + items[i]).hasClass('slideout-active')) {
            $(item + items[i]).hide("slide", { direction: "left"}, 250);
            $(item + items[i]).removeClass('slideout-active');
            $('.slide-out-overlay').fadeOut();
        }
    }
});

{{ __('Information') }}

{{ __('Dashboard') }}

{{ __('System') }}

Content

System

Account

Other

{{ __('Content') }}

{{ __('Pages') }}

{{ __('Blocks') }}

{{ __('Layouts') }}


texts:
You guess heads or tails by clicking one of the buttons on easyGUI.  If it's right, you will get a "good job" message.  If it's wrong, you will get a "wrong" message! After that, there is an option to play again.

Please give me some feedback on how I can make my code better, if there is room for improvement.

import random
import time
import easygui
import sys
while True:
    rand = random.choice(["Heads", "Tails"])
    firstguess = easygui.buttonbox("Pick one", choices= ["Heads", "Tails"])
    if firstguess == rand:
        easygui.msgbox("Wow you win!")
    else:
    easygui.msgbox("Sorry you guessed wrong!")
    time.sleep(2)
    answer = easygui.buttonbox("Play again?", choices=["Yes","No"])
    if answer == "Yes":
        pass
    else:
        break

easygui.msgbox("Ok, see you later!")
sys.exit(0)


texts: Getting and posting data use PHP OOP and MySQLi

texts:
I am not very experienced in PHP OOP. Moreover, when MySQLi comes with PHP OOP, it makes me more confused about using it in the most efficient way.

Connection class:

<?php
//connectionclass.php
class connection{
public $conn;
public $warn;
public $err;

function __construct(){
  $this->connect();
}

private function connect(){
  $this->conn = @ new mysqli('localhost', 'sever_user', 'user_password');
    if ($this->conn->connect_error) {
      $this->conn = FALSE;
      $this->warn = '<br />Failed to connect database! Please try again later';
     }
}

public function get_data($qry){
  $result = $this->conn->query($qry);
  if($result->num_rows>=1){
    return $result;
  }else{
    $this->err = $this->conn->error;
    return FALSE;
  }
  $result->free();
}

public function post_data($qry){
  $this->conn->query($qry);
  if($this->conn->affected_rows>=1){
    return TRUE;
  }else{
    $this->err = $this->conn->error;
    return FALSE;
  }
}
}
?>

Structure of a PHP page which uses a MySQL database to store and get data:

<?php
//login.php
include('/include/connectionclass.php');
$db = new connection();

$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
  if($data){
    while($row=$data->fetch_assoc()){
      echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
    }
  }
?>

My login.php uses a connection class to get data about users. All the things are running well, but one thing confused me. In connectionclass.php, $this->conn is itself an object as it calls new mysqli, so this is an object inside another object $db. Moreover, When I am using $data = $db->get_data($query);, a result set is created inside a $db object by method get_data, then this result set is copied into a variable $data inside the login.php page.

Actually, two instances of the same result sets/data sets are creating here, one inside the db object and one inside the login page.

Is this the right way to use MySQLi and PHP to get a dataset from a MySQL database? Will it use more memory and server resources when the dataset is larger (when have to get large amount of data for many users)?

If it is not right way, please explain your points and provide another solution which can be used efficiently for PHP OOP and MySQLi.


texts: Avoiding the 'possible loss of data' compiler warning

texts:
I'm writing a file I/O DLL in C++ which is going to be used from VB6. The interface is already fixed, and uses INT64/Currency as the general integer data type.

Now I have this function:

extern "C" LPWIN32_FIND_DATAW ZFILEIO_API GetFileInfoByIndex(INT64 index) {
    return total_size >= 0
        && index <= file_vec->size()
        && index >= 0
              ? &file_vec->at(index)
              : NULL;
}

where file_vec is of type std::vector<WIN32_FIND_DATAW>. Its at member function takes a size_t argument, which is in my case an unsigned 32-bit integer. Therefore, MSVC++2010 warns me of possible data loss. I think nothing can happen in my code, but please correct me if I'm wrong. Also, do you know a method to avoid the warning (without shutting it off for other places in my code)?

And then there's another question; I would like to return the WIN32_FIND_DATAW struct by value, not as a pointer, but that's not possible because then I can't return NULL for illegal requests. Can I return such a pointer to my internal data to a VB6 application?


texts:
This is my take on the guess the number game. The user has three attempts to guess the number chosen at random. The number is between 0 and 9, including. It tells the user to guess higher or lower and reveals the number if the game is lost.
Input that is not a number between 0 and 9, including, is not accepted and the cursor will remain on the same line.
Green is for win and red is for retry.
I have tested the code and it works correctly. Please have a go.
guess_the_number.py
"""The user has three attempts to guess what number was chosen at random"""

__all__ = []

import random
import string

from colorama import deinit, init

right_answer = random.choice(string.digits)

as_int = int(right_answer)

MSG_ANS = 'The answer was ' + right_answer
MSG_ASK = 'Guess the number (0-9) '
MSG_OK = '\033[92mCorrect!\033[0m'
MSG_TRY = '\033[91mTry again *\033[0m'

def ask(msg_wrong):
    """
    One attempt

    Non-digits are not accepted

    Digits accepted are removed from the pool
    and are not accepted in subsequent attempts
    """
    global pool

    cursor_up = '\033[A'

    cursor_up_ask = cursor_up + '                       '

    while True:
        answer = input(MSG_ASK)

        if answer and answer in pool:
            break

        answer_sz = len(answer)
        answer_sz = answer_sz * ' '

        line = cursor_up_ask + answer_sz + cursor_up

        print(line)

        print()
        print()

        print(line, end='\r')

    if answer == right_answer:
        print(MSG_OK)

        exit()

    if msg_wrong == MSG_TRY:
        i = int(answer)

        if i > as_int:
            hint = '>'
        else:
            hint = '<'

        msg_wrong = msg_wrong.replace('*', hint)

    print(msg_wrong)

    pool = pool.replace(answer, '')

if __name__ == '__main__':
    pool = string.digits

    init()

    ask(MSG_TRY)

    ask(MSG_TRY)

    ask(MSG_ANS)

    deinit()


texts:
I haven't a clue whether this works for every case, but it has in the ones I tried.
If there are any optimizations that could happen anywhere please do comment on it. Regarding my code style, I'm sure there's something to fix there.
In this game you are given a set of numbers and a target. You need to reach the target using only the given numbers and the operators (\$ + \$, \$ - \$, \$ / \$, \$ \times \$). You cannot use any number more than once, but every operator can be used as many times as necessary. You do not need to use every number/operator.
import itertools

target = 225
numbers = [25, 1, 9, 9, 4, 2]
math_functions = "+-/*"
solution = None

def generate_number_permutations(numbers, length):
    return list(itertools.permutations(numbers, length))

def generate_function_permutations(length):
    return list(itertools.product(math_functions, repeat=length))

for x in range(len(numbers)):
    number_permutations = generate_number_permutations(numbers, x+1)
    function_permutations = generate_function_permutations(x)

    if x == 0:
        for y in number_permutations:
            if y[0] == target:
                solution = y[0]
                break
        else:
            continue

    for permutation in number_permutations:
        for functions in function_permutations:
            value = permutation[0]
            for function in enumerate(functions):
                if function[1] == "+":
                    value += permutation[function[0]+1]
                elif function[1] == "-":
                    value -= permutation[function[0]+1]
                elif function[1] == "/":
                    value /= permutation[function[0]+1]
                else:
                    value *= permutation[function[0]+1]

            if value == target:
                solution = permutation, functions
                break
        else:
            continue
        break

    if solution is not None:
        break

print(solution)


texts: JavaScript/Angular 1 - Multiple complex ng-if conditions properties

texts:
I have 4 ng-if which are related with the same conditions properties:

     {{ action.label }}

     {{ action.label }}

     {{ action.label }}

     {{ action.label }}

How can I improve the code with a method that manages all that with parameters, using a map for example?

Solution :

Template :

  {{ action.label }}

  {{ action.label }}

  {{ action.label }}

  {{ action.label }}

Controller :

  navigationType(navigationType, action) {
    const map = {
      'state': action.state && !action.params && !action.href && !action.callback,
      'params': action.state && action.params && !action.href && !action.callback,
      'href': action.href && !action.params && !action.state && !action.callback,
      'callback': action.callback && !action.params && !action.state && !action.href
    }
    return map[navigationType]
  }

Someone has an improvement?