texts:
Task:  Perform Breadth first traversal on a Binary Search Tree and print the elements traversed.

class Node(object):
    def __init__(self, value,left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class BinarySearchTree(object):
    def __init__(self, value):
        self.root = Node(value)

    def insert(self, value):
        current = self.root
        while current:
            if value > current.value:
                if current.right is None:
                    current.right = Node(value)
                    break
                else:
                    current = current.right
            else:
                if current.left is None:
                    current.left = Node(value)
                    break
                else:
                    current = current.left

    def Breadth_first_search(self,root):
        """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

        visited = []
        if root:
            visited.append(root)
            print root.value
        current = root
        while current :
            if current.left:
                print current.left.value
                visited.append(current.left)
            if current.right:
                print current.right.value
                visited.append(current.right)
            visited.pop(0)
            if not visited:
                break
            current = visited[0]

t = BinarySearchTree(100)
t.insert(12)
t.insert(92)
t.insert(112)
t.insert(123)
t.insert(2)
t.insert(11)
t.insert(52)
t.insert(3)
t.insert(66)
t.insert(10)

print "Output of Breadth First search is "
t.Breadth_first_search(t.root)

The code runs acceptably and gives the correct output. Is there better solution to this problem?


texts: applyFilters - function which take array of items and array of excludes and return filtered by excludes array of items

texts:
I wrote some function which should take an array of items:Array<Object> and array of excludes:Array<Object> with keys which values can't be present in items. and should return an array of filtered items.

Is there some way to improve it? Is complexity of that function equal O(n + k)?

const items = [
  { type: 'phone', name: 'iPhone', color: 'red' },
  { type: 'laptop', name: 'Chromebook', color: 'gray' },
  // 15,000 items
];

const excludes = [
  { k: 'color', v: 'gold' },
  { k: 'type', v: 'laptop' },
  // 1,000 items
];

const applyFilters = (items, excludes) => {
  const newExcludes = excludes.reduce((acc, curr) => {
    if (!acc[curr.k])
      acc[curr.k] = new Set();

    acc[curr.k].add(curr.v);

    return acc;
  }, {});

  return items.reduce((acc, curr) => {
    for (let key in curr) {
      if (newExcludes[key] && newExcludes[key].has(curr[key]))
        return acc;
    }

    return [...acc, curr];
  }, []);
};

console.log(applyFilters(items, excludes));


texts: Shell script for reading /etc/passwd into SQLite

texts:
I want to read 4 columns, namely UID, GID, username and home directory of specific users from /etc/passwd into an SQLite database. I found this to create many subprocesses, and I'd like to have some improvement suggestions.

#!/bin/sh
db="$PWD/users.db"
users=$(grep -E 'joe|bill|tom' /etc/passwd)
sqlite3 "$db" <<EOF
DROP TABLE Users;
CREATE TABLE Users \
    (UID INTEGER PRIMARY KEY, GID INTEGER, Username TEXT, Home TEXT);
EOF
echo "$users" | while IFS= read -r line
do
    sqlite3 "$db" \
        "INSERT INTO Users VALUES ( \
         $(echo "$line" | cut -d":" -f3),   \
         $(echo "$line" | cut -d":" -f4),   \
        '$(echo "$line" | cut -d":" -f1)',  \
        '$(echo "$line" | cut -d":" -f6)');"
done


texts: Using postMessage() in JavaScript with iframes for cross domain communication

texts:
I am trying to enable communication via JavaScript from an iframe and its parent window when they are on different domains. I did a lot of research and it turned out that postMessage() is a good approach if used correctly. I have read the vast resources about how to use it to make sure it’s implemented in a secure way and came up with the code. However, as I am still new to coding, I am paranoiac about XSS vulnerabilities and this code looks too simple to me to be fully secure. I would appreciate if someone can review it.

Context:

The message must be sent from the iframe to the parent window only
The iframe is HTTPS, while the parent is HTTP
The message doesn’t contain sensitive data – it’s just a simple indicator for the parent window to do trigger a google tag manager custom event
Parent window domain in the example is: http://my-main-web.com
Iframe domain in the example is: https://my-iframe-web.com

Questions:

Is the code exposed to security risks?
Are there other risks apart that the attacker might find out the message content is 'download'? For example, can meticulous code be injected through the message?

Sender (iframe):

<script type="text/javascript">
  parent.postMessage("download occurred", "http://my-main-web.com");
</script>

Receiver (parent window):

<script type="text/javascript">
  function receiveMessage(event) {
    if(event.origin !== “https://my-iframe-web.com”) return; // validate origin

    if (event.data !== "download occurred") return; // validate message content
      console.log(“msg received”);
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        'event': 'download' // create custom GTM event
      });
    };

  window.addEventListener("message", receiveMessage, false);
</script>


texts: Two script completing the same task, which is the best way?

texts:
I have the following two methods of completing the same task, however I'd like to know which is the preferred method and WHY? Or if there are any suggestions to complete the task in an even better, cleaner way.

The task

Find part 1 of $string in the example $string = '1/2/3/4'; so the first part would be '1'.

Match that value to the corresponding 'id' from entries in the database, then return the 'filename' that corresponds to the 'id'.

Then loop again until each part of the initial string has a corresponding value.

The 'filename' values are each then output to a string delimited by a '/'.

EG. filename1/filename2/filename3/filename4

Option 1

$string = '1/2/3/4';

$change = str_replace('/',',',$string);

$result = $connection->query("SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD($change)");

while($row = $result->fetch_assoc()) {
    $match[] = $row;
}

foreach ($match as $array) {
    echo $array['filename'].'/';
}

UPDATE
This works fine if there are more than one parts to the string eg. '1/2/3/4' but I get the following error if just '1' is used.

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\admin\pages\test2.php on line 22

OR

Option 2

$string = '1/2/3/4';

$split = explode('/', $string);

$split = array_flip($split);

$result = $connection->query("SELECT id, filename FROM pages");

while ($row = $result->fetch_assoc()) {
    $new_array[$row['id']] = $row['filename'];
}

$matched = array_intersect_key($new_array, $split);

$join = implode('/', $matched); // join $matched as string.

echo $join;


texts:
I have the following method:

private void removeUnnecessaryLines(List<ScatterViewItem> list)
{
    List<Line> remove = new List<Line>();
    foreach (Line line in lines)
    {
        SourceFile destination = (line.Tag as Call).getCallee();

        foreach (ScatterViewItem svi in list)
        {
            SourceFile test = svi.Tag as SourceFile;
            if (test.Equals(destination))
            {
                remove.Add(line);
            }
        }
    }

    foreach (Line l in remove)
    {
        lines.Remove(l);
        Dependencies.Children.Remove(l);
    }
}

As you can see, there is a lot of iteration and casting. Is there a simple way to improve that?


texts:
My code is working fine to save a file with FileChoser. But how can I make it accurate and perfect when a user doesn't select an absolute path for a file and closes it abruptly?

public class HTMLtoPDF {

    @SuppressWarnings("deprecation")
    public void convertHtmlToPdf() {
        try {

            FileChooser fileChooser = new FileChooser();
            // Set extension filter
            FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF File (*.pdf)", "*.pdf");
            fileChooser.getExtensionFilters().add(extFilter);
            // Show save file dialog
            //The stage for show dialouge is get from MainClass stage
            File file = fileChooser.showSaveDialog(MainClass.getStage());

            Client client = new Client("XXXXXX", "XXXXXXXX");
            FileOutputStream fileStream = new FileOutputStream(file);

            String currentUrl = TabController.getWebEngine().getLocation().toString();
            client.convertURI(currentUrl, fileStream);

            fileStream.close();

            //
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


texts: Implementation of the Jacobi Symbol in C

texts:
I am new to C programming and wrote the following algorithm for the calculation of the Jacobi Symbol. Though there are some faster versions of this algorithm available I am only looking for some feedback on my coding style. I should mention that I was taught to ONLY USE ONE return statement in functions and NOT to use things like break, continue or go-to. This is a "philosophy" I also believe in.

How could I improve?
Is anything unclearly formulated?

One point I could think of would be to use "long long" instead of only "long" since this algorithm is used in cryptography and should thus be suited for very large integers.

Any kind of feedback would be welcome.

EDIT: There is still a (commented) print statement in this code that helps to visualize the algorithm.

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

/*
+*****************************************************************************

* Function Name:    jacobi

* Function:         Calculate the Jacobi Symbol

* Arguments:        a   =   numerator
                    n   =   denominator

* Return:           (a|n)

* Notes:            This function evaluates the Jacobi Symbol for two integers
                    a and n. It is based on the same idea as the Euclidean
                    alogrithm for the gcd. The bit complexity is O(log^2(p)).

-****************************************************************************/

short jacobi(long a, long n)
{
    // The two if-conditions below terminate the function in case of wrong inputs, i.e.: n < 3  or 2 | n.
    if (n<3) {
        printf("Wrong input for the Jacobi Symbol: The denominator has to be greater than 2.\n");
        exit(0);
    }
    if (n%2 == 0) {
        printf("Wrong input for the Jacobi Symbol: The denominator has to be coprime to 2.\n");
        exit(0);
    }
    long n_mod8 = 0;
    short result = 1;
    short condition = 1;
    while (condition == 1) {
        // printf("(%d|%d) and result = %d \n", a, n, result);
        a = a % n;
        // The The if-condition below utilises the fact that (0|n) = 0.
        if (a == 0) {
            condition = 0;
            result = 0;
        } else {
            // The while-loop below utilises the Second Supplement
            // to extract the 2’s out of a.
            while (a % 2 == 0) {
                a = a / 2;
                n_mod8 = n % 8;
                if (n_mod8 == 3 || n_mod8 == 5) {
                    result = -result;
                }
            }
            // The if-condition below utilises the fact (1|n) = 1.
            if ( a == 1) {
                condition = 0;
            } else {
                // This else-condition utilises the Law of
                // Quadratic Reciprocity to transfer (a|n) to (n|a).
                long tmp = a;
                a = n;
                n = tmp;
                if (a % 4 == 3  &&  n % 4 == 3) {
                    result = -result;
                }
            }
        }
    }
    return result;
}

int main()
{
    printf("%d", jacobi(4852777,12408107));
    return 0;
}

```


texts: Project Euler #14 - Longest Collatz sequence

texts:
I'm attempting some Project Euler problems in an attempt to learn Python.  While I can get the correct answer quite easily, my programs are quite slow. Project Euler, if doing it correctly, specifies that each program should run in <1 minute. Some of mine take 5-10 mins.

Here is one example.

x=1;
terms=0;
maxTerms=0;
maxTermsNum=0;
for x in range(1,1000000):
    i=x;
    while (i!=1):
        terms+=1;
        if (i%2==0):
            i/=2
        else:
            i=3*i+1
    if (terms>maxTerms):
        maxTerms=terms;
        maxTermsNum=x;
        print(x);
    terms=0;
print("Biggest one: is %s." %maxTermsNum)

It produces the correct answer, but it takes a long long time. How can I speed this up?  This is also in 32-bit Windows.


texts: Iterate over a short list, pairing the elements with the sequential elements of a longer list

texts:
I am a relatively new programmer. I am trying to use iter and cycle to cycle over a list (key) and 'pair' each item with each consecutive item in the second list (message). The code below works as expected, producing the desired pairs and stopping when it is done. It does not, however, execute that last print statement ('Okay, it worked!') because it hits 'StopIteration' instead.

I can see some kludgy ways to get around this, but how can I more neatly "handle" the StopIteration and have the code "continue"?

key = [3, 1, 20]
message = ['a', 'b', 'c', 'd', 'e', 'f']

print(key)
print(message)
print('\n')

# Try making a for loop that cycles through the key and iterates
# over the message
m = iter(message)
for k in cycle(key):
    print(f'{k}:{next(m)}')
print('Okay, it worked!')
```


texts: Concise code to perform action on every element, when need index

texts:
When I read this answer, which has code:

linqObject.Where((obj, index) => {
  DoWork(obj, index);
  return true;
}).ToArray(); //MUST CALL ToArray() or ToList() or something to execute the lazy query, or the loop won't actually execute

My initial reaction was similar to Mark Sowul's comment:

  "Wastes memory (allocating a list or array) and risks bugs (if you don't call ToList or ToArray). Why?".

But on further thought, what is a concise approach, avoiding the downsides of the above?
My first attempt:

int index = 0;
foreach (var item in someEnumerable) {
    DoWork(item, index);
    index++;
}

Compared to calling a Linq operator, that seems verbose, low-level. I'm defining and manipulating an index, whereas Linq has an Operator that "almost" does what I want - takes care of the index tracking for me.

Personally, I would write the explicit foreach loop - but maybe that is only because I've been programming a long time, and am comfortable with that syntax.

Is there a more concise solution, that doesn't have the downsides of the first version shown (Where / ToArray)?

I'm trying to get comfortable with encapsulating such stuff into methods, often by using Action<> or Func<>, which are newer [to me] than the style of programming that became my habit. So that instead of repeating similar snippets of code, I just call a method.

  As an aside, Linq is also newer than my habits. Linq is concise, but not in a way that I find helpful; I find loops clearer to read; a better separation of the aspects of what is happening. But I'm open to seeing situations where its expressive power is appropriate.
  [OFF-TOPIC: In contrast, I spent some time with F#, and found it to be fantastic. I LOVE the combination of functional with OO; just not the way Linq jams a handful of functional constructs into C#'s syntax. But this question is about making good use of C#, so all advice is appreciated.]

I think this becomes:

public static void ForEachWithIndex<T>(IEnumerable<T> e, Action<int, T> a)
{
    int index = 0;
    foreach (T v in e) {
        a(index, v);
        index++;
    }
}

which might be used like this:

ForEachWithIndex(e, (int index, T item) => {
    // Do Work based on index and item.
});

Or if an appropriate "DoWork" method already exists, simply:

ForEachWithIndex(e, DoWork);

Comments?  Improvements, or alternatives?
Is there a way to use Linq more concisely/efficiently than in the original code sample?

NOTE: I did not make this an "extension method" on "IEnumerable", due to comments people made in stackoverflow threads regarding "ForEach" as a possible extension method: dislike of a syntax that looks similar to a Linq operator - which traditionally don't have side-effects - for a method that clearly DOES have side-effects; indeed is all about the side-effects.


texts: Self Running iterable state machine with Enums in Java

texts:
During development I needed to design a state machine with decision which runs to completion and performs state transition without the need to wait for events. So i come up with the following implementation that I want to share.
So the state machine is described with the following Enum
public enum PnoBarringState {
  OPERATOR_WHITE_LIST_START {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        if (commonMethods.isMatchingOperatorsWhiteList(sessionData, pnoValue)) {
            return GROUP_WHITE_LIST;
        } else {
            return OPERATOR_BLACK_LIST;
        }
    }
  },
  GROUP_WHITE_LIST {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        if (commonMethods.isMatchingGroupsWhiteList(sessionData, pnoValue)) {
            return PNO_CHECK_FINISHED;
        } else {
            return GROUP_BLACK_LIST;
        }
    }
  },
  OPERATOR_BLACK_LIST {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        if (commonMethods.isMatchingOperatorsBlackList(sessionData, pnoValue)) {
            return PNO_FORBIDDEN_NUMBER_OPERATOR_LEVEL;
        } else {
            return GROUP_WHITE_LIST;
        }
    }
  },
  GROUP_BLACK_LIST {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        if (commonMethods.isMatchingGroupsBlackList(sessionData, pnoValue))
            return PNO_FORBIDDEN_NUMBER_GROUP_LEVEL;
        else {
            return PNO_CHECK_FINISHED;
        }
    }
  },
  PNO_CHECK_FINISHED {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        return this;
    }

    @Override
    public boolean hasNext() {
        return false;
    }
  },
  PNO_FORBIDDEN_NUMBER_OPERATOR_LEVEL {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        throw new CustomUncheckedException( "Operator Level Barring");
    }
  },
  PNO_FORBIDDEN_NUMBER_GROUP_LEVEL {
    @Override
    public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
        throw new CustomUncheckedException("Group Level Barring");
    }
  };

  public abstract PnoBarringState nextState(SessionData sessionData, String pnoValue);

  public boolean hasNext() { return true; }
}

Function "nextState()" is abstract and implemented in each state in order to examine the transition and return to a new state. Only the "END" state is returning to the same state.
Since it is also desinged to be used in a run-to-completation a "hasNext()" function is provided. The "END" state is overwritting so as to declare the finish of the state-machine.
This enum is then used inside a normal application code with the following way.
PnoBarringState pnoBarringState = PnoBarringState.OPERATOR_WHITE_LIST_START;

while (pnoBarringState.hasNext()) {
    pnoBarringState = pnoBarringState.nextState(sessionData, pnoValue);
}

I am not sure whether any pattern describes it in the same way but i was feeling like sharing it.
Any other approaches are considered valuable.


texts: Converting string to dict using Python ast library

texts:
I have been trying to convert a string of dictionary objects as given below

"{'Cmd': None, 'Hostname': None, 'Entrypoint': None, 'Env': None,     'OpenStdin': False,
'Tty': False, 'Domainname': None, 'Image': u'nginx:latest', 'HostConfig':
{'Binds': None, 'RestartPolicy': {}, 'NetworkMode': u'bridge', 'Dns': None,
'Links': [], 'PortBindings': {}, 'DnsSearch': None, 'Privileged': False,
'VolumesFrom': []}, 'ExposedPorts': {}, 'User': None}"

to python dictionary.

But the solutions came up while searching were suggesting to use python ast library for the purpose. as

import ast
ast.literal_eval(string)

And it works fine. But is ast library is built indented to solve problems like this ? Is there any good approach other than this to solve the problem ?


texts: Socket connect realization: gethostbyname or getnameinfo

texts:
for now I'm using:

int connect(const String& address, int port) {
    struct sockaddr_in servAddr;
    struct hostent* host;            /* Structure containing host information */
    /* open socket */
    if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        return ERROR;
    //TODO: gethostbyname is obsolete.
    if((host = (struct hostent*) gethostbyname(address)) == 0)
        return ERROR;
    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family      = AF_INET;
    servAddr.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*)(host -> h_addr_list[0])));
    servAddr.sin_port        = htons(port);
    if(::connect(handle, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
        return ERROR;
    return OK;
    }

this procedure but everytime I compile it I'm getting:

socket.cpp:(.text+0x374): warning: gethostbyname is obsolescent, use getnameinfo() instead.

getname info is still being confusing stuff for me. here is my try to implement it:

struct sockaddr_in servAddr;
struct hostent *host;        /* Structure containing host information */

/* open socket */
if ((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    return ERROR;

memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family      = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(address.ptr());
servAddr.sin_port        = htons(port);

char servInfo[NI_MAXSERV];
if ( ( host = (hostent*) getnameinfo(
                 (struct sockaddr *) &servAddr
                 ,sizeof (struct sockaddr)
                 ,address.ptr(), address.size()
                 ,servInfo, NI_MAXSERV
                 ,NI_NUMERICHOST | NI_NUMERICSERV )  ) == 0)
    return ERROR;

if (::connect(handle, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
    return ERROR;

-- yes this doesn't work :(

Maybe I should use getaddrinfo instead?

getaddrinfo(hostname, NULL, &hints, &res) - can I use it alike gethostbyname? but where is host actually here? hints?

Working recode based on answer:

int Socket::connect(const String& address, int port) {
    struct sockaddr_in servAddr;
    /* open socket */
    if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        return ERROR;
    //gethostbyname by getaddrinfo replacement
    addrinfo hints = {sizeof(addrinfo)};
    hints.ai_flags = AI_ALL;
    hints.ai_family = PF_INET;
    hints.ai_protocol = 4; //IPPROTO_IPV4
    addrinfo* pResult = NULL;
    int errcode = getaddrinfo(address, NULL, &hints, &pResult);
    if(errcode != 0)
        return ERROR;
    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family      = AF_INET;
    servAddr.sin_addr.s_addr = *((uint32_t*) & (((sockaddr_in*)pResult->ai_addr)->sin_addr));
    servAddr.sin_port        = htons(port);
    if(::connect(handle, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
        return ERROR;
    return OK;
    }


texts: Using static for class default properties

texts:
I have made a class for generating html form elements:

class input
{
  public $tag = 'input', $type = 'text', $customClass, $name;

  public function __construct(array $cfg){
    if ( isset($cfg['name']) ){
      if ( isset($cfg['tag']){
        $this->tag = strtolower($cfg['tag']);
      }
      if ( $this->tag === 'input' && isset($cfg['type']){
        $this->type = $cfg['type'];
      }
      if ( isset($cfg['customClass']){
        $this->customClass= $cfg['customClass'];
      }
      //etc...
    }
  }
}

I would like to be able to set a custom default config for all my fields - without changing the class. For example I want all the fields in a given script to have 'myClass' as customClass. For me, the solution would be to make these default values static, and make a function to change them like this:

class input
{
  static $tag = 'input', $type = 'text', $customClass, $name;

  public static function setDefault(array $cfg){
    if ( isset($cfg['tag']) ){
      self::tag = strtolower($cfg['tag']);
    }
    if ( isset($cfg['type']) ){
      self::type = $cfg['type'];
    }
    if ( isset($cfg['customClass']) ){
      self::customClass= $cfg['customClass'];
    }
    //etc...
  }

  public function __construct(array $cfg){
    if ( isset($cfg['name']) ){
      $this->tag = isset($cfg['tag']) ? strtolower($cfg['tag']) : self::tag;
      $this->type = isset($cfg['type']) ? strtolower($cfg['type']) : self::type;
      $this->customClass = isset($cfg['customClass']) ? $cfg['customClass'] : self::customClass;
      //etc...
    }
  }
}

The problem is that I read everywhere - and particulary here - that static are evil. What other solution would be suitable in the present case? Or can someone tell me "yeah, that's the perfect case to use statics!"? :)


texts: Generating Ulam numbers with OpenMP and single-thread versions

texts:
I'm making a program that takes an integer n and generates the first n Ulam numbers. I followed this guide about OpenMP.

This is the core function, single thread version:

bool isulam (int n, int size) {
    int count = 0;
    for (int i = 0; i < size; i++)
        for (int j = 0; j < size; j++) {
            if (i != j && ulam[i]+ulam[j] == n) count++;
            if (count > 2) return false;
        }
    return count;
}

And this is my attempt at optimizing it with OpenMP:

bool isulam (int n, int size) {
    int count = 0;
    bool toomany = false;
    for (int i = 0; i < size; i++)
        #pragma omp parallel for reduction (|:toomany)
        for (int j = 0; j < size; j++) {
            if (i != j && ulam[i]+ulam[j] == n) count++;
            if (count > 2) toomany = true;
        }
    if (count > 2) return false;
    return count;
}

I'm compiling with g++ -Ofast -fopenmp. The output is correct, but the OpenMP version is much slower:

$ time ompulam <<< 1000 > /dev/null

real  0m22.211s
user  0m39.697s
sys   0m3.202s
$ time ulam <<< 1000 > /dev/null

real  0m7.073s
user  0m7.017s
sys   0m0.008s

What's happening? My CPU is an AMD E1 2500 (2 cores, 1400Mhz) which may not be the best, but I was hoping for a much different result. Is OpenMP only worth on 4+ cores?

FWIW with a regular #pragma omp parallel for (thus without the toomany), the code is running in 18.583s.


texts:
The task
is taken from leetcode

  There are two sorted arrays nums1 and nums2 of size m and n
  respectively.

  Find the median of the two sorted arrays. The overall run time
  complexity should be O(log (m+n)).

  You may assume nums1 and nums2 cannot be both empty.

  Example 1:

  nums1 = [1, 3]

  nums2 = [2]

  The median is 2.0

  Example 2:

  nums1 = [1, 2]

  nums2 = [3, 4]

  The median is (2 + 3)/2 = 2.5

My solution

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
  let i1 = i2 = 0;
  let smallest, valBefore;
  const pivot = Math.floor((nums1.length + nums2.length) / 2);

  while (nums1[i1] || nums2[i2]) {
    smallest = (nums2[i2] === void 0 || nums1[i1] < nums2[i2])
      ? nums1[i1++]
      : nums2[i2++];

    if ((nums1.length + nums2.length) % 2) {
      if (pivot === i1 + i2 - 1) {
        return smallest;
      }
    } else {
      if (pivot - 1 === i1 + i2 - 1) {
        valBefore = smallest
      }
      if (pivot === i1 + i2 - 1) {
        return (smallest + valBefore) / 2;
      }
    }
  }
};

This is the first idea that I had and it reached 99th percentile. I guess you can't take this evaluation seriously. And I'm sure there's a better solution.


texts: Looping through multiple regex efficiently

texts:
I'm writing a program that adds all network interfaces with multiple parameters to a list.

I have written the following code, which should work out of the box on any Linux system with Python and ethtool installed:

import imp
import os
import subprocess
import re
from enum import Enum

class interface_type(Enum):

    OPTIC = 1
    TWISTED_PAIR = 2

class NetworkInterface:

    def set_indentifier(self, id):
        self.id = id

    def set_mac_address(self, mac):
        self.mac = mac

    def set_interface_type(self, interface_type):
        self.interface_type = interface_type

def findNetworkInterfaces(ignoredInterface):

    filteredList = netifaces.interfaces()
    network_interfaces = []

    for interface in filteredList:
        for regex in ignoredInterface:
            if re.search(regex, interface):
                break
            else:
                nwi = NetworkInterface()
                nwi.set_indentifier(interface)
                nwi.set_mac_address(setMAC(interface))
                nwi.set_interface_type(setInterfaceType(interface))
                network_interfaces.append(nwi)
                filteredList.remove(interface)
                break
    return network_interfaces

def setMAC(identifier):

    addrs = netifaces.ifaddresses(identifier)
    mac_address = addrs[netifaces.AF_LINK][0].get("addr")

    return mac_address

def setInterfaceType(identifier):

    bashCommand1 = "ethtool " + identifier
    bashCommand2 = "grep ports"

    try:
        process1 = subprocess.Popen(bashCommand1.split(),
            stdout=subprocess.PIPE)
        process2 = subprocess.Popen(bashCommand2.split(),
            stdin=process1.stdout, stdout=subprocess.PIPE)
        output, error = process2.communicate()

    except:
        print ("Error determining interface type: " + error + "\n")
        print ("Interface will be treated as Optical \n")

    if "TP" in output:
        return interface_type.TWISTED_PAIR
    else:
        return interface_type.OPTIC

if __name__ == "__main__":

    ignored_interface = ["lo", "wlp2s0"]

    try:
        imp.find_module("netifaces")
        netifaces_status = True
        import netifaces

    except ImportError as e:
        print ("netifaces not found: " + str(e))
        os.sys.exit(-1)

    network_identifiers = findNetworkInterfaces(ignored_interface)

    #print network_identifiers

    for iface in network_identifiers:
        print iface.id
        print iface.mac
        print iface.interface_type

I'm mainly concerned with the findNetworkInterfaces function, as I feel I'm doing this in a very ineffecient way (basically copying the list and removing interfaces as to not have doubles). In this special case, I'm not concerned with PEP8 - this is something I'll do later. Any other suggestions to improve the code are very welcome.


texts:
This code downloads a list of images, each in a different thread.

I have some questions about this code:

I don't know how to get information about correcting downloading (sometimes thread just stopped and doesn't do anything: no error, nothing and only part of image has been downloaded). I use the next mechanism for fixing: I wait some time and if thread is alive, I write this image on need_reload file. Is there a better solution?
Is it good or bad this using of threads for this task?
Are parts of my code not "pythonic"?

import os
from threading import Thread
import urllib
import requests

def write_to_failed_image_urls_file(file_name, image_url, failed_image_urls_file):
    """
    Check image in file and write it if need
    :param file_name: image file name
    :param image_url: image URL
    :param failed_image_urls_file: name of file with fails
    :return: None
    """
    with open(failed_image_urls_file, 'a+') as need_reload:
        need_reload.seek(0)
        lines = need_reload.readlines()
        founded = False
        for line in lines:
            if line.startswith(image_url):
                print('File is here')
                founded = True
                break
        if not founded:
            need_reload.write(image_url + "," + file_name + '\n')

def write_response_to_file(response, file_name):
    with open(file_name, 'wb') as f:
        for chunk in response.iter_content(chunk_size=2048):
            f.write(chunk)

def load_image_chunk(image_url, file_name, dir_):
    """
    Loading image by URL
    :param image_url: URL of image
    :param file_name: destination file name
    :param dir_: destination directory
    :return: None
    """
    r = requests.get(image_url, stream=True)
    if r.status_code == requests.codes.ok:
        try:
            write_response_to_file(r, file_name)
        except OSError as err_:
            print(err_.__str__(), 'try redownload...')
            file_name = os.path.join(dir_, file_name.split('=')[-1] + '.jpg')
            write_response_to_file(r, file_name)
    else:
        print(r)

def load_images(image_url_list, dir_, failed_image_urls_file, delay=5):
    """
    loading list of images
    :param image_url_list: list of image urls
    :param dir_: destination dir
    :param failed_image_urls_file: name of file with unsuccessful urls
    :param delay: delay for thread
    :return:None
    """
    abs_failed_image_urls_file = os.path.join(dir_, failed_image_urls_file)
    if not os.path.exists(abs_failed_image_urls_file):
        with open(abs_failed_image_urls_file, 'w') as _:
            pass
    for image in image_url_list:
        f = os.path.join(dir_, image.split('/')[-1])
        t = Thread(target=load_image_chunk, args=(image, f, dir_))
        t.start()
        t.join(delay)
        if t.isAlive():
            print('Bad, bad thread!')
            if abs_failed_image_urls_file is not None:
                write_to_failed_image_urls_file(f, image, abs_failed_image_urls_file)


texts: Finding all non-empty directories and their files on an SFTP server with Paramiko

texts:
The purpose of the following function is to find all non-empty directories, and the files in those non-empty directories. It recursively checks each directory on an SFTP server to see if it has any files, and if it does, adds it to a default dict using the path as the key. The function uses paramiko.SFTPClient and stat. I am specifically concerned about the performance; it is rather slow.

Prereqsuite information

sftp.listdir_attr returns a list of SFTPAttributes which represent either files, directories, symlinks, etc., and contain a st_mode, which is used to determine if it is a directory or file. This can throw an IOException for example if you don't have permissions to inspect the path.
stat.S_ISDIR will inspect the mode to determine if its a directory

The function in question:

def recursive_ftp(sftp, path='.', files=None):
    if files is None:
        files = defaultdict(list)

    # loop over list of SFTPAttributes (files with modes)
    for attr in sftp.listdir_attr(path):

        if stat.S_ISDIR(attr.st_mode):
            # If the file is a directory, recurse it
            recursive_ftp(sftp, os.path.join(path,attr.filename), files)

        else:
            #  if the file is a file, add it to our dict
            files[path].append(attr.filename)

    return files

Use:

import paramiko
import stat
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)

files = recursive_ftp(sftp)

If we have an SFTP server that looks like this:

/foo
----a.csv
----b.csv
/bar
----c.csv
/baz

The function will return a dictionary like so:

{
    './foo': ['a.csv', 'b.csv'],
    './bar': ['c.csv']
}


texts: Minimum number of steps to move from one city to another

texts:
Question:
A country X consists of N cities numbered 0 to N-1 . The map of this country can be represented as a cycle — for each valid i, city i has exactly two neighboring cities (i+1)%N and (i-1+N)%N.

The cities in the country are broadly categorized into different types. For each valid i, the type of city i is denoted by A[i].

A person called Suarez wants to travel between some pairs of the cities. You are given Q queries. In each query, Suarez wants to travel from city number Y to a city of type Z. Also, he wants to travel only in a given direction along the cycle.

The direction is represented by a letter — L or R. If it's L, Suarez may only move from city i to city (i-1+N)%N for each valid i. If it's R, he may only move from city i to city (i+1)%N.

You need to find the minimum number of steps Suarez needs to take to reach a city of type Z if he starts moving from city Y in the given direction (he can take zero steps). In one step, Suarez can move from his current city to a neighboring city.

If Suarez can never reach a city of type Z for a given query, print -1 instead.

Input format

The first line of the input contains two space-separated integers N and Q. The next line contains N space-separated integers, where the i-th of these integers represents A[i].

Each of the following Q lines describes a query in the format Y Z D, where Y is an integer denoting the number of the starting city, Z is an integer denoting the type of a target city and D is a letter ('L' or 'R') denoting the direction along the cycle.

Output format

For each query, print a single line containing one integer — the answer to the query.

    Input                                Output
    3 4                                  0
    1 2 3                                2
    0 1 L                                1
    1 3 L                                -1
    2 1 R
    1 5 L

My solution is as follows. It gives TLE. Can you suggest me a better and optimized way of doing it.

    class TestClass {
public static void main(String args[] ) throws Exception {
    Scanner kb=new Scanner(System.in);
    int size=kb.nextInt();
    int queries=kb.nextInt();
    int[] city=new int[size];
    for(int i=0;i<size;i++){
        city[i]=kb.nextInt();
    }
    while(queries-->0){
        int current_city_number=kb.nextInt();
        int destination_city_type=kb.nextInt();
        char direction=kb.next().charAt(0);
        int number_of_steps=0;
        if(city[current_city_number]==destination_city_type){
            System.out.println("0");
        }
        else{
            boolean flag=false;
            for(int i=0;i<size;i++){
                if(destination_city_type==city[i]){  //Checking valid/invalid city type
                    flag=true;
                    break;
                }
            }
            if(flag){                                           //Valid city type
                    for(int i=current_city_number;i<size;){
                        if(direction=='R')
                        {i=(i+1)%size; number_of_steps++;}
                        else
                        {i=(i-1+size)%size; number_of_steps++;}
                        if(city[i]==destination_city_type){
                            System.out.println(number_of_steps);
                            break;
                        }
                    }
            }
            else{
                System.out.println("-1");                        //Invalid city type
            }
        }
    }
    }
    }


texts: Bash script that can uncompress: tar, gzip, rar

texts:
This code generally works exactly as it is supposed to. I'm learning bash I'm looking for some constructive help that could help me improve my work.

#!/bin/bash

usage()
{
    echo "Program for uncompressing  tar, gzip, rar archives"
    echo "Allowed parametres: --help, --file, --input, --directory"
    echo "Examples:"
    echo "./uncompress.sh --file firstFile secondFile"
    echo "./uncompress.sh --input inputFile.txt"
    echo "./uncompress.sh --directory /home/"

}

uncompress_file()
{
    if [ -f $1 ]
    then
        temp1=`file $1 | cut -d: -f2 | grep tar`

            if [ "$temp1" != "" ]
                then
                    echo    "$1 is a tar archive, uncompressing..."
                    tar xf $1 > /dev/null
            fi

        temp1=`file $1 | cut -d: -f2 | grep RAR`

            if [ "$temp1" != "" ]
                then
                    echo    "$1 is a rar archive, uncompressing..."
                    unrar e $1 > /dev/null
            fi

        temp1=`file $1 | cut -d: -f2 | grep gzip`

            if [ "$temp1" != "" ]
                then
                    echo    "$1 is a gzip archive, uncompressing..."
                    tar xzf $1 > /dev/null

            fi

    else
    echo    "$1 is not a valid file!"
    fi
}

uncompress_dir()
{
    for file in "$1"/*
        do
            if [ -f $file ]
            then
            uncompress_file $file
            fi

            if [ -d $file ]
            then
            uncompress_dir $file
            fi

        done

}

if [ "$1" = "--help" ]
    then
    usage
    exit

fi

if test $# -lt 2
    then echo "What about parametres?" 1>&2
    exit 1
fi

param=$1;
shift;

if [ "$param" = "--file" ]
    then

        while [ $# -ne 0 ]
        do
            uncompress_file $1
            shift
        done
    exit
fi

if [ "$param" = "--input" ]
    then
        if [ -f $1 ]
            then
                while read line
                do
                    uncompress_file $line

                done < $1
            else
                echo "$1 is not a valid file"
        fi
    exit
fi

if [ "$param" = "--directory" ]
    then
        if [ -d $1 ]
            then
                uncompress_dir $1
            else
            echo    "$1 is not a valid directory"
        fi
    exit
fi

echo "wrong parametres!";


texts: What is the best approach to use in R and why?

texts:
I'm starting working with R, and found some tutorials and exercises online.

I want to divide one variable in two, bigger and equal 79 and smaller 79.

Perhaps because I'm used to python, my first approach was to do something like this:

z <- numeric(length(faithful$waiting))
n = 0
for (i in faithful$waiting) {
n = 1 + n
if (i < 79) z[n] <- 1
}

But I found many tutorials that use this solution instead:

min_wait <- min(faithful$waiting)-0.1
max_wait <- max(faithful$waiting)
cutof <- c(min_wait,79,max_wait)
waiting_cat <- cut (faithful$waiting, breaks=cutof)

What is the best way to do something like this? And can someone explain why.

Thank you!


texts: C++ simple password-protected console app

texts:
I have been reading about passwords and hashing algorithms and what not and decided to write a program.

Overview: The user should be prompted to create a password the first time the program is executed. They should enter a key and confirm it. If they have executed the program previously, then they should just enter the password to gain access.

I determine if the user has run the program by checking if key.txt exists. Is there a more preferred method?

I tried to streamline some code with the two bool functions. Any other suggestions for cleaner or more concise code?

#include <iostream>
#include <fstream>
#include <string>
#include "sha256.h"
using namespace std;

bool keyExists() {
    bool keyExists = false;
    ifstream inFile("key.txt");

    if (inFile) {
        keyExists = true;
    }

    return keyExists;
}

bool isMatch(string key, string confirmKey) {

    bool match = false;
    if (key == confirmKey) {
        match = true;
    }

    return match;
}

int main() {

    if (keyExists()) {
        string key;
        string storedKey;
        cout << "Please enter key: ";
        getline(cin, key);

        SHA256 sha256;
        ifstream inFile("key.txt");
        getline(inFile, storedKey);

        if (isMatch(sha256(key), storedKey)) {
            cout << "Acces Granted!\n";
        }
        else {
            cout << "Access Denied!\n";
        }
    }

    else {
        string key;
        string confirmKey;

        cout << "Please create a key: ";
        getline(cin, key);
        cout << "Confirm key: ";
        getline(cin, confirmKey);

        if (isMatch(key, confirmKey)) {

            SHA256 sha256;
            ofstream outFile("key.txt");
            outFile << sha256(key);
        }

        else {
            cout << "Keys do not match!\n";
        }
    }

    return 0;
}

Many thanks to Stephan Brumme for the awesome hashing algorithm code! This was very easy to implement.


texts: Using Java to implement a hash table (dictionary) with only arrays

texts:
I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:

public class HashTable {
    String[][] table;
    int tableSize;

    HashTable(int size) {
        table = new String[size][];
        tableSize = size;
    }

    public void add(String key, String value) {

        if (key == null || value == null) {
            System.out.println("Cannot input null values");
        }

        int iter = 0;
        int code = Math.abs(key.hashCode()) % tableSize;

        if (table[code] == null) {
            table[code] = new String[]{key, value};
        } else {

            while (table[code] != null) {
                if (table[code][0].equals(key)) {
                    System.out.println("Already submitted submitted the word " + key);
                    return;
                }

                if (iter == tableSize) {
                    System.out.println("Table is full. Cannot add word \"" + key + "\"");
                    return;
                }

                code++;
                code %= tableSize;
                iter++;
            }

            table[code] = new String[]{key, value};

        }
    }

    public void remove(String key) {

        if (key == null) {
            System.out.println("Cannot input null value");
        }

        int iter = 0;
        int code = Math.abs(key.hashCode()) % tableSize;

        if (table[code][0].equals(key)) {
            table[code] = null;
        } else {
            while (!table[code][0].equals(key)) {
                if (iter == tableSize) {
                    System.out.println("Could not find word \"" + key + "\"");
                    return;
                }
                code++;
                code %= tableSize;
                iter++;
            }

            table[code] = null;

        }
    }

    public String get(String key) {

        if (key == null) {
            return "Cannot input null value.";
        }

        int iter = 0;
        int code = Math.abs(key.hashCode()) % tableSize;

        if (table[code][0].equals(key)) {
            return table[code][1];
        } else {
            while (!table[code][0].equals(key)) {
                if (iter == tableSize) {
                    return "Could not find word \"" + key + "\"";
                }
                code++;
                code %= tableSize;
                iter++;
            }

            return table[code][1];

        }
    }

}

Is this an okay implementation? How can I make it better?

Thanks!


texts: Pizza-making combining two builder patterns (Bloch's and Go4)

texts:
I think I just made a very simple way to implement both builder patterns:

Bloch builder (for solving telescoping problem). introduction@Medium, Telescoping problem@SO
Go4 builder pattern (The most difficult one among those 23)

Characters in Go4 builder:

Director: Pizza.Maker
ConcreteBuilder: Pizza.Recipe

I'm also thinking about how to make Builder an abstract interface so one can have more type of recipes (Hot/Sweet/Sour...).

The advantages:

The client doesn't have to know the ingredient types used by Pizza, just tune the parameters of a pizza using Bloch builder. (In my example it just coincident that they're both int.)
The client doesn't have to be an expert in making a pizza, i.e. he/she doesn't have know the actual order of steps of making a pizza, because these steps are handled by the director using the Go4 builder pattern.
But if the client doesn't have an idea for certain steps of making a pizza, he/she can customize it; just @override it.

public class Pizza
{
    final private int baseSize;
    final private int a;
    final private int b;
    final private int c;

    private Pizza(Recipe builder) {
        baseSize = builder.baseSize;
        a = builder.a;
        b = builder.b;
        c = builder.c;
    }

    public static Pizza Maker(Recipe builder) {
        builder.prepare2();
        builder.prepare1();
        builder.prepare3();
        return new Pizza(builder);
    }

    public static class Recipe {
        private int baseSize;
        private int a;
        private int b;
        private int c;
        public Recipe() {
            baseSize = 0;
            a = 0;
            b = 0;
            c = 0;
        }
        public Recipe baseSize(int s) {
            this.baseSize = s;
            return this;
        }
        public Recipe changeA(int a) {
            this.a = a;
            return this;
        }
        public Recipe changeB(int b) {
            this.b = b;
            return this;
        }
        public Recipe changeC(int c) {
            this.c = c;
            return this;
        }
        public void prepare1() {
            System.out.println("Basic preparing 1");
        }
        public void prepare2() {
            System.out.println("Basic preparing 2");
        }
        public void prepare3() {
            System.out.println("Basic preparing 3");
        }
    }
}

public class Main
{
    public static void main() {
        Pizza.Recipe myRecipe = new Pizza.Recipe() {
            @Override
            public void prepare3() {
                System.out.println("Advanced preparing 3");
            }
        };
        myRecipe.baseSize(10);
        myRecipe.changeA(20);
        myRecipe.changeB(15);
        myRecipe.changeC(25);
        Pizza myPizza = Pizza.Maker(myRecipe);
        System.out.println();
        // One line-er
        Pizza onelinePizza = Pizza.Maker(new Pizza.Recipe()
                                                  .baseSize(10)
                                                  .changeA(20)
                                                  .changeC(25));
    }
}

And the printed result:

Basic preparing 2
Basic preparing 1
Advanced preparing 3

Basic preparing 2
Basic preparing 1
Basic preparing 3

The original purpose of making Builder abstract, described in Go4 design patterns book, is that the client can decide the representation of the product later on, e.g. In my example then I would be able to create many types of pizza using new recipes (maybe real pizza, pixelized pizza, and LEGO pizza, etc).

But I don't know how to make Pizza.Recipe abstract while still make everything simple. If this can be done then the client can design he/she's own preparing order, just like he/she is the cook!


texts:
I am implementing the algorithms of Course: Coursera Algorithm I.
I implemented the Merge-Sort using recursion and although it sorts correctly I am not sure if it is a correct implementation of this algorithm. Could you guys take a look? How can I keep it more "readable"?

##
# Implemetation of Merge Sort see: {https://pt.wikipedia.org/wiki/Merge_sort}
module Merge
  class Sort
    include Validator, Comparator

    def sort(values)
      return values if invalid_to_sort?(values)
      _sort(values, 0, values.size - 1)
    end

    private

    def _sort(values, ibegin, iend)
      return [values[ibegin]] if ibegin == iend

      mid = ((iend - ibegin) / 2) + ibegin

      left  = _sort(values, ibegin, mid)
      right = _sort(values, mid + 1 , iend)

      merge([], left, right)
    end

    def merge(values, left, right)
      # p "values #{values} left #{left} right #{right}"
      return values if left.empty? and right.empty?

      if left.empty?
        merge(values + [right.shift], left, right)

      elsif right.empty? || (left.first <=> right.first) <= 0
        merge(values + [left.shift], left, right)

      else
        merge(values + [right.shift], left, right)
      end
    end
  end
end

The entire implementation


texts:
I have some code that will brute force solve the following problem:

  Given a set of x coins and a target sum to reach, what is the fewest number of coins required to reach that target?

The code so far:

import java.util.ArrayList;
import java.util.Arrays;

public class coinsSum {
    public static int min = Integer.MAX_VALUE;
    public static int[] combination;
    public static final int TARGET = 59;

    public static void main(String[] args) {
        long start = System.nanoTime();

        int[] validCoins = new int[] {1, 2, 5, 10, 20};
        Arrays.sort(validCoins);
        int len = validCoins.length;

        ArrayList<Integer> maxList = new ArrayList<Integer>();
        for(int c : validCoins) {
            maxList.add(TARGET / c);
        }

        int[] max = new int[len];
        for(int i = 0; i < len; i++) {
            max[i] = maxList.get(i).intValue();
        }

        permutations(new int[len], max, validCoins, 0); // bread&butter

        if(min != Integer.MAX_VALUE) {
            System.out.println();
            System.out.println("The combination " + Arrays.toString(combination) + " uses " + min + " coins to make the target of: " + TARGET);
        } else {
            System.out.println("The target was not reachable using these coins");
        }

        System.out.println("TOOK: " + (System.nanoTime() - start) / 1000000 + "ms");
    }

    public static void permutations(int[] workspace, int[] choices, int[] coins, int pos) {
        if(pos == workspace.length) {
            int sum = 0, coinCount = 0;
            System.out.println("TRYING " + Arrays.toString(workspace));
            for(int a = 0; a < coins.length; a++) {
                sum += workspace[a] * coins[a];
                coinCount += workspace[a];
            }
            if(sum == TARGET) {
                // System.out.println(Arrays.toString(n)); //valid combinations
                if(coinCount < min) {
                    min = coinCount;
                    combination = workspace;
                    System.out.println(Arrays.toString(combination)+" uses " + min + " coins");
                }
            }
            return;
        }
        for(int i = 0; i <= choices[pos]; i++) {
            workspace[pos] = i;
            permutations(workspace, choices, coins, pos + 1);
        }
    }
}

This solution uses recursion. Is there any way to compute combinations in Java using loops?

What other improvements can be made to the algorithm?


texts:
I am calculating market values for shares and on the basis of loss and profit, the respective operations are being done.

Can anyone around help me in optimizing this and making it more Pythonic in approach?

Calc.py:

from decimal import Decimal
from order import Order
from mark import Mark

class MyCalc():
    total_profit = 0

    def __init__(self, loss_limit, market_threshold):
        assert isinstance(loss_limit, Decimal)
        assert isinstance(market_threshold, Decimal)
        self.loss_limit = loss_limit
        self.market_threshold = market_threshold
        self._previous_mark = None
        self._mark_count = 0

    def perform_calculation(self, mark):
        assert isinstance(mark, Mark)
        self._mark_count += 1

        if not self._previous_mark:
            self._previous_mark = mark

        profit = round(((mark.rate - self._previous_mark.rate) / self._previous_mark.rate), 2)
        self.total_profit += profit

        if self._previous_mark.rate < mark.rate and self._mark_count >= 4:
            self.__init__(self.loss_limit, self.market_threshold)
            self.total_profit = 0
            return Order(Order.SIDE_BUY, 100, mark.denote)

        if self.total_profit < 0 and abs(self.total_profit) >= abs(self.loss_limit):
            self.__init__(self.loss_limit, self.market_threshold)
            self.total_profit = 0
            return Order(Order.SIDE_SELL, 100, mark.denote)

        if self.total_profit > self.market_threshold:
            self.__init__(self.loss_limit, self.market_threshold)
            self.total_profit = 0
            return Order(Order.SIDE_SELL, 100, mark.denote)

        if self._previous_mark.denote != mark.denote:
            self._mark_count -= 1
            self.total_profit -= profit
            return None

        if self._previous_mark.rate > mark.rate:
            self.__init__(self.loss_limit, self.market_threshold)
            self._mark_count += 1

        self._previous_mark = mark

        return None

mark.py

from decimal import Decimal

class Mark(object):
    def __init__(self, denote, rate, vol):
        assert isinstance(denote, basestring)
        assert isinstance(rate, Decimal)
        assert isinstance(vol, int)
        self.denote = denote
        self.rate = rate
        self.vol = vol

order.py

class Order(object):
    SIDE_BUY = 1
    SIDE_SELL = 2

    def __init__(self, side, vol, denote):
        self.side = side
        self.vol= vol
        self.denote = denote


texts:
Given a list of numeric intervals in the form of (a,b), where a and b are integers, it finds a set of disjoint intervals that cover the same numbers by splitting the original intervals at the points where they intersect.

For example: disjoint [(1,2),(1,3),(1,3),(30,31)] gives [(1,2),(2,3),(30,31)].

Please help me make this code less ugly.

{-# LANGUAGE TupleSections #-}

import Data.List (group, sortBy)

-- [(97, 99), (97, 100), (98, 108)]
-- [97, 97] [98, 99], [100, 100], [101, 108]

disjoint :: (Ord a, Num a) => [(a, a)] -> [(a, a)]
disjoint [] = []
disjoint ts = disjoint' 0 x xs
    where
      disjoint' _ _ []          = []
      disjoint' c (k, p) (x:xs) = let c' = c + k
                                      h  = if c' > 0 then [(p, snd x)] else []
                                  in h ++ (disjoint' c' x xs)
      eitherValue               = either id id
      endpoints                 = foldr (\(a, b) m -> (Left a):(Right b):m) []
      pcompare x y              = compare (eitherValue x) (eitherValue y)
      runs                      = let f xs@(x:_) = either (length xs,) (-length xs,) x
                                  in map f . group
      (x:xs)                    = runs $ (sortBy pcompare) $ endpoints ts


texts:
In anticipation of the new Angular release and since I've only just begun learning it, I have been developing a project in a directive-oriented way. Below is a sample of a section that handles message posting, and I was wondering how I could improve it using some best practices or conventions that I might have missed.

The directive HTML:

<form id="nieuws-edit-form">
    Title<input type="text" />

    Date
        <input kendo-datetimepicker k-options="news.dtpDateTime_options" />

    Language
        <input kendo-dropdownlist k-options="news.ddlLanguage_options" />

    <textarea kendo-editor k-options="news.ediMessage_options"></textarea>
    Save
</form>

The directive code:

angular.module('app.news')
.directive('newsEdit', [function () {
    return {
        controller: 'newsController',
        controllerAs: 'news',
        bindToController: true,
        templateUrl: partialPath + 'news-edit.html',
        link: function (scope, element, attrs, ctrl) {
            // call some controller things here to prepare the view
            // like fetching the news item (when editing)
            ctrl.readOne();

            // kendo control option definitions
            ctrl.dtpDateTime_options = {
                interval: 15
            };

            ctrl.ddlLanguage_options = {
                dataSource: { },
                dataTextField: 'Name',
                dataValueField: 'Code',
                value: 'eng'
            };

            ctrl.ediMessage_options = {
                resizable: true,
                tools: ['list', 'of', 'items'],
                imageBrowser: { }
            };
        }
    };
}]);

And finally, my controller:

angular.module('app.news')
.controller('newsController', ['$state', 'NewsService',
    function ($state, $service) {
        var _this = this;

        _this.readOne = readOne;
        _this.params = $state.params;
        _this.item = null;

        function readOne(id) {
            if (id == (null || undefined)) {
                id = _this.params.id;
            }

            if (!isNaN(id) && id >= 0) {
                $service.readOne(id).then(function (response) {
                    _this.item = response;
                });
            }
        }
    }
]);

Now, one of my concerns with this method is that I put a bulk of code in the link function so I can initialize the Kendo UI controls. I know I can specify the options in-line in the HTML tag, but that gets ugly very fast. Once the page has 10+ controls, I'll probably split it up in methods or something. I guess there's not much to do about trimming down the size of the control options.

Which brings me to my next concern: am I even using the link function correctly? Should I be doing the things I do in there in a different place?


texts:
I am learning more about python using the book "Automate The Boring Stuff". The problem I completed was "Excel To CSV Converter". I want to kick bad habits to the curb, and make sure I'm learning the best python practices to further my development. I would really appreciate feedback on code efficiency, and code neatness. Is my code PEP-8 compliant? Does it implement all the best practices possible? Thank you in advance, all feedback is appreciated and considered!

import openpyxl, csv, os, re, shutil

path = os.getcwd()
new_path = path + '\\' + 'csv_files'

for excel in os.listdir('.'):

    if not excel.endswith('xlsx'):
        continue

    workbook = openpyxl.load_workbook(excel)

    for sheets in workbook.sheetnames:
        wb_name = re.sub('.xlsx', '', excel)
        csv_name = wb_name + '_' + sheets + '.csv'
        csv_file = open(csv_name, 'w', newline='')
        csv_writer = csv.writer(csv_file)
        sheet = workbook.active

        for row_number in range(1, sheet.max_row + 1):
            row_info = []

            for col_number in range(1, sheet.max_column + 1):
                data = sheet.cell(row=row_number, column=col_number).value
                row_info.append(data)

            csv_writer.writerow(row_info)

        csv_file.close()
        shutil.move(os.path.join(path, csv_name), os.path.join(new_path, csv_name))


texts:
I would like some comments on my code and implementation for this simple piece of jQuery.

Basically it is 2 div boxes #side1 and #side2, in a container div called #frontimage, where #side2 can be swung out by dragging from right to left along #frontimage.

My jQuery code below continuously updates the CSS transform rotateY parameters for #side2 based on a mousemove event.

Here is a working example:

http://jsfiddle.net/Sr4zw/embedded/result/

And here is the complete code including HTML and CSS:

http://jsfiddle.net/Sr4zw/

$(document).ready(function() {

    var yDegrees = 0, slidingLength = 372, maxRotation = -45;

    $("#frontimage").on('mousedown', function( event ) {

        var originX = event.pageX;

        $("#frontimage").on("mousemove", function( event ) {

            yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);
            if (yDegrees < maxRotation) {
                yDegrees = maxRotation;
            };
            if (yDegrees > 0) {
                yDegrees = 0;
                };

            originX = event.pageX;

            $("#side2").css({
                '-webkit-transform': 'rotateY(' + yDegrees + 'deg)',
                '-moz-transform': 'rotateY(' + yDegrees + 'deg)',
                '-ms-transform': 'rotateY(' + yDegrees + 'deg)',
                '-o-transform': 'rotateY(' + yDegrees + 'deg)',
                'transform': 'rotateY(' + yDegrees + 'deg)'
            });
        });
    });

    $('html').on('mouseup', function() {

        $("#frontimage").off('mousemove');

    });
});

Some comments on my implementation:

yDegrees stores the current rotation degree.
slidingLength is the length (in pixels) of the mouse drag that changes yDegrees.


texts: Simulating gravitational attraction between bodies

texts:
I'm currently working on a simple simulator in Unity3D that involves planets orbiting each other. I wrote the following C# script to do that. It uses the classic gravitational formula,

$$F=G\frac{m_1m_2}{r^2}$$

using UnityEngine;

/// <summary>
/// Class used for calculating
/// how an object orbits another
/// object.
/// </summary>
/// <param name="parentObject">The parent gameObject to orbit.</param>
/// <param name="objectMass">The mass of the object.</param>
/// <param name="gravityConstant">The gravitational constant.</param>
[RequireComponent(typeof(Rigidbody))]
public class OrbitObject : MonoBehaviour
{
    public OrbitObject parentObject;
    public float objectMass;
    public float gravityConstant;

    private Vector3 parentPosition;
    private float parentMass;

    /// <summary>
    /// Calculates the gravitational attraction.
    /// </summary>
    /// <returns>The force to apply</returns>
    Vector3 CalculateGravitationalForce()
    {
        this.parentPosition = this.parentObject.transform.position;
        Vector3 force = this.parentPosition - transform.position;
        float distance = force.magnitude;
        float strength = (this.gravityConstant * this.parentMass * this.objectMass) / (distance * distance);
        force.Normalize();
        force = force * strength;
        return force;
    }

    /// <summary>
    /// FixedUpdate is run once per frame.
    /// FixedUpdate is used so that calculations
    /// don't need to be multiplied by Time.deltaTime.
    /// </summary>
    void FixedUpdate()
    {
        rigidbody.AddForce(this.CalculateGravitationalForce());
    }

    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        this.parentPosition = this.parentObject.gameObject.transform.position;
        this.parentMass = this.parentObject.objectMass;
    }
}

For those who are curious, a gif of the script in action can be found here.


texts:
I'm currently learning JAVA in a class and we're using the ACM Graphics package. I wanted some pointers on my code. To provide some context here is the assignment:

  Write a program that creates an array of 5 custom objects (cows, UFOs,
  cars, etc.) and then lines them up along the left edge of the window.
  Assign each object a random velocity, and then move the objects to the
  right edge of the window. When one of the objects (the "winner")
  reaches the right edge of the window, remove the other objects and
  cause the winner to flash on and off.

This works just fine and fulfills all the requirements from the assignment. What I want to know is how can I improve this code while still remaining within the requirements. Also any reading materials/videos that you think would be useful for my learning please feel free to share them.

Main Race file:

import acm.graphics.*;
import acm.program.*;
import acm.util.RandomGenerator;
import java.awt.Color;

public class Race extends GraphicsProgram {

    //Setting up variables
    private static final int WAIT = 20;
    private static final int WINDOWX = 400;
    private static final int WINDOWY = 600;
    private static final int UFO_COUNT = 5;
    private UFO[] ufos = new UFO[UFO_COUNT];
    private boolean flag = true;
    private RandomGenerator rgen = new RandomGenerator();

    public void init() {
        setSize(WINDOWX, WINDOWY);
    }

    public void run() {
        //Set up UFOs at start
        for (int i=0; i<UFO_COUNT; i++) {
            ufos[i] = new UFO(0, i*100);
            ufos[i].alien.setColor(rgen.nextColor());
            add(ufos[i]);
        }

        int winner = -1;
        waitForClick();

        while(flag) {
            pause(WAIT);

            //Move Ufos
            for (int i=0; i<ufos.length; i++ ) {
                ufos[i].move(rgen.nextInt(0, 2), 0);

                //Is there a winner?
                if(ufos[i].getX() > WINDOWX){
                    winner = i;
                    flag = false;
                }
            }
        }

        if(!flag) //Safeguard
            displayWinner(winner);
    }

    private void displayWinner(int winner) {
        //Hide others
        for (int i=0; i<ufos.length; i++ ) {
            ufos[i].setVisible(false);
        }

        //Make the winner flash
        while(true) {
            ufos[winner].setVisible(false);
            pause(200);
            ufos[winner].setVisible(true);
            pause(200);
        }
    }
}

UFO Constructor Class:

import acm.graphics.*;
import java.awt.*;

public class UFO extends GCompound {
    public GOval body, bubble, alien;

    public UFO(int x, int y){
        //Draw ufo
        body = new GOval(100, 50);
        body.setFilled(true);
        body.setColor(Color.RED);

        bubble = new GOval(50, 50);
        alien = new GOval(20, 20);
        alien.setFilled(true);
        alien.setColor(Color.GREEN);

        add(bubble, x+26, y+0);
        add(alien, x+40, y+10);
        add(body, x+0, y+26);
    }
}


texts:
We're migrating our streaming ETL application from Python into Clojure,
the hottest part of the code isn't yet performing as well as our existing
implementation.  This looks to be down to the algorithmic complexity of our flattening function.

Take a nested map, flatten the data structure and rename keys.  We take data
from multiple sources and have to smudge the data to fit a legacy format.
For this all of the keys/values need to be at the root level of the map with the
correct keys.  Any 'new' keys can be left as is and not renamed.

The transformation was originally a threading macro, with a flatten and a
set/rename-keys, this has been improved to rename variables while looping
through each level of the map. The flatten however still accounts for ~80% of the time spent processing a record.

An example input would be as follows:

{:foo {:foo-host "host-1" :user {:foo-user "user-1" :foo-id "id-1"}}
 :bar {:bar-var "potato"}}

With an expected output of:

{:host "host-1" :user "user-1" :id "id-1" :var "potato"}

We've gone through and removed any java reflection, and type hinted the hottest
parts of our code so no more gains can be found there.  The last slow pieces
of code are as follows:

(def match-table {:foo-host :host
                  :foo-user :user
                  :foo-id :id
                  :bar-var :var})

(defn flatten-record
  "Take a nested record and recursively flatten."
  [^clojure.lang.PersistentArrayMap record]
  (into {}
    (for [[k v] record]
      (if (map? v)
        (flatten-record v)
        ;; If the key's not found return itself as the default.
        {(get match-table k k) v}))))

The flatten-record function consumes the stack as it's lacking any tail call
optimisation, trampoline may be a better solution?  The records transformed are
a maximum of 5 deep, so there's no risk of a recursion overflow.

I'm mainly concerned about performance here, so am open to any hints!

Larger examples are available here.


texts: indexOf Boyer-Moore String Search algorithm

texts:
This is an implementation of Boyer-Moore string search algorithm index_of for a pattern in text. I was challenged to implement it by my friend.

This Python function returns the starting index of the first occurrence of a pattern in text and returns None if no index is found. For example, index_of('ababc', 'abc') returns 2 and index_of('abc', 'z') returns None.

I have the following implementation that handles most of the cases and I think the worst case running time is \$O(m/n)\$.

def index_of(text, pattern):
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
    # Check if empty; if so, return 0, earliest bit
    if len(pattern) == 0:
        return 0
    pattern = list(pattern)
    pattern_len = len(pattern)

    text = list(text)
    textext_len = len(text)

    shift = 0
    while(shift <= textext_len - pattern_len):
        index = pattern_len - 1
        # Keep going until it all meets
        while index >= 0 and pattern[index] == text[shift+index]:
            index -= 1
        # If we get past index, then return where the shift is
        if index < 0:
            return shift
        else:
            if text[shift+pattern_len-1] in pattern:
                shift += pattern_len - pattern.index(text[shift+pattern_len-1]) - 1
            else:
                shift += pattern_len
    return None

I include my code here. I ran my code against 3 separate tests, and it passed all of the pytests. So it's pretty robust, and I think my implementation works fine.

import unittest

class Test(unittest.TestCase):

    def test_index_of_with_matching_patterns(self):
        assert index_of('abc', '') == 0  # all strings contain empty string
        assert index_of('abc', 'a') == 0  # single letters are easy
        assert index_of('abc', 'b') == 1
        assert index_of('abc', 'c') == 2
        assert index_of('abc', 'ab') == 0  # multiple letters are harder
        assert index_of('abc', 'bc') == 1
        assert index_of('abc', 'abc') == 0  # all strings contain themselves
        assert index_of('aaa', 'a') == 0  # multiple occurrences
        assert index_of('aaa', 'aa') == 0  # overlapping pattern
        assert index_of('thisisabsolutelycrazy', 't') == 0
        assert index_of('abcdef', 'abcdef') == 0  # all strings contain
        assert index_of('abcdef', 'abcdef') == 0  # all strings contain

    def test_index_of_with_non_matching_patterns(self):
        # Negative test cases (counterexamples) with non-matching patterns
        assert index_of('abc', 'z') is None  # remember to test other letters
        assert index_of('abc', 'ac') is None  # important to test close cases
        assert index_of('abc', 'az') is None  # first letter, but not last
        assert index_of('abc', 'abz') is None  # first 2 letters, but not last

    def test_index_of_with_complex_patterns(self):
        # Difficult test cases (examples) with complex patterns
        assert index_of('ababc', 'abc') == 2  # overlapping prefix
        assert index_of('bananas', 'nas') == 4  # overlapping prefix
        assert index_of('abcabcabc', 'abc') == 0  # multiple occurrences
        assert index_of('abcabcab', 'abc') == 0  # multiple occurrences
        assert index_of('abcabcdef', 'abcd') == 3  # overlapping prefix
        assert index_of('abcabcdef', 'abcdef') == 3  # overlapping prefix
        assert index_of('abcabcdabcde', 'abcde') == 7  # overlapping prefix
        assert index_of('abcabcdabcde', 'abcd') == 3  # multiple occurrences, overlapping prefix
        assert index_of('abra cadabra', 'abra') == 0  # multiple occurrences
        assert index_of('abra cadabra', 'adab') == 6  # overlapping prefix

if __name__ == '__main__':
    unittest.main()


texts: Search for string in many WBs and post results into another WB

texts:
I want to search for a string inserted in TextBox1 on Mainwb within a range of data located in Workbook officerA Worksheet DATA!(A2,G2000), and then paste results found into Workbook Mainwb.sheet("MAIN SCREEN").Range (A5,G500)

I am totally new to VBA and wrote this code quoting from many sources. I'd like to know how it can be improved.

This is used to search within the same workbook:

Sub CommandButton1_Click()
Dim wb1 As Workbook, Wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim strSearch As String
Dim f As Variant
Dim fAddress As String
Dim fRow As Long
Dim cellA As Variant
Dim cellB As Variant

 Set Wb2 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\OfficerA.xlsx")
  Set wb1 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\Mainwb.xlsm")
   Set ws2 = wb1.Sheets("MAIN SCREEN").Range("A5:G2000")
   Set ws1 = Wb2.Worksheets("DATA")

strSearch = TextBox1.Value

ws1.Range("A5:G2000").ClearContents
Set dmr = Workbooks.Open("C:\Users\aselhayani\Desktop\Excel Reports\OfficerA.xlsx")
Set dmr = Worksheets("DATA")
strSearch = InputBox("Please enter T24 ID:", "Search Value")

pasteRowIndex = 5

If strSearch = vbNullString Then
    MsgBox ("User canceled, or did not enter a value.")
    Exit Sub
End If

With ws1.Range("A2:G2000")

    Set f = .Find(strSearch, LookIn:=xlValues)
    If Not f Is Nothing Then
        fAddress = f.Address
        Do
            fRow = f.Row
            cellA = ws2.Cells(fRow, 1).Value
            cellB = ws2.Cells(fRow, 2).Value
            cellC = ws2.Cells(fRow, 3).Value
            cellD = ws2.Cells(fRow, 4).Value
            cellE = ws2.Cells(fRow, 5).Value
            cellF = ws2.Cells(fRow, 6).Value
            cellG = ws2.Cells(fRow, 7).Value

            ws1.Cells(pasteRowIndex, 1) = cellA
            ws1.Cells(pasteRowIndex, 2) = cellB
            ws1.Cells(pasteRowIndex, 3) = cellC
            ws1.Cells(pasteRowIndex, 4) = cellD
            ws1.Cells(pasteRowIndex, 5) = cellE
            ws1.Cells(pasteRowIndex, 6) = cellF
            ws1.Cells(pasteRowIndex, 7) = cellG

            pasteRowIndex = pasteRowIndex + 1

            Set f = .FindNext(f)

        Loop While Not f Is Nothing And f.Address <> fAddress
    End If
End With
MsgBox "Search Done"
End Sub


texts:
I have a model that I've created in Codeigniter to represent a vote. The purpose of the site that it's a part of is to allow users to vote on their preferred pronunciation for a given word.

The routine first checks to see if a user has registered a vote for the given pronunciation and if so, whether it was up or down. Just like the stackexchange network sites, you can only vote either up or down for a given entry and you can only vote once in either direction. Am I doing this wrong? Is there a simpler way to accomplish what I'm trying to do here (such as adding a method or two)? If there's anything else that you'd like to see that I haven't posted, let me know.

public function vote($pronun_id, $user_id, $direction) {
        $data = array(
                'pronun_id' => $pronun_id,
                'user_id' => $user_id,
                'direction' => $direction
            );
        $already_voted = $this->_vote_exists($pronun_id, $user_id);

        if($already_voted == 'up') {
            if($direction == 'up') {
                return false;
            }
            else {
                $this->db->where(array('user_id' => $user_id, 'pronun_id' => $pronun_id));
                $this->db->update('vote', array('direction' => $direction));
                return true;
            }
        }
        elseif($already_voted == 'down') {
            if($direction == 'down') {
                return false;
            }
            else {
                $this->db->where(array('user_id' => $user_id, 'pronun_id' => $pronun_id));
                $this->db->update('vote', array('direction' => $direction));
                return true;
            }
        }
        else {
            $this->db->insert('vote', $data);
            return true;
        }
    }

    private function _vote_exists($pronun_id, $user_id) {
        $data = $data = array(
                'pronun_id' => $pronun_id,
                'user_id' => $user_id
            );
        $query = $this->db->get_where('vote', $data);

        if($query->num_rows() > 0) {
            $row = $query->row_array();
            return $row['direction'];
        }
        else {
            return false;
        }
    }

Update: Also, I'm very new to Codeigniter, so please feel free to be brutal about anything here. I'm not the best programmer and I also just don't know Codeigniter "style" yet, so either of those may be issues here.


texts: Python script to create Android/iOS strings from a .csv

texts:
My script takes a CSV file of strings and then creates an XML file for Android and a .strings file to be used for iOS. It separates each locale meaning that a file will be created for each language.

This has come in handy so far, making localising mobile apps easier. However, I am always seeking feedback so let me know what you think.

Input

The .csv is provided in the format: key, language1, language2

key,en,ru
welcome_message,hello,здравствуйте
thank_you_message,thank you,спасибо
goodbye_message,goodbye,До свидания

Output

XML - Android

en_strings.xml

<?xml version="1.0" ?>
<resources>
    <string name="welcome_message">hello</string>
    <string name="thank_you_message">thank you</string>
    <string name="goodbye_message">goodbye</string>
</resources>

ru_strings.xml

<?xml version="1.0" ?>
<resources>
    <string name="welcome_message">здравствуйте</string>
    <string name="thank_you_message">спасибо</string>
    <string name="goodbye_message">До свидания</string>
</resources>

.Strings - iOS

en.strings

/*  */
"welcome_message" = "hello";

/*  */
"thank_you_message" = "thank you";

/*  */
"goodbye_message" = "goodbye";

ru.strings

/*  */
"welcome_message" = "здравствуйте";

/*  */
"thank_you_message" = "спасибо";

/*  */
"goodbye_message" = "До свидания";

At the moment I've just hardcoded the origin Strings.csv file and the user defines the target directory, this will be useful when integrating it into automatic builds etc.

# -*- coding: utf-8 -*-
# Script takes a csv and creates strings for Android (.xml) and iOS (.Strings).
# csv in the format [key, language1, langauge2 ......]
# usage - Python converter.py [FILEPATH]

import sys, os, getopt, csv, xml.etree.ElementTree as ET
from xml.dom import minidom

def prettify(elem):
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

# Read in output directory
try:
   sys.argv[1:]
   fileDestination = sys.argv[1]
except IndexError:
   print "Error: Please supply an output directory."
   print "Usage: converter.py [FILEPATH]"
   sys.exit()

# Create directory if it doesn't exists
if not os.path.exists(fileDestination):
    os.makedirs(fileDestination)

# Read from csv
f = open('Strings.csv')
csv_f = csv.reader(f)

# Determine the number of languages from the csv
line1 = csv_f.next()
numberOfLocales =  len(line1)

# Create strings for each language
for x in range(1, numberOfLocales):
    #Returns to the start of the csv and ignores the first line
    f.seek(0)
    csv_f.next()
    rowIndex = 0

    # Android xml
    resources = ET.Element("resources")

    # Create iOS strings file
    iOSFile = open(fileDestination+"/"+line1[x]+".Strings", "w+")

    for row in csv_f:
        ++rowIndex
        try:
            # Write string to xml
            ET.SubElement(resources, "string", name=row[0]).text = row[x].decode('utf-8')
            # Write string to iOS .Strings
            iOSFile.write("/*  */\n")
            iOSFile.write('"'+row[0]+'"'+ ' = ' + '"'+row[x]+'"' + ";\n")
            iOSFile.write("\n")
        except IndexError:
            f.seek(0)
            print "There is a problem with the csv file at row {}".format(rowIndex+1) + " with the language {}".format(line1[x])
            r = list(csv_f)
            print r[rowIndex]
            sys.exit()
    # Write to Android file
    androidFile = open(fileDestination+"/"+line1[x]+"_strings.xml", "w+")
    androidFile.write(prettify(resources).encode('utf-8'))


texts:
I have a link aimed to '/FridgeTemperatureRoute' and a checkbox. Purpose of the checkbox is to show the user whether the check has been done or not.

        Fridge and Freezer Temperature

        <input id="FridgeTemperatureCheckBox" type="checkbox" name="" value="" disabled {{fridgeFreezerTemperatureReturnObj}}>

Summary of code
You'll see this line {{fridgeFreezerTemperatureReturnObj}} - this is from Node JS server, which determines whether the checkbox is ticked or not.
Jquery, Javascript and Bootstrap Model
Next, I am aiming to open a bootstrap model on user click, but only if the checkbox is ticked. If the user clicks and the checkbox is checked, then open a bootstrap model asking whether to continue to the href or simply cancel rendering the next page.

You have already completed this check, do you want to do it again?

        <button type="button" class="btn btn-default" id="confirmOk">Ok</button>
            <button type="button" class="btn btn-default" id="confirmCancel" data-dismiss="modal">Cancel</button>

Summary
I have it working - but I believe it can be simplified. Just looking for some reviews and where I can improve on :)


texts:
Need help to refactor this code to look like its done by a pro. Or just put some advice or links to useful stuff.
The idea is to clone a div with two empty tables for two separate arrays of data.
div is cloned depending on the longest array length between the two. Then append row of data to them, if rows reach max number the loop continues on another cloned table. loop continues even if the one row is finished appending

        //content1
        //7 row max

        //content2
        //21 row max

Javascript part
let d1 = @json($data1); //get data
let d2 = @json($data2); //get data

let ar1 = [];
let ar2 = [];
let s = 0;

for (let i = 7; i < d1.length; i+=7) {
    ar1.push(d1.slice(i, i+7));           //slice data 1
}

for (let i = 21; i < d2.length; i+=21) {
    ar2.push(d2.slice(i, i+21));          //slice data 2
}

ar1.length > ar2.length ? s = ar1.length : s = ar2.length; //take longest array length

for (let v = 0; v < s-1; v++) { //clone div using longest array length
     $("#d-page-0").clone().prop("id", "d-page-"+(v+1)).insertAfter("#d-page-"+v); //clone div, edit id
     $("#d-page-"+(v+1)).find("#e-tbl-0", "table").prop("id", "e-tbl-"+(v+1)); //edit 1st tbl id
     $("#d-page-"+(v+1)).find("#w-tbl-0", "table").prop("id", "w-tbl-"+(v+1)); //edit 2nd tbl id
}

//append 1st data to 1st table
 for (let x = 0; x < ar1.length; x++) {
      let k = ar1[x];
      for (let y = 0; y < k.length; y++) {
           $('#e-tbl-'+x).append(
                `

                      ar1[x][y].content

`
            );
      }
}

//append 2nd data to 2nd table
 for (let x = 0; x < ar2.length; x++) {
      let k = ar2[x];
      for (let y = 0; y < k.length; y++) {
           $('#w-tbl-'+x).append(
                `

                      ar1[x][y].content

`
            );
      }
}

working sample
https://jsfiddle.net/eeneg/pgk3dhac/57/


texts:
My argument sanitization lib has a byproduct which does some typechecking and constructor investigation. I'm unsure if I'm using the fastest / most efficient approach here.

What are your opinions? Total rubbish or does it have a right to exist? ;)

// Return the type of an object aka safe typeof
function typeOf(o) {
    return Object.prototype.toString.call(o).match(/(\w+)\]/)[1];
}

// Return the name of a function aka class name
function nameOf(o) {
    return typeOf(o) == "Function"
        ? Function.prototype.toString.call(o).match(/function\s?(\w*)\(/)[1]
        : false;
}

// Return the expected arguments of a function
function argumentsOf(o) {
    if(typeOf(o) == "Function") {
        var args = Function.prototype.toString.call(o).match(/\((.+)\)\s*{/);
        if(!!args && !!args[1]) return args[1].replace(/\s+/g, "").split(",");
        else return [];
    } else return false;
}


texts:
Is this the correct way to set value of textbox to zero when it's null? Is there any way I can improve the calculation that I am doing?

private void TB_PAID_CASH_TextChanged(object sender, EventArgs e)
{
    try
    {
        if (!string.IsNullOrEmpty(TB_TOTAL_INV.Text) && !string.IsNullOrEmpty(TB_PAID_CASH.Text) && string.IsNullOrEmpty(TB_Discount.Text))
        {
            int Discount;
            int.TryParse(TB_Discount.Text, out Discount);
            TB_REMAINDER.Text = (Convert.ToInt32(TB_PAID_CASH.Text) - Convert.ToInt32(TB_TOTAL_INV.Text) - Discount).ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}


texts: Rolling my own markdown parser in JavaScript

texts:
For several days I was messing around trying to create a markdown parser. This is the best I could come up without using regex. I was wondering if I'm on the right track.(I only covered the *,** case )

var str = "**f*";

function parser() {

    var i;
    var string = ' ';

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

        if (token(str[i]) !== -1) {

            var data = trim(str[i], i);

            string += data[0];

            if (data[1] === -1) {
                string += str[i];
            } else {
                i = data[1]; //skip if necessary
            }

        } else {
            string += str[i];
        }

    }

    console.log(string);
}

function trim(chr, pos) {

    var inner_string = '';
    var inner_pos = pos;

    if (str[inner_pos] === chr && str[inner_pos + 1] === chr && str[inner_pos + 1] !== undefined) // consecutive tokens
    {
        var next = pair(chr, pos);

        if (next !== -1) {
            console.log(next);

            inner_string = str.substring(pos + 2, next);
            inner_pos = next;
        } else {

            inner_pos++;
        }
    } else {

        var next = str.indexOf(chr, pos + 1);

        if (next > 0) {

            console.log(next);
            inner_string = str.substring(pos + 1, next);
            inner_pos = next;
            inner_pos = next;
        } else {

            inner_pos = next;
        }

    }

    return [inner_string, inner_pos];
}

function pair(char, pos) {

    var iter = pos;

    while (iter !== str.length - 1) {
        iter++;
        if (str[iter] === char && str[iter + 1] === char && str[iter + 1] !== undefined) {

            return iter;
        }

    }

    return -1;

}

function token(char) {

    if (char === '*') {
        return 1;
    } else return -1;
}

parser();


texts: Application that processes XML based on configuration

texts:
I used CodeClimate to evaluate my code and marked that the following piece of code appeared twice in my source:

    except IOError as e:
        log.error("I/O error({0}): {1}".format(e.errno, e.strerror))
        app_exit(1)

The justification is that the amount of duplication mass is 33, which is above default limit of 32.

How would you solve this problem? Would you disable the check? Would you wrap the 2 lines in a new method? Something else?

The duplicate part in question is in main:

#!/usr/bin/env python

import logging as log

def get_cfg(xmlfile):
    # gets configuration from file which
    # has the same name as XML
    # but with different extension.
    pass

def get_root(xmlfile):
    pass

def app_exit(status):
    log.info('Exiting...')
    exit(status)

def setup_logging(args):
    if args.verbose == 2:
        log.basicConfig(level=log.DEBUG)
    elif args.verbose == 1:
        log.basicConfig(level=log.INFO)
    else:
        log.basicConfig(level=log.WARN)

def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file', help='XML file to be parsed')
    parser.add_argument("-v", "--verbose", action="count",
                        help="increase output verbosity")

    args = parser.parse_args()

    setup_logging(args)

    xmlfile = args.file
    log.info('Getting root element from XML {}.'.format(xmlfile))
    try:
        root = get_root(xmlfile)
    except ET.ParseError as e:
        log.error("Error while parsing {0}: {1}".format(xmlfile, e))
        app_exit(1)
    except IOError as e:
        log.error("I/O error({0}): {1}".format(e.errno, e.strerror))
        app_exit(1)

    log.info('Getting configuration of XML {}.'.format(xmlfile))
    try:
        cfg = get_cfg(xmlfile)
    except IOError as e:
        log.error("I/O error({0}): {1}".format(e.errno, e.strerror))
        app_exit(1)

    # processing of XML using configuration

if __name__ == '__main__':
    main()


texts:
What's the best way to format a number?

If decimal is less than 2 digits, add zero to make it 2 decimals
If more than 4, truncate to 4 decimals
If 3 decimals, keep it to 3 decimals

14 => 14.00
14.1 => 14.10
14.123 => 14.123
14.12347 => 14.1234

I don't want rounding to happen

if (number !== 0) {
    nParts = number.toString().split('.');
    if (nParts[1]) {
      if (nParts[1].length > 4) {
        nParts = 4;
      } else if (nParts[1].length < 3) {
        nParts = 2;
      } else {
        nParts = 3;
      }
    } else {
      nParts = 2;
    }
}
number = number.toFixed(nParts);

Help me improve on this.


texts:
Whenever using ArrayList, the method containsAll(collection) runs in time \$\mathcal{O}(mn)\$, where \$n\$ is the size of ArrayList and \$m\$ is the length of collection. However, it relies only on equals(Object)-method.

I have this subclass of ArrayList that does the same in time \$\mathcal{O}(n)\$, but relies on hashCode() as well.

My main question, should I do this optimization at expense of adding more requirements?

MyArrayList.java:

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * This class provides a faster {@link #containsAll(java.util.Collection) }
 * method.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6
 * @param <E> the actual element type.
 */
public class MyArrayList<E> extends ArrayList<E> {

    /**
     * Returns {@code true} if this list contains all elements in {@code coll}
     * and {@code false} otherwise.
     *
     * @param  coll the collection to check for inclusion in this list.
     * @return {@code true} if this list contains all elements in
     *         {@code coll}:
     */
    @Override
    public boolean containsAll(Collection<?> coll) {
        Set<?> set = new HashSet<>(coll);

        for (E element : this) {
            if (set.contains(element)) {
                set.remove(element);

                if (set.isEmpty()) {
                    return true;
                }
            }
        }

        return false;
    }

    public static void main(final String... args) {
        List<Integer> jdkList = new ArrayList<>();
        List<Integer> myList  = new MyArrayList<>();

        for (int i = 0; i < 1000000; ++i) {
            jdkList.add(i);
            myList.add(i);
        }

        Random rnd = new Random();
        Collection<Integer> coll = new ArrayList<>();

        for (int i = 0; i < 1000; ++i) {
            coll.add(rnd.nextInt(myList.size()));
        }

        // Uncomment for failing test.
        //coll.add(-1);

        long ta = System.currentTimeMillis();

        boolean result = jdkList.containsAll(coll);

        long tb = System.currentTimeMillis();

        System.out.println("ArrayList.containsAll() in " + (tb - ta) + " ms. " +
                           "Result: " + result);

        ta = System.currentTimeMillis();

        result = myList.containsAll(coll);

        tb = System.currentTimeMillis();

        System.out.println("MyArrayList.containsAll() in " + (tb - ta) +
                           " ms. Result: " + result);
    }
}


texts: Using lock with value type (multithread context)

texts:
I have to use value type to lock code sections in correspondence to objects identifiers (i.e. Guid, int, long, etc.).

So I've written the following generic class/method, which uses a Dictionary to handle object that is a reference in correspondence to the value type (so this objects can be used with the lock instruction).

I think the code and comments are self-explanatory enough.

public static class Funcall<TDataType, T>
{
    // Object used for lock instruction and handling a lock counter
    class LockObject
    {
        public int Counter = 0;
    }
    // Correspondance table between the (maybe) value type and lock objects
    // The TDatatype above allows to create an independant static lockTable for each given TDatatype
    static Dictionary<T, LockObject> lockTable = new Dictionary<T, LockObject>();

    static LockObject Lock( T valueToLockOn )
    {
        lock ( lockTable ) // Globally locks the table
        {
            // Create the lock object if not allready there and increment the counter
            if ( lockTable.TryGetValue( valueToLockOn, out var lockObject ) == false )
            {
                lockObject = new LockObject();
                lockTable.Add( valueToLockOn, lockObject );
            }
            lockObject.Counter++;

            return lockObject;
        }
    }

    static void Unlock( T valueToLockOn, LockObject lockObject )
    {
        lock ( lockTable ) // Globally locks the table
        {
            // Decrement the counter and free the object if down to zero
            lockObject.Counter--;
            if ( lockObject.Counter == 0 )
                lockTable.Remove( valueToLockOn );
        }
    }

    public static void Locked( T valueToLockOn, Action action )
    {
        var lockObject = default( LockObject );

        try
        {
            // Obtain a lock object
            lockObject = Lock( valueToLockOn );

            lock ( lockObject ) // Lock on the object (and so on the corresponding value)
            {
                // Call the action
                action?.Invoke();
            }
        }
        finally
        {
            // Release the lock
            Unlock( valueToLockOn, lockObject );
        }
    }

    // Same as above except this is returning a value (Func instead of Action)
    public static TResult Locked<TResult>( T valueToLockOn, Func<TResult> action )
    {
        var lockObject = default( LockObject );

        try
        {
            lockObject = Lock( valueToLockOn );

            lock ( lockObject )
            {
                return action == null ? default( TResult ) : action();
            }
        }
        finally
        {
            Unlock( valueToLockOn, lockObject );
        }
    }
}

Which can be used like this:

Guid anObjectId = ObtainTheId();
return Funcall<AnObjectClass, Guid>.Locked( anObjectId, () =>
{
    // do something
    return something;
} );

Are there better ways to do that? Any advice is welcome.

Edit/note: as asked in the comments, the use case is the following

This "lock" system is to be used by a module for which the entry points are dedicated to modify stored objects of a particular type (this object type will be modified by this module only). Externally the module is used by several concurrent workers.

More specifically, I use MongoDB 3.4 for objects storage and it does not provides transactions which are new in version 4.0 (I mean here session.Start, session.Commit).
Among that, I don't really need a full/complete transactional system, but simply ensure each step of the workers demands are each consistent at the time each demand occurs.
I'm aware that this simple "lock" system can be considered as weak, but it is simple and meet my need in the context I am working on.