Angularjs CRUD views, controllers, navigation I just started to learn AngularJS. I created a simple site using ASP.NET MVC as a backend.

I created 1 main view and 4 partial views for the CRUD operations with a Company Entity.

In the main page I have this element:

 I load here the required partial view.

I created 2 angular controllers, one for the list of Companies and another one for the update, delete and create operations. I did this based on this answer.

In my list view I can navigate to the other views. My list view is this (only a part of it):

        {{Company.Id}}
        ...
        {{Company.HREmail}}

            <button type="button" ng-click="ChangeView(CRUDOperationEnum.Update, Company)">Go to edit</button>

The CRUDOperationEnum is an object that I have attached to the $scope of the controller so that I can use to way above.

The object is the following:

var CRUDOperationEnum = {
    Create: 0,
    Read: 1,
    Update: 2,
    Delete: 3
};

My ChangeView function is the folowing:

$scope.ChangeView = function (CRUDOperationValue, selectedCompany) {

    if (CRUDOperationValue != CRUDOperationEnum.Create) {
        CompanyShareFactory.SelectedCompany = selectedCompany;
    }
    else {
        CompanyShareFactory.SelectedCompany = { Id: 0, Name: '', HRName: '', HREmail: '' };
    }

    switch(CRUDOperationValue) {
        case CRUDOperationEnum.Create:
            nextViewPath = '/CreateCompany'
            break;
        case CRUDOperationEnum.Delete:
            nextViewPath = '/DeleteCompany'
            break;
        case CRUDOperationEnum.Read:
            nextViewPath = '/Companies'
            break;
        case CRUDOperationEnum.Update:
            nextViewPath = '/EditCompany'
            break;
        default:
            throw "Error: Invalid CRUD operation";
    }

    CompanyShareFactory.CRUDOperationValue = CRUDOperationValue;
    $location.path(nextViewPath);
};

This way the controller decides where to navigate based on what is the required action.

The CompanyShareFactory is injected to the controller and used to store the selected entity so that the client does not have to create another request to get the selected entity by id after changing views. The other controller (that is for delete, update, create) reads it from the factory. This controller also decides what is the current operation based on the CompanyShareFactory.CRUDOperationValue.

Is this a good way to follow using Angular? Please tell me if my approach is wrong, since I just try to find out a good way to perform crud with Angular.

Ideally your code should be easily understandable where you read it.

The buttons says "Go to edit", then is better readable as ng-click="edit(Company). Also the Company is not a class, so general convention is not to capitalize it. But what is CRUDOperationEnum.Update? I don't see where it comes from, so I'd rather avoid it there. If it is already on your scope - it is already accessible inside your controller - no need to pass it again.

Also it looks strange that the same Button leads to different things - that may be confusing to the User.

I would not put different routes inside the same function. Either put clickable links to different routes directly inside your HTML, or use dedicated functions to update the location.


Java and C++ stack implementations with dramatically different performance I'm developing a small programming language for use in any project I have where I feel a small scripting language could be used well. I've written two emulators for the language, one in C++ and one in Java. The C++ performs faster except for any recursion in the language, in which it suddenly performs terribly!

Here is the code from my language that I am running which runs in 1.5s on the Java emulator and 4s on the C++ emulator:

dec i = 0;
recurse();
print i;

def recurse:
    if i < 10000000:
        i++;
        recurse();
    return;

This compiles down into the following instructions:

% i = 0; #define the alias i as being variable 0;
# i needs to be initialised;
STOREINT i 0;
CALL @recurse; #call the label recurse, push this line onto the stack;
PRINTINTLN $i;
END; #end of program;

@recurse; #define the function recurse;
# if i is < 10000000 then inc i;
GEQ $i 10000000;
JCMP @return; #jump to the return statement
INC i;
CALL @recurse;
@return;
RETURN; #return back to the line on the top of the stack;

The C++ implementation differs slightly from the Java implementation in that it uses an array of unions to store each "typeless" object, whereas Java just uses Object. Other than that, the code is almost identical (with C++ not needing to do any casting because from the instructions we can be sure which field  in the union we are using, and therefore we access the correct field instead of casting the Object to the correct type in Java. C++ also doesn't need to use & 0xFF in order to fix sign problems with the java byte type, as we can make unsigned chars). The main difference between them seems to be the performance of the call stacks, which are implemented in each case as follows:

Java

public class ArrayStack<T> implements Stack<T>
{
    private static final long serialVersionUID = 1L;
    protected Object[] stack;
    protected int capacity;
    protected int pointer;

    public ArrayStack(int capacity)
    {
        stack = new Object[capacity];
        this.capacity = capacity;
        clear();
    }

    public void push(T value)
    {
        stack[pointer++] = value;
    }

    public T pop()
    {
        return (T) stack[--pointer];
    }

    public T peek()
    {
        return (T) stack[pointer-1];
    }

    public boolean isEmpty()
    {
        return pointer == 0;
    }

    public boolean isFull()
    {
        return pointer == capacity;
    }

    public void clear()
    {
        pointer = 0;
    }

    public int size()
    {
        return pointer;
    }

    public int capacity()
    {
        return capacity;
    }
}

C++

template <class T> class ArrayStack
{
    private:
        T* stack;
        int capacity;
        int pointer;

    public:
        ArrayStack(int capacity)
        {
            this->capacity = capacity;
            stack = new T[capacity];
            clear();
        }

        ~ArrayStack() { delete stack; }
        void push(T value) { stack[pointer++] = value; }
        T pop() { return stack[--pointer]; }
        T peek() const { return stack[pointer-1]; }
        bool isEmpty() const { return pointer == 0; }
        void clear() { pointer = 0; }
        int size() const { return pointer; }
        int getCapacity() { return capacity; }
};

I'll provide the case statements running during this program below if anybody wants to see them, but for now I'll leave them out to keep this post a little shorter!

To my eyes, the C++ looks like it should be either faster than or equal to the Java one, as even if new was the slow part of the C++ code, that isn't taken into account in the timing of the program execution, which starts timing as soon as the first instruction is executed. Could it be that I'm storing the stack as a member variable in the Emulator class, and not as a pointer or something like that, or something the JIT compiler can do that the static C++ compiler (on O3) can't?

Performance

I'll get to a bit of a review, but first, since you're most interested in performance, I've done some benchmarking. In short, all evidence points towards maaartinus' theory being the cause.

Benchmark.java:

public class Benchmark {

    private static class Stored {
        private final int[] big = new int[250];

        public Stored() { }
    }

    public static void main(String[] args) {

        // Create the objects up front so we don't include allocation/construction time in the benchmark
        Stored stored[] = new Stored[1000000];
        for (int i = 0; i < stored.length; ++i) { stored[i] = new Stored(); }

        for (int n = 0; n < 100; ++n) {
            long start = System.nanoTime();

            ArrayStack<Stored> stack = new ArrayStack<Stored>(1000000);
            for (int i = 0; i < 1000000; ++i) { stack.push(stored[i]); }
            for (int i = 0; i < 1000000; ++i) { stack.pop(); }

            long end = System.nanoTime();

            if (!stack.isEmpty()) { System.out.println("This is just here to make sure nothing gets optimized out."); }

            System.out.printf("Time: %f seconds%n", (end - start) / 1e9);
        }
    }
}

Once the JVM has warmed up and some JITing has (presumably) happened, each test takes 0.0038 seconds (with a very small variance). If the size of big in Stored is changed, this doesn't change timings since the stack stuff is still just copying a reference. Even if more references are added to Stored, this increasing the size of stored, there is still no time increase. This all makes sense: all Java has to do is copy a pointer, and the size of this pointer is fixed.

benchmark.cpp

int main() {

    // To be consistent with the Java approach, we'll create the objects up front. Noteably, this doesn't actually
    // matter since the copying of the objects is just as expensive as creation.
    // (Note: typically it wouldn't make sense for this to be dynamically allocated, but 1000000 objects was too big for
    // the stack.)
    Stored* stored = new Stored[1000000]();

    // Do the simple approach
    for (int n = 0; n < 100; ++n) {
        auto start = std::chrono::high_resolution_clock::now();

        ArrayStack<Stored> stack(1000000);
        for (int i = 0; i < 1000000; ++i) { stack.push(stored[i]); }
        for (int i = 0; i < 1000000; ++i) { stack.pop(); }

        if (!stack.isEmpty()) { std::cout << "This is here so the code doesn't get optimized out.\n"; }

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end - start;
        std::cout << "Time: " << diff.count() << " seconds\n";
    }
}

This was run with a few different Storeds. The first was a relatively large class:

struct Stored {
    int x[250];
};

The second was a very light class:

struct Stored {
    int x[1];
};

As a third option, the large class was kept, but rather than storing a value, a pointer was stored in the stack:

for (int i = 0; i < 1000000; ++i) { stack.push(&stored[i]); }

The timings were 0.30 seconds, 0.001 seconds, and 0.001 seconds for options 1, 2, and 3, repsectively. This is consistent with the Java theory and findings: C++ is peforming expensive copies that Java is not doing.

Benchmark Conclusions

The question now obviously becomes how to optimize your C++, and unfortunatley there's no simple solution to that without knowing a lot more about what exactly it is that you're putting into your stack. Move semantics are one option, provided your copying is expensive and you'd be happy to sacrifice the object into the stack rather than copy it.

The other option is to move away from value semantics so that copies become cheaper. If you have simple hierarchical ownership semantics (e.g. the objects being stored in the stack will always outlive the stack), this is super easy: just store pointers in the stack instead of objects. If your ownership isn't quite so simple, you would need to consider using something like heap allocation and a smart pointer. Both of these approaches are trade offs though. Smart pointers are safe but relatively expensive to copy, and raw pointers can quickly become a confusing mess if you're not very particular and consistent with your semantics. In both cases you no longer have the pleasantness of value semantics.


Efficient pathfinding without heuristics? Part of my program is a variable-sized set of Star Systems randomly linked by Warp Points. I have an A* algorithm working rather well in the grid, but the random warp point links mean that even though the systems have X,Y coordinates for where they're located on a galactic map, a system at 2,3 isn't always linked directly to a system at 2,4 and so the shortest path may actually lead away from the target before it heads back towards it. I think this limitation eliminates A* since there's almost no way to get a good heuristic figured out.

What I've done instead is a recursive node search (I believe this specific pattern is a Depth-First Search), and while it gets the job done, it also evaluates every possible path in the entire network of systems and warp points, so I'm worried it will run very slowly on larger sets of systems. My test data is 11 systems with 1-4 warp points each, and it averages over 700 node recursions for any non-adjacent path.

My knowledge of search/pathfinding algorithms is limited, but surely there's a way to not search every single node without needing to calculate a heuristic, or at least is there a heuristic here I'm not seeing?

Here's my code so far:

private int getNextSystem(StarSystem currentSystem, StarSystem targetSystem,
                          List<StarSystem> pathVisited)
{
    // If we're in the target system, stop recursion and
    // start counting backwards for comparison to other paths
    if (currentSystem == targetSystem)
        return 0;

    // Arbitrary number higher than maximum count of StarSystems
    int countOfJumps = 99;
    StarSystem bestSystem = currentSystem;

    foreach (StarSystem system in currentSystem.GetConnectedStarSystems()
                                  .Where(f=>!pathVisited.Contains(f)))
    {
        // I re-create the path list for each node-path so
        // that it doesn't modify the source list by reference
        // and mess up other node-paths
        List<StarSystem> newPath = new List<StarSystem>();
        foreach (StarSystem s in pathVisited)
            newPath.Add(s);
        newPath.Add(system);

        // recursive call until current == target
        int jumps = getNextSystem(system, targetSystem, newPath);

        // changes only if this is better than previously found
        if (jumps < countOfJumps)
        {
            countOfJumps = jumps;
            bestSystem = system;
        }
    }
    // returns 100 if current path is a dead-end
    return countOfJumps + 1;
}

Complete and Incomplete Algorithms

Search algorithms can be classed into two categories: complete and incomplete.

A complete algorithm will always succeed in finding what your searching for. And not surprisingly an incomplete algorithm may not always find your target node.

For arbitrary connected graphs, without any a priori knowledge of the graph topology a complete algorithm may be forced to visit all nodes. But may find your sought for node before visiting all nodes. A* is a complete best-first method with a heuristic to try to avoid searching unlikely parts of the graph unless absolutely necessary.

So unfortunately you can not guarantee that you will never visit all nodes whatever algorithm you choose. But you can reduce the likelihood of that happening.

Without pre-processing

If you cannot consider pre-processing your graph then you're stuck with a myriad of on-line algorithms such as depth-first, breadth-first, A* and greedy-best-first. Out of the bunch I'd bet on A* in most cases if the heuristic is even half good and the graphs are non-trivial.

If you expect all routes to be short, a breadth-first algorithm with cycle detection and duplicate node removal may outperform A* with a poor heuristic. I wouldn't bet on it though, you need to evaluate.

With pre-processing

In your case I'd see if I could pre-process the graph, even if you need to repeatedly re-do the pre-processing when the graph changes as long as you do sufficiently many searches between pre-processing it would be worth it.

You should look up Floyd-Warshall (or some derivative) and calculate the pairwise cost/distance/jumps between all nodes and use this table as a heuristic for your A*. This heuristic will not only be admissible, it will be exact and your A* search will complete in no-time.

Unless you of course modify the algorithm to store all pairwise routes as they are detected in a matrix of vectors, then you have O(1) run time at the cost of memory.


LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers II I'm posting my Python code for LeetCode's 1320. If you have time and would like to review, please do so.
Problem

You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for
example, the letter \$A\$ is located at coordinate \$(0,0)\$, the letter
\$B\$ is located at coordinate \$(0,1)\$, the letter \$P\$ is located at
coordinate \$(2,3)\$ and the letter \$Z\$ is located at coordinate
\$(4,1)\$.

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates
\$(x_1,y_1)\$ and \$(x_2,y_2)\$ is \$|x_1 - x_2| + |y_1 - y_2|\$.

Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers
do not have to start at the first letter or the first two letters.

Example 1:
Input: word = "CAKE" Output: 3
Explanation:
Using two fingers, one optimal way to type "CAKE" is:

Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1

Total distance = 3
Constraints:

\$2 \le \text{word.length} \le 300\$
Each word[i] is an English uppercase letter.

Accepted Python
import string
import functools

class Solution:
    def minimumDistance(self, word: str) -> int:
        WIDTH = 6
        A_DECIMAL = 65
        def get_coordinates(left: int, right: int) -> int:
            if not left or not right:
                return 0

            x_left, y_left = indices[left]
            x_right, y_right = indices[right]

            return abs(x_left - x_right) + abs(y_left - y_right)

        @functools.lru_cache(None)
        def get_dp(index, word_a: str = None, word_b: str = None) -> None:
            if index == len(chars):
                return 0

            dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)
            dist_b = get_coordinates(word_b, chars[index]) + get_dp(index + 1, word_a, chars[index])

            return min(dist_a, dist_b)

        chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)
        indices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}
        return get_dp(0)

Reference
On LeetCode, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss

Some remarks
A_DECIMAL and it's use
A_DECIMAL = 65
# [...]
indices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}

there is nothing wrong with
ord('A')

which you can use inline without defining a global (which it is not in the required Solution context).
You can even get rid of the ord math by enumerating.
indices = {char: divmod(idx, WIDTH) for idx, char in enumerate(string.ascii_uppercase)}

Names
def get_coordinates(left: int, right: int) -> int:
    if not left or not right:
        return 0

    x_left, y_left = indices[left]
    x_right, y_right = indices[right]

    return abs(x_left - x_right) + abs(y_left - y_right)

does in no way return coordinates, it returns a distance.
Also left and right was misleading me, I thought of the two finger positions.
Also you claim the parameters are ints. Actually you pass characters. That is sloppy.
dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)

is near to obfuscation. get_coordinates delivers a distance, word_a is not a word but a character where one finger is on, and what get_dp delivers cannot be guessed from the name nor is a docstring existing.
Algorithm
You use depth first search (DFS) while for finding the shortest path typically breadth first (BFS) is the better approach. With DFS you have to search the whole tree. By introducing an lru cache you found a nice trick to shortcut some branches. Still you cannot find the shortest path early but have to check the whole tree.
While the fingers are exchangeable you handle them as if they could not be swapped. So you find two optimal paths, one starting with the left finger, one starting with the right. Identical sequence, only the fingers are swapped. Also the cache does not match swapped fingers.
Cache
As already said, your cache does not match swapped fingers. By sorting the fingers you could match them. You do the lru cache on a function in a function. As the inner function is only existing while the outer is running also your cache is working for a single word only. Another call with the same word cannot be served from cache. If you pull the function on class level and change the signature to hold the remaining word instead of the index you could reuse cached "endgames".
A function that would greatly benefit from a lru cache is get_coordinates (read get_distance)
Hostile test cases
You should implement a BFS with priority queue. Then you do some logging and timing on tests like "FY"*150. While the minimum distance is 0, your DFS evaluates branches at a distance of near 2700. A BFS would register nodes at a max distance of 9 but would never follow them.
Other
The line
chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)

would deserve an explanatory comment or a nice function name.


Brainfuck interpreter improvement I created a brainfuck interpreter in javascript. It works good to me as I have seen no bugs in my compiler. I like to get a suggestion and review from you to what should this compiler improve.

Here's the short code:

function bf(str, input){

var array = str.split("");

var memory = [0];

var pointer = 0;

var result = [];

var open = [];

for(var i = 0; i < array.length; i++){

  if(array[i] == ">"){

    pointer++;

    if(memory.length-1 < pointer){

     memory.push(0);

    }

  }else if(array[i] == "<"){

    if(pointer > 0){

     pointer--;

    }else{

     throw "Overflow Error at " + i

    }

  }else if(array[i] == "+"){

    if(memory[pointer] < 255){

      memory[pointer]++;

    }else{

      memory[pointer] = 0;

    }

  }else if(array[i] == "-"){

    if(memory[pointer] > 0){

      memory[pointer]--;

    }else{

      memory[pointer] = 255;

    }

  }else if(array[i] == "."){

    result.push(String.fromCharCode(memory[pointer]));

  }else if(array[i] == ","){

    memory[pointer] = input.shift().charCodeAt(0);

  }else if(array[i] == "["){

    if(open.length){

      if(open[open.length-1] != i){

        open.push(i);

      }

    }else{

      open.push(i);

    }

  }else if(array[i] == "]"){

    if(open.length){

      if(memory[pointer]){

        i = open[open.length - 1];

      }else{

        open.pop();

      }

    }

  }

}

return result;

}

General style points

No need to split the str into an array, you can access the character directly using bracket notation. eg str[i] === ">"

If you want a number to cycle over a range use the remainder operator % to do that. Example  to add 1 memory[pointer] = (memory[pointer] + 1) % 255 and to subtract memory[pointer] = (memory[pointer] + 254) % 255.
However as you want to simulate memory as bytes you may as well use a typed array that has an Unsigned Char. The bytes in the array behave the same as they would on the VM that runs BF commands. Example const memory = new Uint8Array(1024)

Not sure why you throw overflow for "<" when you don't throw the same error >. < should just cycle to highest byte in memory.

Use "const" for variables that do not change.

Use === and !== rather than == and !=

Don't double space (every other line empty). It makes the code hard to read as it will not fit to one screen.

Naming is rather poor.
-result could be better as "output"

str maybe commands or program
i maybe programCounter or commandIndex. I am old school so would use pc

Rather than index into an array over and over, as you do with array[i], store it in a variable const command = array[i]; and then if(command === ">") { makes the code more compact and easier to follow.

Design.
You can use a lookup to get the action required for each command. (see example commandList) rather than one long if() {}else if().... This is a lot quicker to run as you don't need to step over else if statements to find the matching block. Also make it easy to add or change commands, and easier to read.
The Bug
As I pointed out in the comments there is a bug. You have not implemented the "[" command correctly. This is a big issue as many programs will fail. To solutions are non trivial.
There are two solutions.

When you need to skip ahead search for the matching close. This can cost a lot of performance.
Compile the code and locate matching open and close [ and ] so that you can quickly locate the match and move to it if required.

Ease of use
The input and output would be better as strings rather than arrays. Makes the BF easier to use.
The halting problem.
There is a fundamental requirement you have missed. You can never know if the program you are running will exit.
As JavaScript is blocking this means there is no way to stop the execution if the bf code goes into infinite loop. You should protect against this problem.
The easiest is to put a limit on the number of instructions, and throw error if reached.
Or you could have the commands execute on a timer.
Example
The function name is bfVM for brainFuckVirtualMachine and requires a compiled program. (as that is how I fixed your bug).
I included the compiler, all it does is find matching blocks and maps them to each other. returns a compiled object.
And two programs as testing fodder.

// Run two comnpiled BF programes.
setTimeout(() => {
console.log(bfVM(helloWorld))
console.log(bfVM(addNums))
},0);
/* Old school naming pc is program counter, ptr is a pointer, and
   inPtr is input pointer */
function bfVM(compiled, input) {
    const program = compiled.program;
    const blocks = compiled.blocks;
    const RAM = compiled.RAM;
    const memory = new Uint8Array(RAM);
    const commandList = {
        ">"(){ ptr = (ptr + 1) % RAM },
        "<"(){ ptr = (ptr + RAM - 1) % RAM },
        "+"(){ memory[ptr]++ },
        "-"(){ memory[ptr]-- },
        "."(){ output += String.fromCharCode(memory[ptr]) },
        ","(){ memory[ptr] = input.charCodeAt(inPtr++) },
        "["(){ pc = !memory[ptr] ? blocks.get(pc)[0] : pc },
        "]"(){ pc = memory[ptr] ? blocks.get(pc)[0] : pc  },
    };

    var cycles = 0, ptr = 0, pc = 0, inPtr = 0, output = "";
    while (pc < program.length && cycles++ < MAX_CYCLES) {
        const cmd = commandList[program[pc]];
        cmd && cmd();
        pc ++;
    }
    if (cycles=== MAX_CYCLES) { throw new Error("Cycle limit reached at PC: " + pc)  }
    return output;
}

const MAX_CYCLES = 1024 * 1024;  // Limit of execution steps.
function compileBF(program, RAM) {
    var pc = 0;
    const blocks = new Map();
    const blockStack = [];
    while (pc < program.length) {
        if (program[pc] === "[") {
            blocks.set(pc, [])
            blockStack.push(pc);
        } else if(program[pc] === "]") {
            const open = blockStack.pop();
            const block = blocks.get(open);
            if (block === undefined) {
                throw new Error("Syntax error: No matching block for ']' at " + pc);
            }
            block[0] = pc;
            blocks.set(pc, [open]);
        }
        pc++;
    }
    if (blockStack.length) {
       throw new Error("Syntax error: Block missmatch at " + pc);
    }
    return {program, blocks, RAM};
}

const nums = ["", "+", "++", "+++", "++++", "+++++", "++++++", "+++++++", "++++++++", "+++++++++"]
const toASCIINum = "++++++++[<++++++>-]<"
const helloWorld = compileBF(("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."), 14)
const addNums = compileBF(nums[5]+">"+nums[4]+"[<+>-]"+toASCIINum+".",2);


Task Wrappers for starting operation only if previous task has finished I've written these two wrappers around Tasks, to help with common scenarios in our code where methods are called repeatedly, even if the previous operation hasn't completed yet. There are two common scenarios:

An operation is triggered several times by the user (e.g. clicking a checkbox filters a list by its value. User clicks 3 checkboxes in quick succession). In this case, every operation starts a possibly expensive server call, but I only care about the last one.
A periodic operation is triggered by a timer every x seconds, but the operation sometimes takes more than x seconds. In this case, I don't want to start a new operation but to simply skip it, waiting for the next timer event to try again.

The solution I've used for both of these is similar:

public static void ExecuteAndCancelPreviousTask(ref Task previousTask, ref CancellationTokenSource cancellationTokenSource, Action action)
{
    if (previousTask != null && !previousTask.IsCompleted)
        cancellationTokenSource.Cancel();

    cancellationTokenSource = new CancellationTokenSource();
    previousTask = Task.Run(action, cancellationTokenSource.Token);
}

public static void ExecuteIfPreviousTaskComplete(ref Task previousTask, ref CancellationTokenSource cancellationTokenSource, Action action)
{
    if (previousTask != null && !previousTask.IsCompleted)
        return;

    cancellationTokenSource = new CancellationTokenSource();
    previousTask = Task.Run(action, cancellationTokenSource.Token);
}

In both cases, I receive the previously running operation (which can be null, the first time) and the CancellationTokenSource attached to it. In the first case, I use the CTS to cancel the previous operation. In the second, I simply ignore it and skip running the action.

Of course, the Action passed has to be CTS-aware, and check it for cancellation:

public void Timer_Elapsed()
{
    TaskExtensions.ExecuteIfPreviousTaskComplete(ref _pollingTask, ref _pollingCancellationTokenSource, async () =>
    {
        var cts = _pollingCancellationTokenSource;
        var pollingResults = await _service.Poll();
        if (cts.IsCancellationRequested)
           return;
        UpdateFromResults(pollingResults);
    });
}

My questions are:

Do you feel that these methods clearly express their purpose and usage?
I'm a bit leery of the two ref parameters. But since the methods have the update the task and its CTS, I could see no better way.
I don't really have a need for the action to be run on a new thread. I mainly use Task.Run() because I need, well, a Task that can be monitored and cancelled. Should I instantiate the task some other way?
The two methods are almost identical except for the second line of each, but I figured that their usage and intent are clearer when they're separate. Should I merge them? Should I keep them as two distinct public methods, but merge their implementation into a single private method? Or is this overkill for two and a half lines of code?
In the first case, should I wait, after Canceling the task, before creating a new one? Make sure it's ended?
Currently, I'm capturing the CancellationTokenSource at the beginning of my Action so that it doesn't get replaced when the ref is updated. Is this necessary? Or will the capture keep the original value?

I think you might by overengineering it. Have you tried the Task.ContinueWith method which

  Creates a continuation that executes asynchronously when the target Task completes.

There are multiple overloads that let you specify a lot of options with the TaskContinuationOptions enumeration.


Create and open a file to take lecture notes depending on day and time I am just wondering what, if any, more elegant ways might exist to write a script to accomplish the task that the script below accomplishes. The script works, so I don't need it to be debugged, but I want to learn more. Other commands to be used, other ways of structuring it, etc. I have taken it through shellcheck.

Yesterday I decided to try my hand at a shell script that would create and open a file to take notes for each of my classes in the folder designated for notes from that class. It was pretty satisfying to do; I started with basically no knowledge and over the course of an hour or two I went from a script that would prompt me to enter the class and the desired file title (read Class read Title if [[ $Class = "X]] then touch /path/"$Title".docx etc) to something that would just create the file in the right place based on the time/date the command is invoked, since the title is always today's date anyhow.

Again, it works. I just know that there must be more ways to skin this cat and I was wondering what those might be. The version below has been revised once after input from some good samaritans.

Also, FWIW, this is running on OS X Sierra.

#!/bin/bash

read date hour day month <<< $(date +"%-d %-H %a %B")
if [[ $hour -lt 11 && $day = "Tue" ]] || [[ $hour -lt 11 && $day = "Thu" ]]; then
    dir="/path/to/first"
elif [[ $hour -gt 12 && $hour -lt 15 && $day = "Tue" ]] || [[ $hour -gt 12 && $hour -lt 15 && $day = "Thu" ]]; then
    dir="path/to/second"
elif [[ $hour -ge 16 && $hour -le 17 && $day = "Wed" ]]; then
    dir="/path/to/third/"
else
    echo "I am of no use to you right now"
    exit 1
fi
file="$dir/$month $date".docx
touch "$file"
open "$file"
killall Terminal

killall Terminal is very harsh!  Maybe you aren't a serious Terminal user now, but someday, you might be doing something important in another Terminal window.  And, due to the way macOS works, multiple windows all run under a single Terminal process, so you would be killing all of your Terminal windows.  At most, do

osascript -e 'tell application "Terminal" to close the front window'

… which sends a message to just one window using AppleScript.  But I would consider even that to be too violent for my taste.

I find those cases too cumbersome to read as conditions.  I would write out all of the combinations, using pattern matching, and in particular, extended pattern matching enabled by shopt -s extglob.

#!/bin/bash

shopt -s extglob

read date hour day month <<< $(date +"%-d %-H %a %B")

case $day.$hour in
    @(Tue|Thu).@(8|9|10|11))
        dir="/path/to/first"
        ;;
    @(Tue|Thu).@(13|14))
        dir="/path/to/second"
        ;;
    Wed.16)
        dir="/path/to/third"
        ;;
    *)
        echo "I am of no use to you right now"
        exit 1
esac
…


Calculating the number of prime numbers to solve the puzzle How can the following program execution time improved?  I have used dynamic programming in both "recursive" as well as "prime" function, but I'm not getting the efficient execution time.

  There is a wall of size 4xN in the victim's house where. The victim
  also has an infinite supply of bricks of size 4x1 and 1x4 in her
  house. In every configuration, the wall has to be completely covered
  using the bricks. Gale Bertram wants to know the total number of ways
  in which the bricks can be arranged on the wall so that a new
  configuration arises every time.

  Let the number of Configuration = \$M\$.

  So, he wants Patrick to calculate the number of prime numbers (say \$P\$)
  up to \$M\$ (i.e. \$<= M\$).  You are required to help Patrick correctly solve
  the puzzle.

  Sample Input

  The first line of input will contain an integer \$T\$
  followed by \$T\$ lines each containing an integer \$N\$.

  Sample Output

  Print exactly one line of output for each test case. The
  output should contain the number \$P\$.

  Constraints

  \$1 <= T <= 20\$
  \$1 <= N <= 40\$

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Solution{
    public static int[] b = new int[217287];
    public static void main(String[] args){
        Scanner stdin = new Scanner(System.in);
        int t = stdin.nextInt();
        int[] a = new int[41]; //array initialized before because the value remains same.
        for(int j=0;j<4;j++){
                a[j] = 1;          //till n<=3, number of possiblities = 1. These will work as base cases.
            }
            a[4] = 2;
        for(int x=0;x<t;x++){
            int n = stdin.nextInt();
            for(int i=5;i<=n;i++){
                a[i] = -1;         //initialise all value in the array as -1.
            }
            if(n<4)
                System.out.println("0"); // if n<4, number of possibilities =1. So no prime number before that is 0.
            else{
                         //for n=4, possibilities = 2. This is a base case.
            int num1 = recursive(a,n);          // storing number of possibilities in num1.
            int num2 = prime(num1);    //calling to calculate number of prime numbers before or equal to num1.
            System.out.println(num2);
            }
        }
    }
    public static int recursive(int[] a, int n){
        if(a[n]!=-1)                             // retrieving a[n] value if already calculated.
            return a[n];
        else{
            a[n] = recursive(a,n-1) + recursive(a,n-4); // calling recursively.If we fill with a 4*1 first tile then number
                                                        //tiles left is n-1(try visualising).If we fill 1*4 tile first
                                                        // we have n-4 tile left.
            return a[n];
        }
    }
    public static int prime(int n){
        int count = 0;
        if(b[n]!=0)
            return b[n];
        else{
        for(int i=2;i<=n;i++){
            if(b[i]!=0){
                count = b[i];
            }
            else{
            int flag = 0;
            for(int j=2;j<=i/2;j++){
                if(i%j==0){
                    flag = 1;
                    break;
                    }
                }
        if(flag==0){
            count++;
            b[i]=count;
        }
        }
        }
        return count;
        }
    }
}

I got a timeout (more than 4s) for the following input:

20
35
23
25
38
4
35
19
8
23
35
3
36
12
10
30
13
18
31
40
37

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

Clean up those imports. Importing everything in a package is a bad idea, as it might easily lead to conflicts between same named classes. Also it is hard to see what is actually used.

You ain't got a package defined, define one.

class Solution{

That's a not very good class name. Classes should be named after what purpose they serve, or what purpose the methods contained within the class serve.

public static int[] b = new int[217287];

Here is the ultimate rule for variable naming:

  You're only entitled to use one character variable names if you're dealing with dimensions (x, y, z). Second best is you're allowed to use one character variable names in simple for loops (i, j, k)...but the last point is up for debate and it should not be the case.

And here is a simple guide for naming variables:

  Name variables after what they contain. You're not allowed to use one character variables except when dealing with dimensions.

Why is it so important to name variables after what they do? Well, quick, tell me what this code does:
 if (b[n] != 0).

for(int x=0;x<t;x++){

This is even worse. x is normally only used for the dimension, so unless you're looping over the x dimension of something here, this variable should be called different and according to what it does.

for(int i=0;i<=n;i++){
    a[i] = -1;         //initialise all value in the array as -1.
}

Only comment things that are not obvious from the code. In this case I can see that the array is initialized to -1...or I could see it if the variables would have fitting names:

for (int index = 0; index < a.length; index++) {
    a[index] = -1;
}

Note that a is still not a good name. Also what I do not see from the code at this point is why it is initialized to that value. So if to comment something, then the why is interesting.

if(n<4)
    System.out.println("0"); // if n<4, number of possibilities =1. So no prime number before that is 0.
else{

You should not omit braces from ifs and fors, even one line once. It can be very confusing in the long run.

else{
for(int j=0;j<4;j++){
    a[j] = 1;          //till n<=3, number of possiblities = 1. These will work as base cases.
}
a[4] = 2;             //for n=4, possibilities = 2. This is a base case.
int num1 = recursive(a,n);          // storing number of possibilities in num1.
int num2 = prime(num1);    //calling to calculate number of prime numbers before or equal to num1.
System.out.println(num2);
}

Why are your else branches not indented?

public static int recursive(int[] a, int n){

That's another not very good name. Functions should be verbs, not adjectives. They have a function, not a state, and the name should mirror that function.

You have no JavaDoc in there, fix that.

Consider using a code formatter, and then consider using more blank lines and more whitespace to make the code easier readable.


Gathering emails, phones, URIs, and tag related to a room I've made a strange method with multiples conditionals, creating a lot of Lists and I was wondering if I could write it in a better and more legible way.

def findRooms(room:Room) = {
    ...
    if(room.id != null && !room.id.isEmpty)
      query+=("_id" -> room.id)
    if(room.members != null && room.members.length > 0){
      val emails = scala.collection.mutable.MutableList[String]()
      val phones = scala.collection.mutable.MutableList[String]()
      val forwardUris = scala.collection.mutable.MutableList[String]()
      for(member <- room.members){
        if(member.email != null && member.email != None)
          emails+=member.email.get
        if(member.forwardUrl != null && member.forwardUrl != None)
          forwardUris+=member.forwardUrl.get
        if(member.phoneNumber != null && member.phoneNumber != None)
          phones+=member.phoneNumber.get
      }

      if(emails.size > 0)
        query+=("members.user.email" -> MongoDBObject("$all" -> emails))

      if(phones.size > 0)
        query+=("members.user.phoneNumber" -> MongoDBObject("$all" -> phones))

      if(forwardUris.size > 0)
        query+=("members.user.forwardUrl" -> MongoDBObject("$all" -> forwardUris))
    }

    if(room.tags != null && room.tags.length > 0){
      val tags = scala.collection.mutable.MutableList[String]()
      for(tag <- room.tags){
        tags+=tag
      }
      if(tags.size > 0){
        query+=("tags" -> MongoDBObject("$in" -> tags))
      }
    }
    ...
}

There's really not much we can help you, given the low level of detail in the question.

There are somethings you have in this code snippet that are generally considered a Very Bad Idea, so I'll give what help I can in that regard.

Null Checks

There are a bunch of these types of checks in the posted code:

if(room.id != null && !room.id.isEmpty)

If you have any control at all over Room you should be using Option instead. If you have no control over Room, define these methods using an implicit. These checks should only every be made in one place, not every place that accesses the code.

Assuming that id is a String (just a guess). The signature should in Room should be:

def idOption: Option[String] = Option(this.id).filter(_.nonEmpty)

Which would drop the code in the snippet to:

room.idOption.foreach(id => query += ("_id" -> id))

Much simpler.

Premature Optimizations

If you ever have enough members in a room for the MutableList optimization to gain you anything, you'll probably be exceeding the length of the Mongodb query. This needlessly complicates your code.

Ironically, any gains are lost when you forgot to use nonEmpty rather than .size > 0, which needs to iterate through the lists you just made to avoid iterating through the lists.

It looks like the accessors for the Member attributes already return Option values, so this can be much more readably rendered like this:

val emails = for {
  member <- room.members
  email <- member.email
} yield email

val phones = for {
  member <- room.members
  phone <- member.phoneNumber
} field phone

// 'uri' is not the plural of 'url', they are not
// actually equivalent, please don't conflate them.
val forwardUrls = for {
  member <- room.members
  url <- member.forwardUrl
} yield url

if(emails.nonEmpty)
  query+=("members.user.email" -> MongoDBObject("$all" -> emails))

if(phones.nonEmpty)
  query+=("members.user.phoneNumber" -> MongoDBObject("$all" -> phones))

if(forwardUrls.nonEmpty)
  query+=("members.user.forwardUrl" -> MongoDBObject("$all" -> forwardUrls))

Redundant Code

Much of the tags block is a no-op. It condenses down to just this:

if (room.tags.nonEmpty) {
  query+=("tags" -> MongoDBObject("$in" -> room.tags))
}


Scoping and asynchronous function I have the following code where I need to return an array of objects as a response that has values from the server. The objects are filled with the right values, but when they are pushed into the array they are pushed before. What's the best way of rewriting this asynchronously?

  router.post('/teacher-schedule',function(req,res){
var teacher_id= req.body.teacher_id,
    school_id= req.body.schoolId,
    array = [], tempo = {};

Schedule.find({school_id:school_id}).then(function(schedules){
    schedules.forEach(function(element){
        ClassSection.findOne({_id:element.class_section_id},function(err,cla){
            if(err){
                console.log(err);
                return res.json({status:"error", message:"error occurred"})
            }else{
                element.entry.forEach(function(entries){
                    if( entries.teacher_id==teacher_id){
                        tempo = {};
                        console.log("tempo fade"+ tempo)
                        tempo.class_section = cla.class_title;
                        tempo.class_section_code = cla.code;
                        tempo.schedule_id =schedules._id ;
                        tempo.class_section_id = element._id;
                        tempo.subject_id = entries.subject_id;
                        console.log("tempo gabel el subject"+ tempo)
                        Subject.findOne({_id:entries.subject_id},function(err,subject){
                            if(err){
                                console.log(err);
                                return res.json({status:"error", message:"error occurred"})
                            }else{
                                tempo.subject_title = subject.title;
                            }
                        })

                        array.push(tempo);// its always an empty value
                    }

                })
            }
        })

    });
    res.json({status:"success",message:"successfully returned", records: array})
}).catch(function(err){
    console.log(err);
    res.json({status:"error", message:"error occurred"});
})
});

Direction

With latest version of Ecmascript we get async/await that allow us writing asynchronous code in synchronous style.

Consider an example where function f(...) returns you Promise<F>, and g(...) returns Promise<G>. We can use the following constructions then:

try {
  const resultF = await f();
  const resultG = await g(resultF);
  // keep working with as if we were writing "regular" synchronous code
} catch (anyError) {
  console.error(anyError);
}

This code has to be declared in an async function or arrow function to work. Otherwise, it's still a perfectly asynchronous code...

Sample

In your case, the transformed solution could look similar to this. Please understand this is not 100% working code, because I am not familiar with the particular API of ClassSection that your code deal with. This is more of a sketch to show the direction.

router.post('/teacher-schedule', async (req, res) => {
  const records = [];

  try {
    const schedules = await Schedule.find({school_id : req.body.schoolId});
    schedules.forEach(schedule => {
      ClassSection.findOne(
        { _id: schedule.class_section_id},
        (classSectionSearchError, classSection) => {
          if (err)
            throw new Error(classSectionSearchError);

            schedule.entry.forEach(entryFound => {
            if (entryFound.teacher_id === req.body.teacher_id) {
              const tempo = {
                class_section: classSection.class_title,
                class_section_code: classSection.code,
                schedule_id: schedules._id ,
                class_section_id: schedule._id,
                subject_id: entryFound.subject_id,
              };

              Subject.findOne(
                { _id: entryFound.subject_id},
                (subjectSearchError, subject) =>
                {
                  if (subjectSearchError)
                    throw new Error(subjectSearchError);
                  tempo.subject_title = subject.title;
                }
              );

              records.push(tempo);
            }
          })
      })
    });
    res.status(200).json({ records: records });
  } catch (errorCaught) {
    console.log(errorCaught);
    res.status(500).json({ details: "error occurred: " + JSON.stringify(errorCaught) });
  }
});

Bonus

There's whole lot more potential improvements unrelated to asyncronousity, though.

Use === instead of ==, unless you have a strong reason not to follow this advice.
Please setup eslint tool -- it's really hard to read the code which is formatted like that.
Use const for variable declarations. If something needs to get reassigned, use let. Do NOT use var unless it is necessary (which is super rare the case).
If you're using node.js consider using arrow functions.
In case of errors set status code to HTTP 500 Internal Server Error, whereas for success use 2XX (they vary depending on scenario).
Use proper names. array is too generic. records is actually what's being collected.
Use proper names. cla name means nothing to a reader...
Logging an object right after creation, but before population is meaningless:

tempo = {};
console.log("tempo fade" + tempo)

Do NOT declare all the variables before actually using them. Always try to achieve joint declaration and assignment: const recordsFound = [].


Rotate square matrix clockwise by 90degrees #include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

void nl(void) {     //function to print new line
    printf("\n");
}

int** allocate(_size) {
    int** matrix=(int**)malloc(sizeof(int*)*_size);
    for(int i=0;i<_size;i++) {
        matrix[i]=(int*)malloc(sizeof(int)*_size);
    }
    return matrix;
}

void scanMatrix(_matrix,_size)
int** _matrix;
{
    printf("Enter the values: ");
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size;j++) {
            scanf("%d",&_matrix[i][j]);
        }
    }
}

void printMatrix(_matrix,_size)
int** _matrix;
{
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size;j++) {
            printf("%d ",_matrix[i][j]);
        }
        nl();
    }
}

void swap(num1,num2)
int* num1;
int* num2;
{
    *num1=*num1+*num2;
    *num2=*num1-*num2;
    *num1=*num1-*num2;
}

void rotateMatrix(_matrix,_size)
int** _matrix;
{
    for(int i=0;i<_size;i++) {
        for(int j=i+1;j<_size;j++) {
            swap(&_matrix[i][j],&_matrix[j][i]);
        }
    }
    for(int i=0;i<_size;i++) {
        for(int j=0;j<_size/2;j++) {
            swap(&_matrix[i][j],&_matrix[i][_size-1-j]);
        }
    }
}

main(argc,argv)
const char** argv;
{
    int size=0;
    printf("Enter the size of the square matrix: ");
    scanf("%d",&size);
    int** matrix=allocate(size);
    scanMatrix(matrix,size);
    printMatrix(matrix,size);
    nl();
    rotateMatrix(matrix,size);
    nl();
    printMatrix(matrix,size);
    return 0;
}

This code doesn't use extra memory and also uses run-time allocation using malloc. However, has a time complexity of O(n^2). How do I further optimise it?

has a time complexity of O(n^2).

I think you are incorrectly using "n" as if it is the size of the n×n matrix.

The "n" in O() notation refers to the total size of the input data.

So, for a m×m matrix, the "n" value for complexity would be m2.

Your algorithm is O(n).

  This code doesn't use extra memory

Is there a specific reason for doing the swap trick the way you did rather than simply using the more obvious method with an auto int temp; on the stack?

auto memory is allocated on a stack, so it exists only during the invocation of the function.
After that, it can be reused by other functions.
Unless a function is called recursively, there's no cumulative problem with using temporary stack space; that's what it's for.

And if an algorithm should ever actually require persistent storage, it would be done using static rather than auto.

  This is C using the Original K&R C.

The biggest drawback to using that is that you don't get the benefit of typechecking, which was introduced in C89.

The compiler won't notice any problem with this:

swap(&_matrix[i][j],&_matrix[j][i]);
swap(_matrix[i][j],_matrix[j][i]);
swap("me", "you");

but at runtime things will fail.

I hope you are at least using lint on the source to check for such problems.


What's a better way to decrease cardinality when serializing records I need to transfer data from one vendor's system to another.

The source vendor has a view that generates data that combines invoice and line-item data into records w/ line-item cardinality:

"Invoice","Date","Line","Description","Price"
"A","2/1/2020","1","something","100"
"A","2/1/2020","2","something else","75"
"B","1/1/2020","1","lorem ipsum","25"
"C","12/15/2020","1","foo bar","10.25"
"C","12/15/2020","2","foo bar","99.99"

The data needs to be transmitted, however, as a unit that combines the invoice and its line items:

<I>
  <Invoice>A</Invoice>
  <Date>02/01/20</Date>
  <Items>
    <Item>
      <Line>1</Line>
      <Description>something</Description>
      <Price>100</Price>
    </Item>
    <Item>
     <Line>2</Line>
     <Description>something else</Description>
     <Price>75</Price>
    </Item>
  </Items>
</I>

Towards this end, I've written the following:

# create testing data
function Get-Data
{
    [PSCustomObject]@{
        Invoice = 'A'
        Date='2/1/2020'
        Line=1
        Description = 'something'
        Price = 100.0
    }

    [PSCustomObject]@{
        Invoice = 'A'
        Date='2/1/2020'
        Line=2
        Description = 'something else'
        Price = 75.0
    }

    [PSCustomObject]@{
        Invoice = 'B'
        Date='1/1/2020'
        Line=1
        Description = 'lorem ipsum'
        Price = 25.0
    }
    [PSCustomObject]@{
        Invoice = 'C'
        Date='12/15/2020'
        Line=1
        Description = 'foo bar'
        Price = 10.25
    }
    [PSCustomObject]@{
        Invoice = 'C'
        Date='12/15/2020'
        Line=2
        Description = 'foo bar'
        Price = 99.99
    }

}

# serialize related line items
function ConvertTo-LineItemXml {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [int]$Line,

        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$Description,

        [Parameter(ValueFromPipelineByPropertyName)]
        [decimal]$Price
    )
    begin {}
    process
    {
        $xml += "<Item><Line>$Line</Line><Description>$Description</Description><Price>$Price</Price></Item>"
    }
    end
    {
        $xml
    }
}

# convert data to required Xml message and post
function Send-Invoice {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$Invoice,

        [Parameter(ValueFromPipelineByPropertyName)]
        [datetime]$Date,

        [Parameter(ValueFromPipelineByPropertyName)]
        [pscustomobject]$Items
    )

    begin {}
    process {

        $xml = "<I><Invoice>$Invoice</Invoice><Date>$($Date.ToString('MM/dd/yy'))</Date><Items>"

        $xml += $Items | ForEach-Object {
            $_ | ConvertTo-LineItemXml
        }

        $xml += '</Items></I>'

        Invoke-WebRequest -Method Post -Uri $Uri -Body $xml -ContentType 'application/xml'
    }
    end {}
}

# controller
Get-Data |
    # group by invoice
    Group-Object {$_.Invoice} |
        # for each group
        ForEach-Object {

            # get invoice-specific information from the group's first record
            $i = $_.Group | Select-Object -First 1 Invoice, Date

            # get the line-item-specific information from the group's records
            $li = $_.Group | Select-Object Line, Description, Price

            # assign to property
            $i | Add-Member -MemberType NoteProperty -Name 'Items' -Value $li

            # return structure
            $i

        } |
Send-Invoice # format as xml and post

I should probably move ConvertTo-LineItemXml from within Send-Invoice to allow the caller to have more control over the processing.

What other improvements can I make?

You can use XElement.
It is especially useful when constructing XML.

using namespace System.Xml.Linq
Add-Type -AssemblyName System.Xml.Linq

Get-Data | Group-Object Invoice | ForEach-Object {

    $items = $_.Group | ForEach-Object {
        [XElement]::new('Item', @(
            [XElement]::new('Line', $_.Line)
            [XElement]::new('Description', $_.Description)
            [XElement]::new('Price', $_.Price)))
    }

    $xml = [XElement]::new('I', @(
        [XElement]::new("Invoice", $_.Name)
        [XElement]::new("Date", $_.Group[0].Date)
        [XElement]::new('Items', $items)
    )).ToString()

    $xml
}


Checking ends of a substring I was doing this particular problem AIBOHP and used a dp approach based on checking the ends of a substring of length i starting from 1. Although my time complexity is fine at O(n^2) but space is taking too much because of which I am getting RTE if I am declaring it dynamically or TLE if I am declaring it as global static which needs to be reduced because the dp size can be 6100*6100 . Any suggestions how to optimize my below code for this purpose .

The problem statement is:

  He now asks the doctors to insert the minimum number of characters
  needed to make S a  palindrome. Help the doctors accomplish this task.

  For instance, if S = "fft", the doctors should change the string to
  "tfft", adding only 1 character.

My code:

static int dp[6101][6101];
main()
{
    int tc;
    scanf("%d",&tc);
    while(tc--)
    {
        char s[6102];
        scanf("%s",s);
        int len=strlen(s);
        memset(dp,0,sizeof dp);
        for(int i=1;i<len;i++)
            for(int j=0,k=i;k<len;k++,j++)
                dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;
        printf("%d\n",dp[0][len-1]);
    }
    return 0;
}

Things you did well:

Usage of static.
Using memset() instead of some for loops for initialization of your int[][].

Things you could improve:

User Experience:

You don't indicate to the user that they should enter a number first.

printf("Enter the number of test cases: ");

You don't indicate that the user should enter a string after then enter a number.

printf("Enter test case string: ");

Variables:

I don't expect dp will ever contain negative numbers:

static int dp[6101][6101];

You also don't need the full range of int.  Using a unsigned short will half your memory usage.

static unsigned short dp[6101][6101];

Always initialize your variables when you create them.

int tc = 0;

Readability:

You don't declare what main will return or take in as parameters.

main()

I know that when the type specifier is missing for what you will return, it defaults to an int.  You should still declare it for more readability.  Also, whenever you don't take in any parameters, declare them as void.

int main(void)

Your for loop is hard to follow.

for(int i=1;i<len;i++)
    for(int j=0,k=i;k<len;k++,j++)
        dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;

Braces will help, and will reduce the likelihood of you unintentionally adding bugs in the future.

for(int i=1; i<len; i++)
{
    for(int j=0,k=i; k<len; k++, j++)
    {
        dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;
    }
}

Don't use the ternary operator for longer statements.

dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;

This makes it hard to follow and understand what you are trying to do.  Just use the normal if-else statements.

if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];
else dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;

Use more space in your code.  Let it breathe a bit.  But don't go overboard.
Use more comments to explain your code.

Syntax/Styling:

You have some magic numbers in your code.

static int dp[6101][6101];

With the help of macros, we can easily get rid of them.

#define ARRAYSIZE 6101
static int dp[ARRAYSIZE][ARRAYSIZE];

Don't use the function min().

dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;

min() and max() functions are not included in standard C.  To make things simple for your code, use the standard math function fmin().

dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;

You have an implicit conversion that loses integer precision:

int len=strlen(s);

You aren't converting your unsigned long that strlen() returns to an int.

int len = (int) strlen(s);

Use fgets() instead of scanf().  This way we can specify the maximum number of characters to be copied into our string (including the terminating null-character).

fgets(s, 6101, stdin);

You should always check for superfluous input and get rid of it.

while (getchar() != '\n');

Preprocessor:

Whenever you include functions such as scanf() and printf() that deal with input or output, you need included the standard I/O header.

#include <stdio.h>

Whenever you include functions that deal with strings, there is a good chance you will have to include the string header.

#include <string.h>

Whenever you include math functions, you need to include the math header.

#include <math.h>

Final Code:

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

#define ARRAYSIZE 6101

static unsigned short dp[ARRAYSIZE][ARRAYSIZE];
char s[ARRAYSIZE] = {0};
int main(void)
{
    int tc = 0;
    printf("Enter the number of test cases: ");
    scanf("%d",&tc);
    while (getchar() != '\n');
    while(tc--)
    {
            printf("Enter test case string: ");
        fgets(s, ARRAYSIZE, stdin);
        int len = (int) strlen(s);
        memset(dp, 0, sizeof dp);
        for(int i=1; i<len; i++)
        {
            for(int j=0, k=i; k<len; k++, j++)
            {
                if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];
                else dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;
            }
        }
        printf("%d\n", dp[0][len-1]);
    }
    return 0;
}


Reach to the last index starting at index 0 The task:

  Given an integer list where each number represents the number of hops
  you can make, determine whether you can reach to the last index
  starting at index 0.

  For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns
  false.

My solutions:

// functional:
const reachLastIndexOf = (arr, start) => {
  if (arr[start] === undefined) return false;
  const next = start + arr[start];
  if (start === next || next >= arr.length) return false;
  if (next === arr.length -1) return true;
  return reachLastIndexOf(arr, next);
}
console.log(reachLastIndexOf([2, 0, 1, 0], 0)

// imperative:
const reachLastIndexOf2 = arr => {
  let start = 0;
  while(start < arr.length) { // I'm tempted to write `while(true)` here
    if (arr[start] === undefined) return false;
    const next = start + arr[start];
    if (start === next || next >= arr.length) return false;
    if (next === arr.length - 1) return true;
    start = next;
  }
}
console.log(reachLastIndexOf2([1, 1, 0, 1]));

Default Parameters

When can compare the method signatures of the iterative approach and the functional one, we can see, that for the functional one we have to append the 0 on the first call.

If you want to avoid this - and in this case I think it makes sense - you can add a default parameter into the method signature: const reachLastIndexOf = (arr, start = 0)

Long Condition & Pattern Matching

The condition start === next || next >= arr.length is currently in on if-statement. The ||-operator operates short-circuit - that means if the first operation is true, the compiler don't validates the second condition. When we split the disjuncture into to two if-statements, we can keep the same short-circuit behavior and create a more pattern-matching look and feel:

if (start === next) return false
if (next >= arr.length) return false

The advantage is that you have a less logical operator. The less code, the fewer errors and at the same time the readability is increased.
Please note that I have meant this more generally for conditions, even if in this context only a Boolean operator is avoided, the code is still more readable in my view than before.

Readable Method Names

For this algorithm we need to check if:

an index exists (arr[start] === undefined)
an index stays on the same place (start === next)
an index is out of the array bound (next >= arr.length)
an index reached the end (next === arr.length - 1)

We all now what these checks are meaning but it would be much better if we wrap these into their own functions

const reachLastIndexOf = (arr, start = 0) => {
    if (isIndexDefined(arr, start)) return false;

    const next = start + arr[start];

    if (isStayingInTheSamePosition(start, next)) return false
    if (isOverArrayBound(next, arr)) return false
    if (isReachingTheEnd(next, arr)) return true
    return reachLastIndexOf(arr, next)
}

const reachLastIndexOf = (arr, start = 0) => {
  if (isIndexDefined(arr, start)) return false;

  const next = start + arr[start];

  if (isStayingInTheSamePosition(start, next)) return false
  if (isOverArrayBound(next, arr)) return false
  if (isReachingTheEnd(next, arr)) return true
  return reachLastIndexOf(arr, next)
}

const isIndexDefined = (array, index) => array[index] === undefined
const isStayingInTheSamePosition = (start, next) => start === next
const isOverArrayBound = (next, array) => next >= array.length
const isReachingTheEnd = (next, array) => next === array.length - 1

console.log(reachLastIndexOf([2, 0, 1, 0], 0));


php script to retrieve enum values from sql table I have an sql table with multiple fields and 4 of them are enums. I wrote a script that runs thought the table and retrieve the enums and put them in a 2 dimension array.

Unfortunately this script is extreamly slow and I can't fix it.

<?php

require_once('mySQL_Connect.php');

$con = ConnectToDataBase();
if ($con == false)
{
    //data returned will be null
    exit;
}

$db = 'courses_db';
$table = 'courses';

$fields = array(
'training_field',
'speciality_field',
'type',
'language');

$enums = array();

foreach ($fields as $colomn) {
$sq1 = "SELECT
            column_type
        FROM
            information_schema.columns
        WHERE
            table_schema = '$db'
        AND
            table_name = '$table'
        AND
            column_name = '$colomn'";
$query =  mysqli_query($con,$sq1);

$stack = array();
$i = 0;
$stack[$i]=$colomn;
if ($fetch = mysqli_fetch_assoc($query) )
{
    $enum = $fetch['column_type'];
    $off = strpos($enum,"(");
    $enum = substr($enum, $off+1, strlen($enum)-$off-2);
    $values = explode(",",$enum);

    // For each value in the array, remove the leading and trailing
    // single quotes, convert two single quotes to one. Put the result
    // back in the array in the same form as CodeCharge needs.

    for( $n = 0; $n < Count($values); $n++) {
    $val = substr( $values[$n], 1,strlen($values[$n])-2);
    $val = str_replace("''","'",$val);
    $stack[$i+1]=$val;
    $i++;
    }
}
    // return the values array to the caller
    //echo json_encode( $stack);
    array_push($enums,$stack);
    reset($stack);
}
echo json_encode($enums);
?>

You can use describe queries in mysql to find column types

for example DESCRIBE courses returns the table information including column type


Status Report sending using python I used this script to sending status report to my team lead. It will read the status from the file Readme.md. Here i already wrote my status. if this script execute on target_time or greater than it will execute the mailer function otherwise ask for confirmation

# importing messagebox for confirmation diaglog box
import tkMessageBox
import smtplib

from time import gmtime, strftime

def mail_send():
    target_time = 02
    # By using strftime we only current time in hours, it returns string like
    # "12"
    current_Time = strftime("%H")
    print current_Time

    # convert str to number
    cTime = int(current_Time)

    def sub_mailer():

        print "Mailer loading ...."
        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.starttls()
        s.login('myuser@gmail.com', 'anypass')
        f = open('Readme.md', 'r')
        filedata = f.read()
        subject = "Today Update"
        msg = 'Subject:{}\n\n{}'.format(subject, filedata)
        s.sendmail('myuser@gmail.com', 'teamlead@Gmail.com',
                   msg)
        s.quit()
        f.close()

    # get time using time module
    if target_time <= cTime:
        sub_mailer()
    else:
        status = tkMessageBox.askquestion(
            "Shift hours is not completed. Shall i  send a mail", icon="warning")
        if status == "yes":
            sub_mailer()
        else:
            print "Mail sending process was canceled by user"

First of all, Welcome to CodeReview!

Let's analyse the code to see what could be improved here.

current_Time = strftime("%H")
print current_Time
# convert str to number
cTime = int(current_Time)

A few things could be improved here:

Too many calls! current_Time = int(strftime("%H")) would have sufficed
the comment # convert str to number adds no real value to the code readability

s = smtplib.SMTP('smtp.gmail.com', 587)

Use better names, s does not make it clear what it does.
Avoid "magic" numbers-- it would have been better to have these as named constants

f = open('Readme.md', 'r')

Use context managers (with open ... as ...), see the docs

Some random thoughts

Use guards-- that way your script can be imported by other modules. Might not need it here, but I think it is good practice to always use them.
Consider upgrading your python-2.7 to python-3 and port all your code, since the Python 2 End Of Life is just 2 years away!


Gilbreath's conjecture in Python I've written some code for testing Gilbreath's conjecture in python (2.x). The conjecture was shown (in the 90s) to be true up to n=1012. My code uses the primesieve module to quickly generate primes and, by ignoring blocks of 0s and 2s, only calculates values in the array when necessary. However, it's quite slow; it makes heavy use of dictionary lookup, addition and deletion, and I expect would benefit from modification of this aspect.

def gilbreath(nMax):
    import primesieve
    def fill(D, j, k):
        if (j, k-1) not in D:
            fill(D, j, k-1)
        D[(j, k)] = abs(D[(j+1, k-1)]-D[(j, k-1)])
        # remove unneeded entries
        if (j-1, k) in D:
            del D[(j, k-1)]
        if (j+1, k) in D:
            del D[(j+1, k-1)]
    primes = primesieve.Iterator()
    D = {}
    depthLeft, depth, maxDepth, nDepth = -1, -1, -1, -1
    for n in xrange(1, nMax+1):
        D[(n, 0)] = int(primes.next_prime())
        j, k = n, 0
        while (D[(j, k)] > 2) or (k <= depthLeft):
            if D[(j, k)] > 2:
                depth = k
            j -= 1
            k += 1
            fill(D, j, k)
            if (j == 1) and D[(j, k)] > 1:
                print "conjecture false at n = %d" %n
        depthLeft = depth
        if depth > maxDepth:
            maxDepth, nDepth = depth, n
    print "max depth %d at n = %d of %d" %(maxDepth, nDepth, nMax)

12% speed-up by simplification

Your code as is takes (with input 10**5):

max depth 96 at n = 92717 of 100000
        4027699 function calls (3764972 primitive calls) in 9.303 seconds

I simplified it by removing the:

    if (j-1, k) in D:
        del D[(j, k-1)]
    if (j+1, k) in D:
        del D[(j+1, k-1)]

And it runs in:

max depth 96 at n = 92717 of 100000
         4027699 function calls (3764972 primitive calls) in 8.129 seconds

So it both runs faster and is less code to maintain, a win-win.


Initialize comparison datatable This code doesn't look too good.  Could anyone help me format it?

private void initComparisonDatatable() {
    List<BrandProfitAndLoss> brandProfitAndLossComparisonDatatable = new ArrayList<BrandProfitAndLoss>();
    BrandProfitAndLoss brandProfitAndLossCurrentYear = new BrandProfitAndLoss();
    BrandProfitAndLoss brandProfitAndLossPreviousYear = new BrandProfitAndLoss();
    // if the selected year is null and the previous year is not null
    if(brandActionForm.getBrandProfitLossList().size() <= 0 && brandActionForm.getBrandProfitLossComparisonList().size() > 0){
        for(int i = 0; i < brandActionForm.getBrandProfitLossComparisonList().size(); i++){
            brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
            brandProfitAndLossCurrentYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossComparisonList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
            brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
                                                     , brandProfitAndLossPreviousYear));
        }
    }
    // the selected year is not null
    else {
        for(int i = 0; i < brandActionForm.getBrandProfitLossList().size(); i++){
            brandProfitAndLossCurrentYear = brandActionForm.getBrandProfitLossList().get(i);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
            if(brandActionForm.getBrandProfitLossComparisonList().size() > 0){
                brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
                brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
                brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
                                                    , brandProfitAndLossPreviousYear));
            }
            else {
                brandProfitAndLossPreviousYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
                brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
                brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandActionForm.getBrandProfitLossList().get(i)
                                                    , brandProfitAndLossPreviousYear));
            }
        }
    }
    brandActionForm.setBrandProfitLossComparisonListForDatatable(brandProfitAndLossComparisonDatatable);
}

Some problems that could be seen without actually understanding code:

Unhelpful and possibly misleading comments: // the selected year is not null
Repeating type in variable name : brandProfitAndLossCurrentYear
Using ad hoc code instead of using appropriate library methods: list.size() <= 0 instead of list.isEmpty() and list.size() > 0 instead of !list.isEmpty()
Long method doing more than one thing: initComparisonDatatable retrieve data from form, calculate something based using said data, modify form using calculated data
Feature Envy: Since initComparisonDatatable acts on brandActionForm and uses only data from brandActionForm it belongs to brandActionForm.
Repetitive code: body of the three loops are repeated with minor variations.

There are probable design issues, but those cannot be addressed properly without further clarification. For example new BrandProfitAndLoss().getAllRateComparisonRecords suggests BrandProfitAndLoss has some data access code in it, therefore should be moved elsewhere; it probably is a class method instead of an instance method; and since it is a class method it probably has dependency issues, I can smell an evil singleton from here.

How refactored code could look like, (since loops and conditional statements have been changed these will definitely break something, so do not try to use it in production without proper unit testing):

    private void initComparisonDatatable() {
        List<BrandProfitAndLoss> comparisonDatatable = listForDatatable(
                brandActionForm.getBrandProfitLossComparisonList(),
                brandActionForm.getBrandProfitLossList(),
                brandActionForm.getDateMode());

        brandActionForm.setBrandProfitLossComparisonListForDatatable(comparisonDatatable);
    }

    private static List<BrandProfitAndLoss> listForDatatable(
            List<BrandProfitAndLoss> brandProfitLossComparisonList,
            List<BrandProfitAndLoss> brandProfitLossList, Object dateMode) {
        List<BrandProfitAndLoss> comparisonDatatable = new ArrayList<BrandProfitAndLoss>();

        int prevYearSize = brandProfitLossComparisonList.size();
        int currentYearSize = brandProfitLossList.size();
        int size = Math.max(prevYearSize, currentYearSize);

        for (int i = 0; i < size; i++) {
            BrandProfitAndLoss ofPreviousYear = (i < prevYearSize)
                    ? brandProfitLossComparisonList.get(i)
                    : null;

            BrandProfitAndLoss ofCurrentYear = (i < currentYearSize)
                    ? brandProfitLossList.get(i)
                    : null;

            if (ofPreviousYear == null) {
                ofPreviousYear = new BrandProfitAndLoss(
                        ofCurrentYear.getDate(), dateMode, Consts.CURRENT_YEAR);
            }

            if (ofCurrentYear == null) {
                ofCurrentYear = new BrandProfitAndLoss(
                        ofPreviousYear.getDate(), dateMode, Consts.CURRENT_YEAR);
            }

            comparisonDatatable.add(ofCurrentYear);
            comparisonDatatable.add(ofPreviousYear);
            comparisonDatatable
                    .add(new BrandProfitAndLoss().getAllRateComparisonRecords(
                            ofCurrentYear, ofPreviousYear));
        }

        return comparisonDatatable;
    }


Caesar Cypher in Python What do you think about this code? I'm learning Python and I made this tool to code a plain text or decode it!

inp = input('Input the text you want to code:\n')
inp = inp.lower()

key = int(input('Input the key you want to use from 2 to 25:\n'))
def rot13(input,key): #Function to code a text with caeser chyper.
    if key > 25:
        key = 25
    elif key < 2:
        key = 2
    finaltext = ''
    for letter in input:
        if letter.isalpha():
            num = ord(letter)
            if (num + key) > 122: #If the final number is greater than 122..
                x = (num + key) - 122
                finaltext += chr(x + ord('a') - 1)
            elif((num + key <= 122)):
                finaltext += chr(num + key)
        else:
            finaltext += letter
    print(finaltext)

rot13(inp,key)

I'd say the code is not bad, just a few style issues and a couple of practical things.

You don't need two lines to lowercase the input string, you can do directly
inp = input('Input the text you want to code:\n').lower()

You're not checking user input, if the second input is not an integer, int() will generate a ValueError. You should put a try/catch around that.

Your input implies that numbers lower than 1 and higher than 25 are not acceptable, while actually you're accepting them and doing something different than what you told the user. Either you generate an error and refuse the input, or you say that the input will be modified accordingly. Either way the user should know what's going on.

You have quite a few hard-coded values, consider using constants .

The comment # If the final number is greater than 122.. is useless, the code is clear at that point.

The comment # Function to code a text with caeser chyper. should actually be a docstring . You should also specify what you expect as input and what kind of output you return.

I would rename the variable input to input_string , just so it's not the same name of the input() function.

elif((num + key <= 122)): is actually just else:

You're printing inside of the function. I'd return the value and let the caller decide what to do with it.

You may want to consider putting if __name__ == "__main__": in your code and call your function from there.

This is a simple function, so no need to dig too deep but if you want, you may have a look here about string concatenation .


What should I do to reduce run time of my code? This is a URI online judge problem (problem no: 1973).
Link : https://www.urionlinejudge.com.br/judge/en/problems/view/1973

  After buying many adjacent farms at the west region of Santa Catarina,
  the Star family built a single road which passes by all farms in
  sequence. The first farm of the sequence was named Star 1, the second
  Star 2, and so on. However, the brother who lives in Star 1 has got
  mad and decided to make a Star Trek in order to steal sheep from the
  proprieties of his siblings. But he is definitely crazy. When passes
  by the farm Star i, he steals only one sheep (if there is any) from
  that farm and moves on either to Star i + 1 or Star i - 1, depending
  on whether the number of sheep in Star i was, respectively, odd or
  even. If there is not the Star to which he wants to go, he halts his
  trek. The mad brother starts his Star Trek in Star 1, stealing a sheep
  from his own farm.

  Input

  The first input line consists of a single integer N (1 ≤ N ≤ 10⁶),
  which represents the number of Stars. The second input line consists
  of N integers, such that the ith integer, Xi (1 ≤ Xi ≤ 10⁶),
  represents the initial number of sheep in Star i.

  Output

  Output a line containing two integers, so that the first represents
  the number of Stars attacked by the mad brother and the second
  represents the total number of non-stolen sheep.

Sample Input          Sample Output
8                     8 68
1 3 5 7 11 13 17 19

8                     7 63
1 3 5 7 11 13 16 19

I have solved the problem with two ways and they also give the desired output, but every time I submitted it it says time limit exceeded.

#1st solution:
num_star = int(input())
sheep = list(map(int, input().split()))
star = set()
index = 0

while index != num_star:
    if sheep[index] == 0:
        break
    elif sheep[index] % 2 == 1:
        star.add(index)
        sheep[index] -= 1
        index += 1
    else:
        star.add(index)
        sheep[index] -= 1
        index -= 1
        if index == -1:
            break

print(len(star), sum(sheep))

#2nd solution
n = int(input())
x = list(map(int, input().split()))
i = 0
farm_visited = 0
while i in range(n):
    if x[i] == 0:
        if i >= farm_visited: farm_visited = i+1
        break
    elif (x[i]) % 2 == 1:
        if i >= farm_visited: farm_visited = i + 1
        x[i] -= 1
        i += 1
    else:
        if i >= farm_visited: farm_visited = i + 1
        x[i] -= 1
        i -= 1
print(farm_visited, sum(x))

set in the first solution, and while i in range(n) in the second one are very expensive.

That said, thou shalt not bruteforce.

The crazy guy moves right as long as he visits the odd-populated farms, leaving a trail of even-populated farms behind. As soon as he hits the even-populated farm, he switches direction, and since now on he faces only the even-populated farms, he goes all the way to the Star 1, and the track stops there.

So, find the leftmost even-populated farm. If there is none, the guy would visit all farms, stealing one ship per farm. If there is, its index is the number of farms visited; on the way there, one ship per farm will be stolen, and on the way back another ship per farm will be stolen (except if initially there was just one ship).

This should be enough to keep you going.

As a side note, break in

    if x[i] == 0:
        if i >= farm_visited: farm_visited = i+1
        break

is a bug. An empty farm should not stop him:

  he steals only one sheep (if there is any) from that farm and moves on


Scraping names and images of products from a webpage I've written some code in python to scrape item names, category and the variety of images connected to each item from four different links out of a webpage. The main problem with which i had to hurdle is that each item may have one image or around five different images. Parsing those image links are no big deal but problem appears when it comes to save them in a local folder. Coder like me find it difficult cause few links contain single image and the rest contain several. It was hard for me to twitch the scraper in such a way so that all the images can be parsed and saved properly. I used four different links: two of which contain one image for each item and the rest contain five images for each item . However, my parser is running smoothly now. Here is what I did:

import requests
from lxml import html
import os

urls = [

    "http://www.floralart.com.au/products/39-melbourne-online-floristflorist-melbourne-flowers-delivery-funeral-flowers-free-online.aspx",
    "http://www.floralart.com.au/products/316-amore-mio-vase-arrangement.aspx",
    "http://www.floralart.com.au/products/90-wedding-florist-wedding-flowers-wedding-bouquet-bridal-flowers-flowers-for-weddings-artificial.aspx",
    "http://www.floralart.com.au/products/182-flowers-on-line-flower-bouquets-flower-deliveries-flowers-melbourne-cheap-flower-deliveries-mel.aspx",
]

def opening_link(link):

    response = requests.get(link)
    tree = html.fromstring(response.text)
    cat = tree.cssselect(".breadcrumb a")[1].text.strip()      #category name of the item

    for item in tree.cssselect(".product-details-page"):
        name = item.cssselect("h1.productname")[0].text.strip() if item.cssselect("h1.productname") else ""
        image_link = [img.attrib['src'] for img in item.cssselect(".picture a img")]             #for single image
        image_links = [img_link.attrib['src'] for img_link in item.cssselect(".overview a img") if '.jpeg' in img_link.attrib['src']]      #for list of images
        if image_links:
            saving_images(cat,name,image_links)
        else:
            saving_images(cat,name,image_link)

def saving_images(cat, item_name, item_links):

    for link in item_links:
        response = requests.get(link, stream = True)
        image_name = link.split('/')[-1]

        if response.status_code == 200:
            os.chdir(r"C:\Users\ar\Desktop\mth")
            with open(image_name, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)

    print(item_name, cat)

if __name__ == '__main__':
    for url in urls:
        opening_link(url)

Btw, if there are more than one image in a link then it is not necessary to make use of single image cause the list containing several images also contain the main image.

Code Style
There is a number of common PEP8 style guide violations which you may address:

imports to be properly organized
respect blank lines usage: remove the one in the urls list definition, use two newlines between the function definitions, remove extra blank lines at the beginning of the function bodies
inline comments should be 2 spaces from the right, there should be a single space after the # character
usage of spaces around the operators and in expressions and statements

Other Improvements
You can move some of your if checks from Python to CSS selectors. For instance:
[img_link.attrib['src'] for img_link in item.cssselect(".overview a img") if '.jpeg' in img_link.attrib['src']]

could be replaced with:
[img_link.attrib['src'] for img_link in item.cssselect(".overview a img[src$=jpeg]")]

When image_links is truthy, you send it to saving_images() function, which means that image_link is not used and you just wasted time defining it. How about refactoring it to be:
image_links = [img_link.attrib['src'] for img_link in item.cssselect(".overview a img[src$=jpeg]")]
if image_links:
    saving_images(cat, name, image_links)
else:  # single image
    image_link = [img.attrib['src'] for img in item.cssselect(".picture a img")]
    saving_images(cat, name, image_link)


Document term matrix in Clojure This is my very first foray into Clojure (I'm normally a Python-pushing data-type). I'm trying to create a simple term-document matrix as a vector of vectors, out of a vector of strings.

For those who aren't into textmining, the term-document matrix is a dataset in matrix form where the column names represent every word in a set of documents, each row is a document, and each cell is the number of times a given word appears in a given document.

This is the very first step in what I hope to be a useful text data-cleaning library, as well as a clojure learning project.  After the basics are nailed down, I want to add functionality like n-grams, stemming, removing sparse terms, etc. etc.  My ultimate goals involve performance, so I want to optimize this beginning part within an inch of its life right from the start in order to build on it later.

I'm also trying to minimize dependencies (right now there are none), though I'm willing to use incanter or clojure.core.matrix if there are big performance gains to be gotten thereby.

So obviously I have a long way to go, but here are some questions on this initial step:

Is this "good clojure?"  I tried to stick to sort of basic functional programming practice, composing lots of short functions with discrete behavior and such.  But I'm not yet sure what the norms are otherwise.
How do I optimize this?  The particular parts of the existing code that smell funny to me, performance-wise, are:

terdocmmap: there's gotta be a more efficient way of handling the sorting here than building a bunch of sparse maps then sorting them all.  Ideally I'd like to build them in sorted form from the start somehow.
termdocmatrix: the maps -> sequences -> vectors conversion seems really wasteful; I'd like to come up with a more efficient way.

I'm not worrying about namespace and project structure at this stage.

(require '[clojure.string :as str])
(require '[clojure.walk :as walk])

(defn whitesplit
  "split a vector of string into vector of vectors of strings on whitespace"
  [docs]
  (map #(str/split % #" ") docs))

(defn stringcounts
  "count frequencies of strings in vector of vectors of strings"
  [stringvecs]
  (map frequencies stringvecs))

(defn liststrings
  "list all strings in doc set"
  [stringvecs]
  (distinct
    (apply concat stringvecs)))

(defn makezeroes
  [stringlist]
  (zipmap stringlist (repeat 0)))

(defn expandcounts
  "based on strings in all docs, fill counts with 0 for unused strings in each single doc"
  [zeroes counts]
  (map #(merge-with + % zeroes) counts))

(defn bigmap
  "split vector of docs by spaces then make zero-filled map of counts"
  [docs]
  (let [stringvecs (whitesplit docs)]
    (expandcounts
      (-> stringvecs liststrings makezeroes)
      (-> stringvecs stringcounts))))

(defn terdocmmap
  "make a sorted document-term-map of vector of docs with keywords"
  [docs]
  (walk/keywordize-keys  ; this is mainly for later flexibility
    (map #(into (sorted-map) %) (bigmap docs))))

(defn tdseqs
  "convert document-term-map into sequence of sequences"
  [tdmap]
  (cons
    (keys (first tdmap))
    (map vals tdmap)))

(defn nestvecify
  "sequence of sequences --> vector of vectors"
  [seqofseq]
  (into [] (map #(into [] %) seqofseq)))

(defn termdocmatrix
  "make document term matrix as vector of vectors from vector of docs"
  [docs]
  (-> docs terdocmmap tdseqs nestvecify))

Example input and output:

(termdocmatrix ["this is a cat" "this is a dog" "woof and a meow" "woof woof woof meow meow words"])

Produces:

[[:cat :is :this :words :dog :and :meow :woof :a] [1 1 1 0 0 0 0 0 1] [0 1 1 0 1 0 0 0 1] [0 0 0 0 0 1 1 1 1] [0 0 0 1 0 0 2 3 0]]

I'm pretty new at Clojure myself, and haven't studied the collection algorithms very much yet, so this may not address your performance concerns, but I did find a few things that could be improved.

Potential problem with "real" document input
As I started going through your functions and how they work together, I noticed that your logic makes the assumption that all input will always just be words separated by spaces. Perhaps your data set is already preprocessed before it enters your termdocmatrix function? Unless that is the case, any text from actual documents written by humans will have many artifacts like punctuation marks and such that you should probably account for.
I ran these to illustrate what happens with more "natural" document text:

(def docs-punc ["this is, a cat" "this is a dog." "woof: and a meow" "woof; woof woof! meow? meow words"])
(whitesplit docs-punc)
; => ([this is, a cat] [this is a dog.] [woof: and a meow] [woof; woof woof! meow? meow words])
(termdocmatrix docs-punc)
; => [[:cat :dog. :is :this :woof: :is, :words :meow? :woof! :and :meow :woof; :woof :a] [1 0 0 1 0 1 0 0 0 0 0 0 0 1] [0 1 1 1 0 0 0 0 0 0 0 0 0 1] [0 0 0 0 1 0 0 0 0 1 1 0 0 1] [0 0 0 0 0 0 1 1 1 0 1 1 1 0]]

That totally messed up the results as you can see. I added a strip-punc function at the top (I made punc-to-remove its own form for readability, personal preference), and a helper function to apply it to a vector of strings:
(defn strip-punc
  "remove punctuation marks in string using `punc-to-remove` capture pattern and replacing them with empty string"
  [str]
  (def punc-to-remove #"[.,;:!?$%&\*()]")
  (str/replace str punc-to-remove ""))

(defn vec-strip-punc
  "applies strip-punc to a vector of strings"
  [vec]
  (map #(strip-punc %) vec))

Then change your bigmap function accordingly to call it before you split the strings:
  (let [docs-no-punc (vec-strip-punc docs)
        stringvecs (whitesplit docs-no-punc)] ; etc.

Or alternatively inline style:
(let [stringvecs (whitesplit (vec-strip-punc docs))]

This will take care of pretty much all your general punctuation cases, and you can easily tweak the regex pattern as needed:

(def docs-punc ["this is, a cat%" "this $is a dog." "woof: and [a] meow*" "woof; (woof woof!) meow? meow words"])
(termdocmatrix docs-punc)
; => [[:cat :is :this :words :dog :and :meow :woof :a] [1 1 1 0 0 0 0 0 1] [0 1 1 0 1 0 0 0 1] [0 0 0 0 0 1 1 1 1] [0 0 0 1 0 0 2 3 0]]

Naming
Your names don't follow typical Lisp naming convention. According to Wikipedia on naming conventions (programming):

Common practice in most Lisp dialects is to use dashes to separate words in identifiers, as in with-open-file and make-hash-table. Global variable names conventionally start and end with asterisks: *map-walls*. Constants names are marked by plus signs: +map-size+.

Also since most/all your functions actually transform your data structure, I would suggest naming them in a way that suggests that. Perhaps also using an acronym consistently, let's say td (or even TD) for term-document, that would make it read better without being really verbose.
termdocmatrix -> TD-matrix-from-docs
terdocmmap -> TD-map-from-docs
tdseqs -> TD-seqs-from-TD-map

bigmap I don't think is a descriptive name. What is "big" in this context? In truth it reminds me of a Cartesian product, since each document entry in the docs vector will return its own map of all possible words, e.g., {this 1, is 1, a 1, cat 1, dog 0, woof 0, and 0, meow 0, words 0}. I would be tempted to call it something like cartesian-product-map or perhaps just cartesian-map.
I would also suggest to perhaps change whitesplit to space-split, since that is really what it is doing (it is not splitting other whitespace like \r \n \t. Or if you want to make it a true whitespace-split, then you should change #" " to the #"\s" special character which includes "all whitespace". Here is an article on RegexOne about it.