texts:
For flexing my newly acquired Django & Python muscles, I have set up a mobile content delivery system via Wap Push (Ringtones, wallpapers, etc).

The idea is that a keyword comes in from an sms via an URL, let's say  the keyword is "LOVE1" and the program should search if this keyboard points to a Ringtone or an Image. For this I have created a parent model class called "Categoria" (Category) and two subclasses "Ringtone" and "Wallpaper". This subclasses have a variable called "archivo" (filename) which points to the actual path of the content.

Dynpath is a dynamic URL which has been created  to download the content, so it is available only for X amount of time. After that a Celery scheduled task deletes this dynamic URL from the DB.

I have a piece which has "code smell" which I would like to have some input from everyone here.

Model

class Contenido(models.Model):
    nombre = models.CharField(max_length=100)
    fecha_creacion = models.DateTimeField('fecha creacion')
    keyword = models.CharField(max_length=100)

class Ringtone(Contenido):
    grupo = models.ManyToManyField(Artista)
    archivo = models.FileField(upload_to="uploads")

    def __unicode__(self):
        return self.nombre

class Wallpaper(Contenido):
    categoria = models.ForeignKey(Categoria)
    archivo = models.ImageField(upload_to="uploads")

    def __unicode__(self):
        return self.nombre

class Dynpath(models.Model):
    created = models.DateField(auto_now=True)
    url_path = models.CharField(max_length=100)
    payload = models.ForeignKey(Contenido)
    sms = models.ForeignKey(SMS)

    def __unicode__(self):
        return str(self.url_path)

View

Here is my view which checks that the Dynamic URL exists and here is where the code (which works) gets a little suspicious/ugly:

    def tempurl(request,hash):
        p = get_object_or_404(Dynpath, url_path=hash)
        try:
            fname = str(p.payload.wallpaper.archivo)
        except DoesNotExist:
            fname = str(p.payload.ringtone.archivo)

        fn = open(fname,'rb')
        response = HttpResponse(fn.read())
        fn.close()
        file_name = os.path.basename(fname)
        type, encoding = mimetypes.guess_type(file_name)
        if type is None:
            type = 'application/octet-stream'
        response['Content-Type'] = type
        response['Content-Disposition'] = ('attachment; filename=%s') % file_name
        return response

I am talking explictitly this snippet:

      try:
            fname = str(p.payload.wallpaper.archivo)
        except DoesNotExist:
            fname = str(p.payload.ringtone.archivo)

I would have loved to do something like:

fname = p.payload.archivo

But it would not let me do that, from the docs:

Django will raise a FieldError if you override any model field in any ancestor model.

I took a look at generics, but could not make it work with them. Any ideas on a better way of doing this?


texts: Use of static factory methods for vectors and matrices library

texts:
I've been working on a Java-based mathematics library focusing on vectors and matrices. I plan to use it for an important upcoming project, so the classes are analogous to data types available in GLSL (e.g. Vector2 for GLSL's vec2, Matrix4 for GLSL's mat4, and so on).

I'm trying to only expose interface to clients (e.g. Vector2) and keep implementation classes package-private (e.g. Vector2f). I'm trying to use the static factory methods and, since I'm using Java 1.8, I'm trying to take advantage of the new option that allows static methods to be added to interfaces.

However, there's something I currently don't like too much and I'm wondering if there's a way to improve the code design to address it.

Here's what the interface looks like (I've omitted the non-static methods for brevity because they're not relevant to the question):

public interface Vector2 extends Measurable, Bufferable {

    static Vector2 createZeroVector() {
        return Vector2f.createZeroVector();
    }

    static Vector2 createFrom(float x, float y) {
        return Vector2f.createFrom(x, y);
    }

    static Vector2 createFrom(double x, double y) {
        return Vector2f.createFrom(x, y);
    }

    static Vector2 createFrom(final float[] values) {
        return Vector2f.createFrom(values);
    }

    static Vector2 createFrom(final double[] values) {
        return Vector2f.createFrom(values);
    }

    static Vector2 createNormalizedFrom(float x, float y) {
        return Vector2f.createNormalizedFrom(x, y);
    }

    static Vector2 createNormalizedFrom(double x, double y) {
        return Vector2f.createNormalizedFrom(x, y);
    }

    static Vector2 createNormalizedFrom(final float[] values) {
        return Vector2f.createNormalizedFrom(values);
    }

    static Vector2 createNormalizedFrom(final double[] values) {
        return Vector2f.createNormalizedFrom(values);
    }

    // ... non-static methods omitted ...
}

I'll briefly note that:

final class Vector2f implements Vector2 {
    // details omitted
}

Since the interface methods are static, they must be implemented in the interface itself. Classes implementing the interface don't get overrides because this can be resolved at compile time.

However, if a client goes ahead and does something like this:

public class Vector2d implements Vector2 {
    // a double-precision implementation
}

and then tries to use the interface as intended:

// ...
Vector2 vec = Vector2.createFrom(5f, 3f);

Then there seem to be at least 2 problems:

the interface knows about a specific implementation and can only return Vector2f instances, and
a client expecting a Vector2d implementation class gets a Vector2f instead!

Since the methods in the interface are static, there seems to be no way for the client to actually get an instance of the hypothetical Vector2d implementation without changing the interface itself.

How can I improve the code's design in order to resolve this problem for clients?

I've read other articles and I'm not aware of something else that might be helpful here, though I might be wrong.


texts:
Problem: You are given a board containing lower-case letters and a word that you have to form. You can only take the letters from the front or the back, hence you have to rotate the board left or right. You have to use the greedy approach (choose which rotation lets you take the letter the fastest on each turn) and get a list of rotations necessary to get the word.

Example:

Initial Condition: Board: a g t c f  word: cat
Rotate Right -> f a g t c
Take c -> f a g t
Rotate Left -> a g t f
Take a -> g t f
etc

Code:

        public static List<Move> SolveLetterBoard(List<char> board, string word)
        {
            List<Move> result = new List<Move>();

            for (int i = 0; i < word.Length; i++)
            {
                char curChar = word[i];

                int leftPosition = board.IndexOf(curChar);
                int rightPosition = board.LastIndexOf(curChar);

                int location = 0;
                int where = leftPosition;
                Direction howToSpin = Direction.Left;

                //Is it easier to spin to the right or to the left
                if (board.Count - rightPosition <= leftPosition)
                {
                    where = board.Count - rightPosition - 1;
                    location = board.Count - 1;
                    howToSpin = Direction.Right;
                }

                Move curMove = new Move(howToSpin);
                for (int j = 0; j < where; j++)
                {
                    result.Add(curMove);

                    //Spin the board
                    char temp = board[location];
                    board.RemoveAt(location);
                    board.Insert(board.Count - location, temp);
                }

                //Remove the letter
                curMove = new Move(howToSpin, curChar);
                board.RemoveAt(location);

                result.Add(curMove);
            }

            return result;
        }

The code works, but I was told by the interviewer that the code "Your final code showed some lack of best practices", without any elaboration.
Could someone please advise what I did wrong.


texts:
I am trying to detect whether a condition is being returned true or false. The only problem is, I have a bunch of if/else statements. Is it possible to refactor this in less lines? Maybe a for loop or re-writing my markup?

$(document).on('click', '.cert-modal-btn', function(event) {
event.preventDefault();

        var $this  = $(this);
    certNcv        = $this.data("ncv"),
    certDealer     = $this.data("cert"),
    certExpress    = $this.data("express"),
    certOne        = $this.data("dealone"),
    certPromise    = $this.data("iscustomer"),
    certEcomm      = $this.data("isecomm"),
    $tabbedMenu    = $('.tabbed-menu').find('li'),
    $certsDescription = $('.certs-description').find('li');

if(certNcv) {
    console.log("certNcv is true");
    $tabbedMenu.eq(0).removeClass('hidden-item');
    $certsDescription.eq(0).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(0).addClass('hidden-item');
    $certsDescription.eq(0).addClass('hidden-item');
}
if (certExpress == "X") {
    console.log("certExpress is X");
    $tabbedMenu.eq(1).removeClass('hidden-item');
    $certsDescription.eq(1).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(1).addClass('hidden-item');
    $certsDescription.eq(1).addClass('hidden-item');
}
if(certEcomm) {
    console.log("certEcomm is true");
    $tabbedMenu.eq(2).removeClass('hidden-item');
    $certsDescription.eq(2).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(2).addClass('hidden-item');
    $certsDescription.eq(2).addClass('hidden-item');
}
if(certOne) {
    console.log("certOne is true");
    $tabbedMenu.eq(3).removeClass('hidden-item');
    $certsDescription.eq(3).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(3).addClass('hidden-item');
    $certsDescription.eq(3).addClass('hidden-item');
}
if(certPromise) {
    console.log("certPromise is true");
    $tabbedMenu.eq(4).removeClass('hidden-item');
    $certsDescription.eq(4).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(4).addClass('hidden-item');
    $certsDescription.eq(4).addClass('hidden-item');
}
if(certDealer) {
    console.log("certDealer is true");
    $tabbedMenu.eq(5).removeClass('hidden-item');
    $certsDescription.eq(5).removeClass('hidden-item');
}
else {
    $tabbedMenu.eq(5).addClass('hidden-item');
    $certsDescription.eq(5).addClass('hidden-item');
}
// console.log(certNcv);
// console.log(certDealer);
 });


texts:
Here's a constexpr hash function, that will pack a string into the largest unsigned integral type available. So, what do you think?
#include <climits>

#include <cstdint>

#include <utility>

#include <iostream>

namespace detail
{

template <typename T, std::size_t ...I>
constexpr T hash(char const* const s, std::size_t const N,
  std::index_sequence<I...>) noexcept
{
  return ((T(s[I < N ? I : 0]) << ((I < N ? I : 0) * CHAR_BIT)) | ...);
}

}

template <typename T = std::uintmax_t>
constexpr T hash(char const* const s, std::size_t const N) noexcept
{
  return detail::hash<T>(s, N, std::make_index_sequence<sizeof(T)>());
}

template <typename T = std::uintmax_t, std::size_t N>
constexpr T hash(char const(&s)[N]) noexcept
{
  return hash<T>(s, N - 1);
}

int main()
{
  std::cout << (hash("a") == 'a') << std::endl;

  return 0;
}

https://wandbox.org/permlink/KbPiWJc434xYLL3q


texts:
I wrote a class that extends the dict class to provide indexing like functionality, so I can find which key(s) map to a given value in the dict. It's pretty bare bones and there are a lot of things I haven't fleshed out like docstrings (will add these later when I have a final version), how to handle unhashable elements (it currently just fails, but this might be changed in the future), etc.

The extremely bare bones nature of this is because this is something I whipped up in a few minutes for immediate use.

from collections import defaultdict  # The class currently doesn't exist in a separate module, and there are many other imports used by surrounding code.

# Do something

class DoubleDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.values_dict = defaultdict(lambda: [])
        for key, value in self.items():
            self.values_dict[value] += [key]

    def __setitem__(self, key, value):
        var = self.get(key)
        if var in self.values_dict:
            self.values_dict[var].remove(key)
            if not self.values_dict[var]:
                del self.values_dict[var]
        super().__setitem__(key, value)
        self.values_dict[value] += [key]

    def index(self, value):
        return self.values_dict[value][-1]

    def indices(self, value):
        return self.values_dict[value]

# Do Something

My concerns are to have this be as performant as feasible, and sane and generally correct (there may be some unavoidable tradeoffs) approach. I would probably make this into its own module after incorporating feedback.


texts: Calculating a base price with surcharge conditions

texts:
The following code has a lot of conditionals. I am trying to write
it in a functional programming way.

val basePrice = {
  var b = 0.0

  if (runtime > 120)
    b += 1.5
  if ((day == Sat) || (day == Sun))
    b += 1.5
  if (!isParquet)
    b += 2
  if (is3D)
    b += 3
  b
}

I think the following code would be a good approach, but maybe I am
complicating this too much.

val basePrice = {
  List((runtime > 120, 1.5),
       (day == Sat || day == Sun, 1.5),
       (!isParquet, 2.0),
       (is3D, 3.0)).foldLeft(0.0)((acum, cond) =>
     if (cond._1) acum + cond._2 else acum)
}

How would you write the first snippet of code using functional
programming?


texts:
still new to java and i am trying to improve my understanding and use of OOP concepts.here i am supposed to print the name of a randomly selected card from a deck of 52 cards.

Program:

/*
 * RandomCard.java
 * -------------------
 * Displays the name of a card randomly chosen from a complete deck of 52
 * playing cards.
 */

 import java.util.Random;

 public class RandomCard {
    /* Instance Variables */
    private Random rgen = new Random(); /* random generator */

    /**
     * Display the name of a randomly selected card from a deck of 52 cards
     */
    public static void main(String [] args) {
        System.out.println("This program displays a randomly chosen card");
        Card randomCard = selectCardFromDeckRandomly();
        System.out.println(randomCard);
    }

    /*
     * Randomly select a card from a card deck
     * @ return The selected card
     */
    private Card selectCardFromDeckRandomly() {
        String rank = selectRanomCardRank();
        String suit = selectRandomCardSuit();
        return (new Card(rank, suit));
    }

    /*
     * Randomly select a card rank
     * @ return the selected card rank
     */
    private String selectRanomCardRank() {
        String cardRank;
        int r = 1 + rgen.nextInt(13);
        switch (r) {
        case 1:
            cardRank = "Ace";
            break;
        case 2:
            cardRank = "2";
            break;
        case 3:
            cardRank = "3";
            break;
        case 4:
            cardRank = "4";
            break;
        case 5:
            cardRank = "5";
            break;
        case 6:
            cardRank = "6";
            break;
        case 7:
            cardRank = "7";
            break;
        case 8:
            cardRank = "8";
            break;
        case 9:
            cardRank = "9";
            break;
        case 10:
            cardRank = "10";
            break;
        case 11:
            cardRank = "Jack";
            break;
        case 12:
            cardRank = "Queen";
            break;
        default:
            cardRank = "King";
            break;
        }
        return cardRank;
    }

    /*
     * Randomly select a card suit
     * @ return The selected card suit
     */
    private String selectRandomCardSuit() {
        String cardSuit;
        int s = 1 + rgen.nextInt(4);
        switch (s) {
        case 1:
            cardSuit = "Clubs";
            break;
        case 2:
            cardSuit = "Diamonds";
            break;
        case 3:
            cardSuit = "Hearts";
            break;
        default:
            cardSuit = "Spades";
            break;
        }
        return cardSuit;
    }
}

class Card:

/*
 * Card.java
 * -------------
 * Creates a playing card of certain Rank and Suit.
 * This class is part of exercises 1 solution.
 * This program is intended as a practice on programming methodologies.
 */

 public class Card {
    /* Instance variables */
    private String rank;   /* The card rank : Ace,2,3,4,5,6,7,8,9,10,Jack,Queen,King */
    private String suit;   /* The card suit : Clubs, Diamonds, Hearts, Spades */

    /* Constructor */
    /**
     * Creates an instance object of class Card with the specified rank and suit
     * @param rnk The rank of the card
     * @param sut The suit of the card
     */
    public Card(String rnk, String sut) {
        rank = rnk;
        suit = sut;
    }

    public String toString() {
        return (rank + " of " + suit);
    }
}

Note: still not in a position to use arrays.

Evaluation points:

Encapsulation
Top-Down design (refactoring)
Readability and complexity reduction
Object oriented
Documentation


texts: Automate the Boring Stuff with Python 2nd Edition - Sandwich Maker Practice Project

texts:
I am in learning process, even though its a very easy project, I still want experts to please review it and share the improvement that can be done, if anyone wants to use other modules to shorten the code then you can also use them, I already thank you to the people who wants to spend their precious time for this. other beginners will also find it helpful.
import pyinputplus as pyp

menu = True

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}
while menu:
    # options to select bread, protein, cheese with inputMenu() method
    bread = pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True)

    protein = pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True)

    cheese = pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')
    cheese_type = ''
    if cheese == 'yes':
        cheese_type = pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True)

    # using inputYesNo() for single ingredients with no further types
    mayo = pyp.inputYesNo('Do you want mayo?(Y/N) \n')
    mustard = pyp.inputYesNo('Do you want mustard?(Y/N) \n')
    lettuce = pyp.inputYesNo('Do you want lettuce?(Y/N) \n')
    ketchup = pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0

    # using for loop to print items, prices and adding their amount to total_amount variable
    for item, price in prices.items():
        if bread == item:
            print(f'Your sandwich ingredients and prices are as follows: \n'
                  f'{item}= {price}')
            total_amount += price

        if protein == item:
            print(f'{item}= {price}')
            total_amount += price

        if cheese_type == item:
            print(f'{item}= {price}')
            total_amount += price

    # for items that have yes and no values stored and also adding their amount to total
    if mayo == 'yes':
        print(f"mayo = {prices['mayo']}")
        total_amount += prices['mayo']

    if mustard == 'yes':
        print(f"mustard = {prices['mustard']}")
        total_amount += prices['mustard']

    if lettuce == 'yes':
        print(f"lettuce = {prices['lettuce']}")
        total_amount += prices['lettuce']

    if ketchup == 'yes':
        print(f"ketchup = {prices['ketchup']}")
        total_amount += prices['ketchup']

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    order_confirm = pyp.inputYesNo('Please confirm your order: (Y/N)\n')
    if order_confirm == 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        menu = False


texts:
I think I solved the following problem. However, I was wondering if there was a faster or more efficient way to solve this.

I believe the the runtime is O(n) and space is O(1)  (O(256) assuming ASCII)

# Longest substring with at most 2 distinct characters
#
# Given a string S, find the length of the longest substring T that contains at most 2 distinct characters
#
# For example,
#     Given S = "eceba"
#     T is "ece" which it's length is 3

def longest_substring(string):
    if string is None or len(string) == 1 or len(string) == 0:
        return 0
    distinct_set = set()
    longest = 0
    current = 0
    for i in string:
        set_len = len(distinct_set)
        if set_len < 2:
            if i in distinct_set:
                current += 1
            if i not in distinct_set:
                distinct_set.add(i)
                current += 1
        if set_len == 2:
            if i in distinct_set:
                current += 1
            if i not in distinct_set:
                distinct_set.clear()
                distinct_set.add(i)
                if current > longest:
                    longest = current
                current = 1
        if current > longest:
            longest = current
    return longest

Input:

test_cases = [None, "", "a", "ab", "aab", "bab", "babc", "bbbbcccac"]

Output:

0, 0, 0, 2, 3, 3, 3, 7


texts:
I have the following code which takes 10-15 minutes to execute. That is way too slow considering that my database is growing daily. Is there any chance to make it faster?

# Replace all empty lists ([], '[]') in dataframe with NaN's
df = df.mask(df.applymap(str).eq('[]'))

# Replace all zeros in dataframe with NaN's
df[df == 0.0] = np.nan

# Replace empty strings in dataframe with NaN's
df.replace('', np.nan, inplace=True)

# Replace all strings with value 'null' in a dataframe with NaN
df.replace('null', np.NaN, inplace=True)


texts: Finding pairs that add up to a given sum, using recursion

texts:
I'm currently tasked with using recursion to find pairs that add up to a given sum. How would I make the function recursiveFixedSumPairs function more efficient and truncate this code? Also, what is the current runtime? I believe it is n since it will go through the array only once always starting at the first index.

public class HW4 {

    public static void main(String[] args) {

        int[] a = {1, 5, 8, 11, 14, 15, 20, 23, 25, 28, 30, 34};
        int k;
        k = 43;
        System.out.println("k = " + k);
        findFixedSumPairs(a, k);
    }

    public static void findFixedSumPairs(int[] a, int k) {
       recursiveFixedSumPairs(a, -1, 0, k);
    }

    private static void recursiveFixedSumPairs(int[] array, int subPair1, int index, int k) {
//        // pairs whose sum equals k are printed in this method
//        if ((array[subPair1] + array[subPair2]) == k) {
//            System.out.println("[" + array[subPair1] + ", " + array[subPair2] + "]");
//        } else if ((array[subPair1] + array[subPair2]) > k) {
//            recursiveFixedSumPairs(array, subPair1, subPair2 - 1, k);
//        } else {
//            recursiveFixedSumPairs(array, subPair1 + 1, subPair2, k);
//        }

            if (index == array.length) {
                return;
            }

            else if (index == array.length-1) {

                if (subPair1!= -1 && subPair1 + array[index] == k) {
                    System.out.println(""+subPair1 +" "+ array[index]);
                }

                else {
                    return;
                }
            }

            if (subPair1 != -1) {

                if (array[index] == k- subPair1) {
                    System.out.println(""+subPair1 +" "+ array[index]);
                    return;
                } else {
                    recursiveFixedSumPairs(array, subPair1, index + 1, k);
                }

            } else {
                recursiveFixedSumPairs(array, array[index], index+1, k);
                recursiveFixedSumPairs(array,-1, index+1, k);
            }
        }
}


texts: What would be preferred aesthetically and performance wise?

texts:
Which one of these two would you prefer writing in your code?

This:

tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", "");

tweet = tweet.replaceAll("\n", " ");

tweet = tweet.replaceAll("[^\\p{L}\\p{N} ]+", " ");

tweet = tweet.replaceAll(" +", " ").trim();

Or this:

tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", "")
                .replaceAll("\n", " ")
                .replaceAll("[^\\p{L}\\p{N} ]+", " ")
                .replaceAll(" +", " ")
                .trim();

Which one looks cleaner (in my opinion the second one but it obstructs you from commenting every line if you wanted to) and which one should perform better? (my guess is that there is no difference since regex doesn't create a new string everytime and it does everything internally if I am correct)

Additional Information:

Using one .replaceAll() is not possible because if the content that I want to be removed is not removed in this order then the output will be wrong.

Here is a short compilable example:

public class StringTest {

    public static void main(String args[]) {
        String text = "RT @AshStewart09: Vote for Lady Gaga for \"Best Fans\""
                + " at iHeart Awards\n"
                + "\n"
                + "RT!!\n"
                + "\n"
                + "My vote for #FanArmy goes to #LittleMonsters #iHeartAwards\n"
                + "for ART!"
                + "htt… è, é, ê, ë asdf324 ah_";
        System.out.println("Before: " + text + "\n");

        text = text.replaceAll("@\\w+|#\\w+|\\bRT\\b", "")
                .replaceAll("\n", " ")
                .replaceAll("[^\\p{L}\\p{N} ]+", " ")
                .replaceAll(" +", " ").trim();

        System.out.println("After: " + text + "\n");
    }
}

I have tried merging some of the .replaceAll() but the output was always wrong if I did the operations in any other order than this. In the end I want to be left with just the words of the tweet and nothing else. Bare in mind that this is the first time I'm using regex so I am far from a pro at it so if there actually is a way to merge them then do tell.

This is the closest I'm currently at merging the replaceAll():

text = text
    .replaceAll("@\\w+|#\\w+|\\bRT\\b|\n|[^\\p{L}\\p{N} ]+", " ")
    .replaceAll(" +", " ")
    .trim();

I basically made everything a space and then removed all the extra spaces. Is that better than before? Is it even possible to merge the last replaceAll as well?


texts: Allow adding errors and warnings and remove both after a while with seperate timers

texts:
I use this in my Blazor application, letting other services send errors or warnings to this AlertService. The service triggers an update of a component which simply displays the messages, errors in red warnings in yellow.
While getting no new warnings, the existing warnings should be deleted, every 5 seconds one less warning being displayed. Same goes for errors.
When a new warning comes in, the timer restarts (so when the service was 1 second before deleting a warning, that timer is now void and the new timer starts with 5 seconds again).
This is my class, I feel there must be a better way but I haven't figured it out yet:
    public class AlertService
{
    private readonly ObservableCollection<string> errors = new ObservableCollection<string>();
    private readonly ObservableCollection<string> warnings = new ObservableCollection<string>();
    private object? talkingStickErrors;
    private object? talkingStickWarnings;

    public ReadOnlyObservableCollection<string> Errors { get; }

    public ReadOnlyObservableCollection<string> Warnings { get; }

    public AlertService()
    {
        Errors = new ReadOnlyObservableCollection<string>(errors);
        Warnings = new ReadOnlyObservableCollection<string>(warnings);
    }

    public void Error(string message)
    {
        Console.WriteLine($"Error: {message}");
        errors.Add(message);
        StartErrorTimer();
    }

    private void StartErrorTimer()
    {
        talkingStickErrors = new object();
        RemoveErrorAfterDelay(talkingStickErrors);
    }

    private async void RemoveErrorAfterDelay(object localTalkingStick)
    {
        while (true)
        {
            await Task.Delay(5000);
            if (localTalkingStick != talkingStickErrors || !errors.Any()) return;
            errors.RemoveAt(0);
        }
    }

    public void Warning(string message)
    {
        Console.WriteLine($"Warning: {message}");
        warnings.Add(message);
        StartWarningTimer();
    }

    private void StartWarningTimer()
    {
        talkingStickWarnings = new object();
        RemoveWarningAfterDelay(talkingStickWarnings);
    }

    private async void RemoveWarningAfterDelay(object localTalkingStick)
    {
        while (true)
        {
            await Task.Delay(5000);
            if (localTalkingStick != talkingStickWarnings || !warnings.Any()) return;
            warnings.RemoveAt(0);
        }
    }
}

Also I couldn't think of a better word for the talking sticks. They're not exactly locks.
Update: No more talking sticks, it now just reused the last message it received.
Update 2: Talking sticks again, as string have no unique identity.
Update 3: Instead of an extra event, the alerts are now in ObservableCollections. I keep receiving stuff about encapsulation and Rx. ould appreciate someone helping me to DRY this.


texts:
I've just started iOS development and learning Swift. My code below works, but I'm interested to know in ways I can improve it having no experience in iOS Swift prior to this attempt.

import UIKit
class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableView: UITableView!
var titleItems: NSMutableArray = []
var descritpionItems: NSMutableArray = []

/*
class to get data from API
*/
class RemoteAPI {

    // base url
    let baseUrl = "http://api.dev/web/"
    var newsTitle: NSMutableArray = []
    var newsDescription: NSMutableArray = []

    func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void {
        // get news feed url
        let url = NSURL(string: baseUrl + "news")
        // create session
        let session = NSURLSession.sharedSession()
        // set task
        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
            if (error != nil) {
                return completionHandler(nil, error)
            }

            var error: NSError?
            // convert data object to json
            let json = JSON(data: data)

            for var i = 0; i < json.count; ++i {
                // get news title from json object
                var title = json[i]["title"].string
                var blurb = json[i]["description"].string
                // add to dictionary
                self.newsTitle.addObject(title!)
                self.newsDescription.addObject(blurb!)
            }

            if (error != nil) {
                return completionHandler(nil, error)
            } else {
                return completionHandler([self.newsTitle,self.newsDescription], nil)
            }
        })
        task.resume()

    }
}

// get data
var api = RemoteAPI()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.view.frame = CGRect(x: 0, y: 50, width: 320, height: 480)
    self.tableView = UITableView(frame:self.view!.frame)
    self.tableView!.delegate = self
    self.tableView!.dataSource = self
    self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.view?.addSubview(self.tableView)

    api.getData({data, error -> Void in
        if (data != nil) {
            self.titleItems = self.api.newsTitle
            self.descritpionItems = self.api.newsDescription
            self.tableView!.reloadData()
        } else {
            println("API failed :-(")
            println(error)
        }
    })
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    return self.titleItems.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    var cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")

    if let newsTitle = self.titleItems[indexPath.row] as? NSString {
        cell.textLabel?.text = newsTitle
    }
    if let newsDesc = self.descritpionItems[indexPath.row] as? NSString {
        cell.detailTextLabel?.text = newsDesc
    }
    return cell
}
}


texts: Product of corresponding elements in 2 arrays

texts:
Given two arrays A and B, of length N and length k respectively, if we move B over A and take the sum of product of corresponding elements of A and B, then find the minimum of those sum of products.

For example, if A=[2,3,4,5] and B=[1,3], then after moving B over A, we get 3 possible values [2*1+3*3, 3*1+4*3, 4*1+3*5], max of which is 19.

I tried coding for this and reached an \$O(n^2)\$ solution. Can I reduce the algorithm's complexity here?

My code in Python:

A=[2,3,4,5]
B=[1,3]
print max([sum([A[i+j]*B[j] for j in xrange(len(B))]) for i in xrange(len(A)-len(B)+1)])


texts: Eliminating files that are completely contained within other files

texts:
I have a block of code that is really bugging me but I can't figure out how to clean it up. I have a list of objects which are all related. In fact some of them are complete supersets of one or more others.

To identify the 'Dupes' which are completely contained within other files, I am comparing every file against every other. Once a file is flagged as a dupe it doesn't need to be included in the comparisons anymore.

The function isbetter determines when a file is a superset.

for a in self.files:
    if not a.isDupe:
        for b in self.files:
            if  a != b and not b.isDupe:
                if a.isbetter(b):
                    b.isDupe = a.name

I'm sure there is a very pythonic way to simplify this.


texts:
This is my second attempt to create asynchronous version of AutoResetEvent.
At first I tried to make it completely lock-less, but it turned out to be impossible.
This implementation contains a lock however the lock isn't an instance wide:

/// <summary>
///     Asynchronous version of <see cref="AutoResetEvent" />
/// </summary>
public sealed class AutoResetEventAsync {
    private static readonly Task<bool> Completed = Task.FromResult(true);

    private readonly ConcurrentQueue<TaskCompletionSource<bool>> handlers =
        new ConcurrentQueue<TaskCompletionSource<bool>>();

    private int isSet;

    /// <summary>
    ///     Initializes a new instance of the <see cref="AutoResetEventAsync" /> class with a Boolean value indicating whether to set the intial state to signaled.
    /// </summary>
    /// <param name="initialState">true to set the initial state signaled; false to set the initial state to nonsignaled.</param>
    public AutoResetEventAsync(bool initialState) {
        this.isSet = initialState ? 1 : 0;
    }

    /// <summary>
    ///     Sets the state of the event to signaled, allowing one waiting continuation to proceed.
    /// </summary>
    public void Set() {
        if (!this.TrySet())
            return;

        TaskCompletionSource<bool> handler;

        // Notify first alive handler
        while (this.handlers.TryDequeue(out handler))
            if (CheckIfAlive(handler)) // Flag check
                lock (handler) {
                    if (!CheckIfAlive(handler))
                        continue;

                    if (this.TryReset())
                        handler.SetResult(true);
                    else
                        this.handlers.Enqueue(handler);

                    break;
                }
    }

    /// <summary>
    ///     Try to switch the state to signaled from not signaled
    /// </summary>
    /// <returns>
    ///     true if suceeded, false if failed
    /// </returns>
    private bool TrySet() {
        return Interlocked.CompareExchange(ref this.isSet, 1, 0) == 0;
    }

    /// <summary>
    ///     Waits for a signal asynchronously
    /// </summary>
    public Task WaitAsync() {
        return this.WaitAsync(CancellationToken.None);
    }

    /// <summary>
    ///     Waits for a signal asynchronously
    /// </summary>
    /// <param name="cancellationToken">
    ///     A <see cref="P:System.Threading.Tasks.TaskFactory.CancellationToken" /> to observe while waiting for a signal.
    /// </param>
    /// <exception cref="OperationCanceledException">
    ///     The <paramref name="cancellationToken" /> was canceled.
    /// </exception>
    public Task WaitAsync(CancellationToken cancellationToken) {
        // Short path
        if (this.TryReset())
            return Completed;

        cancellationToken.ThrowIfCancellationRequested();

        // Wait for a signal
        var handler = new TaskCompletionSource<bool>(false);

        this.handlers.Enqueue(handler);

        if (CheckIfAlive(handler)) // Flag check
            lock (handler)
                if (CheckIfAlive(handler) && this.TryReset()) {
                    handler.SetResult(true);
                    return handler.Task;
                }

        cancellationToken.Register(() => {
            if (CheckIfAlive(handler)) // Flag check
                lock (handler)
                    if (CheckIfAlive(handler))
                        handler.SetCanceled();
        });

        return handler.Task;
    }

    private static bool CheckIfAlive(TaskCompletionSource<bool> handler) {
        return handler.Task.Status == TaskStatus.WaitingForActivation;
    }

    private bool TryReset() {
        return Interlocked.CompareExchange(ref this.isSet, 0, 1) == 1;
    }
}

Any suggestions?


texts: Longest Common Prefix in an array of Strings

texts:
Please be brutal, and treat this as if I was at an interview at a top 5 tech firm.

  Question: Write a function to find the longest common prefix string
  amongst an array of strings.

Time it took: 17 minutes

Worst case complexity analysis: n possible array elements, each can have length m that we are traversing, hence O(n*m); m could be a constant, since it's rare to find a string with length, so in a sense, I imagine this could be treated as O(n *constant length(m)) = O(n)?

Space complexity analysis: O(n)

public String longestCommonPrefix(String[] strs) {
    String longestPrefix = "";
    if(strs.length>0){
        longestPrefix = strs[0];
    }
    for(int i=1; i<strs.length; i++){
        String analyzing = strs[i];
        int j=0;
        for(; j<Math.min(longestPrefix.length(), strs[i].length()); j++){
            if(longestPrefix.charAt(j) != analyzing.charAt(j)){
                break;
            }
        }
        longestPrefix = strs[i].substring(0, j);
    }
    return longestPrefix;
}


texts: Rest Controller in Spring Boot for Rock Paper Scissors REST API

texts:
I have created a Spring Boot Microservice for playing Rock Paper Scissrors. I have tried to follow best practices, but still would appreciate some critique on my code. Thanks.

@RestController
public class RockPaperScissorsController {

  @Autowired
  private PlayerService playerService;

  @Autowired
  private HttpServletRequest context;

  @Autowired
  private GameSessionService gameSessionService;

  @Autowired
  private GameplayService gameplayService;

  public RockPaperScissorsController(PlayerService playerService,
      GameSessionService gameSessionService) {
    this.playerService = playerService;
    this.gameSessionService = gameSessionService;
  }

  @GetMapping(value = "/ping", produces = "application/json")
  public ResponseEntity<String> ping() {
    return ResponseEntity.ok("{\"response\":\"pong\"}");
  }

  @GetMapping(value = "/player/{playerName}", produces = "application/json")
  public ResponseEntity player(@PathVariable("playerName") String playerName) {
    try {
      Player player = playerService.getPlayer(playerName);
      return ResponseEntity.ok(player);
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @PostMapping(value = "/player/{playerName}", produces = "application/json")
  public ResponseEntity playerPOST(@PathVariable("playerName") String playerName) {
    try {
      playerService.createPlayer(playerName);
      return ResponseEntity.ok().body("");
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @DeleteMapping(value = "/player/{playerName}", produces = "application/json")
  public ResponseEntity playerDELETE(@PathVariable("playerName") String playerName) {
    try {
      playerService.deletePlayer(playerName);
      return ResponseEntity.ok("");
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @PostMapping(value = "/createInvite/{playerName}", produces = "application/json")
  public ResponseEntity createInvite(@PathVariable("playerName") String inviter) {
    try {
      Player player = playerService.getPlayer(inviter);
      GameSession session = gameSessionService.createSessionFrom(new Invite(player));
      return ResponseEntity.ok(session);
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @PostMapping(value = "/acceptInvite/{inviteCode}/{playerName}", produces = "application/json")
  public ResponseEntity acceptInvite(@PathVariable("inviteCode") String inviteCode,
      @PathVariable("playerName") String playerName) throws InvalidOperationException {
    try {
      Player player = playerService.getPlayer(playerName);
      return ResponseEntity.ok(gameSessionService.acceptInvite(player, inviteCode));
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @GetMapping(value = "/session/{inviteCode}", produces = "application/json")
  public ResponseEntity session(@PathVariable("inviteCode") String inviteCode) {
    return ResponseEntity.ok(gameSessionService.sessions().get(inviteCode));
  }

  @PostMapping(value = "/readyplayer/{playername}", produces = "application/json")
  public ResponseEntity ready(@PathVariable("playername") String playerName) {
    try {
      Player player = playerService.changePlayerState(playerName, Player.State.READY);
      return ResponseEntity.ok(player);
    } catch (RPSException e) {
      return ResponseEntity.badRequest().body(e.getMessage());
    }
  }

  @PostMapping(value = "/play", produces = "application/json")
  public ResponseEntity play(@RequestBody PlayRequest playRequest) {
    try {
      gameplayService.play(playRequest);
      return ResponseEntity.ok().body("");
    } catch (RPSException e) {
      e.printStackTrace();
    }
    return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body("");
  }

}


texts: Given a string and a word dict, find all possible sentences

texts:
I have been trying to figure out how to meet space and time complexity requirements for the following leet code question. I have come up with two versions, one that meets the time requirements and another that meets the space requirements. Both versions fail on the same test case (the last test case shown below). Can anyone suggest how to reconcile both space and time requirements? What am I missing?
Question and examples

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
add spaces in s to construct a sentence where each word is a valid dictionary word. Return
all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]

Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]

Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]

Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]

Output:
[]

Code that fails time limit
class Solution:
    def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':
        if not wordDict:
            return []

        wD = set(wordDict)
        max_offset = len(max(wD, key=len))
        paths = []

        def dfs(st, path):
            if st == len(s):
                paths.append(path)
                return

            for en in range(st + 1, st + max_offset + 1):
                if s[st:en] in wD:
                    dfs(en, path + [(st, en)])

        dfs(0, [])
        return [' '.join([s[x[0] : x[1]] for x in path]) for path in paths]

Code that fails space limit
class Solution:
    def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':
        from collections import defaultdict

        if not wordDict:
            return []

        wD = set(wordDict)
        memo = defaultdict(list)
        memo[len(s)] = [[(len(s), len(s) + 1)]]

        for i in range(len(s) - 1, -1, -1):
            for j in range(i + 1, len(s) + 1):
                if s[i:j] in wD and j in memo:
                    for l in memo[j]:
                        memo[i].append([(i, j), *l])
        return [' '.join([s[ind[0] : ind[1]] for ind in x[:-1]]) for x in memo[0]]

Testing (the last test case fails each of the above versions)
import pprint

inps = [
    ("catsanddog", ["cat", "cats", "and", "sand", "dog"]),
    ("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"]),
    ("catsandog", ["cats", "dog", "sand", "and", "cat"]),
    ("a", ['a']),
    ("abc", ['abc', 'a', 'b', 'c']),
    ("hellow", []),
    (
       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
       [
           "a",
           "aa",
           "aaa",
           "aaaa",
           "aaaaa",
           "aaaaaa",
           "aaaaaaa",
           "aaaaaaaa",
           "aaaaaaaaa",
           "aaaaaaaaaa",
       ],
    ),
]

sol = Solution()
for s, wd in inps:
    print(f"Doing s[{s}] and wd[{wd}]...")
    ans = sol.wordBreak(s, wd)
    pprint.pprint(ans)


texts:
Short and sweet...

I wrote a cross-thread method that displays the countdown [in seconds] of a delay on a label.

I'm fairly confident it's far from optimal, so I'm in need of that glorious optimization advice.

private async Task SnoozeAsync(int seconds)
{
    for (var i = 0; i < seconds; i++)
    {
        Invoke((MethodInvoker)(() => statusLabel.Text = $"Waiting {seconds - i} seconds..."));
        await Task.Delay(1000);
    }
}

await SnoozeAsync(60);


texts: jQuery function to select user specified text within a div

texts:
I'm very new to jQuery, and have recently converted one JavaScript function to jQuery. This function is part of a small utility that mimics click and drag for selection of text. Complete code is available on my github repo. Following is the screenshot of the utility.

The purpose of the code is to allow user to select text by entering the desired text in target text input, hitting the select button calls the getSelection function to select the target text within sentence div.

JavaScript

getSelection = function(){
  sentence = document.getElementById("sentence");
  target= document.getElementById("target");
  selection = window.getSelection();
  range = document.createRange();
  index = sentence.innerHTML.indexOf(target.value);
  range.setStart(sentence.firstChild,index);
  range.setEnd(sentence.firstChild,(index + target.value.length));
  selection.removeAllRanges();
  selection.addRange(range);
}

jQuery

$(document).ready(function(){
  $("#getSelection").click(function(){
    sentence = $("#sentence")[0];
    target= $("#target")[0];
    selection = window.getSelection();
    range = document.createRange();
    index = sentence.innerHTML.indexOf(target.value);
    range.setStart(sentence.firstChild,index);
    range.setEnd(sentence.firstChild,(index + target.value.length));
    selection.removeAllRanges();
    selection.addRange(range);
  });
});

Additional Info

Question: Having little knowledge of jQuery I'm concerned whether I'm doing everything right? Please let me know.


texts:
I have a working Tic-Tac-Toe game, which requires two players. The game also keeps track of the result of each game and assigns score to each player based on the result of the game.

For this, I have made use of structures:

Player Structure

typedef struct
{
    int score[10];
    char choice;
    char name[10];
    bool turn;

}Player;

Game Structure

I have made use of another structure for the game setup, which contains the game board, the valid positions available, and also the number of games played:

typedef struct
{
    char board[3][3];
    bool validPos[10];
    int games;

}Game;

main function

 // included only a part of the main function that I am concerned about;
int main(void)
{
    Game *game = malloc(sizeof(Game));
    Player *player_1 = malloc(sizeof(Player));
    Player *player_2 = malloc(sizeof(Player));
}

Functions used in the game:

void assignXO(Player *, Player *);
void startGame(Game *, Player *, Player *);
void display(Game *, Player *, Player *);
bool victoryCheck(Game *);
bool isComplete(Game *);
void playerMove(Game *, Player *);
void declareWinner(Game *, Player *, Player *);
void gameReset(Game *);
void scoreBoard(Player *, Player *, int);

Queries

As you can observe the number of arguments passed to the functions are dependent on the purpose of the function. Is it wise to declare global variables for the structure so that potentially no arguments are needed to be passed to any of the functions?
Is it good practice to have more than 2 arguments passed to the functions? Does it help with conveying the logic to the reader?
If I used the structure Player within the Game structure, will it make the code any better in terms of readability and how well the code is organised?


texts: Python making call list for C++ executable

texts:
I have a text file which contains configuration values that are intended to be arguments to a C++ executable (to be read in as a vector in C++). I am using a Python script to read in the text file and then call the C++ executable as a subprocess. The reason I'm doing it via Python is because I do not want to modify the C++ executable for unrelated reasons.

Here is my code snippet to achieve this. I was wondering if there's a better way to do this.

call_list = [executable, "--directory", directory, "--filePrefix", file_prefix, "--configList"]

# read config file
config_file = directory + file_prefix + ".txt"
config_list = [line.strip() for line in open(config_file)]

config_list_split = []
for config in config_list:
    config_list_split.extend(config.split())

call_list.extend(config_list_split)

subprocess.check_call(call_list)


texts: Shell script to download and extract a tarball from GitHub

texts:
I don't want anything to execute if any preceding step fails:

#!/bin/sh

file="v0.9"
renamed=$file".tar.gz"
dir="utils/external/firepython/"
location="https://github.com/darwin/firepython/tarball/$file"

wget --no-check-certificate $location --output-document=$renamed && \
mkdir -p $dir && \
gunzip $renamed && \
echo "extracting to $dir" && \
tar xf $file".tar" --directory $dir --strip-components 1 && \
echo "Cleaning up..." && \
rm -r $file".tar" && \
echo "Done"


texts: Are redundancy and reflection my only options here?

texts:
I have a function - TriggerNotifications - that accepts a NotificationType.  The Type determines which settings I should pull from the User.

The code looks like this:

public void TriggerNotification(DbContext db, User user, NotificationType type, string content) {
            switch (type) {
                case NotificationType.Followed:
                    CreateNotification(db, user, user.Followed, content);
                    return;
                case NotificationType.Unfollowed:
                    CreateNotification(db, user, user.Unfollowed, content);
                    return;
                case NotificationType.Messaged:
                    CreateNotification(db, user, user.Messaged, content);
                    return;
                default:
                    throw new InvalidDataContractException("Invalid Notification Type");
            }
        }

So the only purpose of this method is to determine which settings should be used.  Every User has a property matching each of the enum NotificationTypes.

I think this is a good use case for reflection, but want to ask if there's any other way to reduce redundancy here.  I don't like reflection because it's not as straightforward to debug, and it's slow (right?).

UPDATE

CreateNotification:

private void CreateNotification(DbContext db, User user, NotificationSetting setting, string content) {
        // send email, notification, or both
        if (setting.Equals(NotificationSetting.None))
            return;
        var notification = new Notification() {
            UserId = user.userId
            Description = content,
            Email = email,
        };

        if (setting.Equals(NotificationSetting.Email) || setting.Equals(NotificationSetting.Both)) {
            // tell worker role to pick it up
            notification.PendingEmail = true;
        }

        // signalR stuff here

        db.Add(notification);
    }

User:

public class User : Settings {
      // other stuff
}

Settings:

public abstract class Settings {
    // notifications
    public NotificationSetting Followed { get; set; }
    public NotificationSetting Unfollowed { get; set; }
    public NotificationSetting Messaged { get; set; }
}

NotificationSetting:

// values stored in the db for each setting property - messaged, unfollowed, etc
public enum NotificationSetting {
    Navbar,
    Email,
    Both,
    None
}

NotificationType:

// values used in logic only to tell the notification builder which setting to pull
public enum NotificationType {
    Followed,
    Unfollowed,
    Messaged
}


texts: Mechanism to retry failed requests, with throttling

texts:
I have a simple event that the client sends to the server, the server can then respond saying if it was successful, or if it failed for some reason.

The client has to send a auth code, which is inside their config class. Below I attempt to throttle it, allowing 2 attempts, then reloading the config after the 2nd failed attempt.

If it still fails 2 more attempts after reloading the config, I throttle it for 60 seconds. If it fails after reloading the config 3 or more times (12 requests), then I just refuse to resend it.

Please note that I understand just leaving it and not warning the user why it failed to connect to the server is wrong, but I haven't finished with that code yet, and will adapt later on.

I'm just looking to see if its okay, and if I can improve it in any way.

public class HandshakeFailedEvent : IIncomingPacketEvent
{
    private static int ATTEMPTS_BEFORE_CONFIG_RELOAD = 2;
    private static int ATTEMPTS_BEFORE_THROTTLE = 4;
    private static int SECONDS_TO_THROTTLE = 60;

    private int _timesFailed;
    private int _timesSinceReset;

    public void Process(ICoreContext coreContext, IIncomingPacket packet)
    {
        if (packet.GetInteger("error_code") == 1) // WRONG_PASSWORD
        {
            CheckForThrottle(coreContext);
        }

        // Other error codes may need fixing, not throttling, handle here.

        coreContext.SocketHandler.SendPacket(new HandshakeRequestComposer(coreContext.ConfigHandler));
    }

    private void CheckForThrottle(ICoreContext coreContext)
    {
        _timesFailed++;
        _timesSinceReset++;

        if (_timesFailed >= ATTEMPTS_BEFORE_THROTTLE * 3)
        {
            // Application.Restart();
            return;
        }

        if (_timesSinceReset >= ATTEMPTS_BEFORE_CONFIG_RELOAD && _timesSinceReset < ATTEMPTS_BEFORE_THROTTLE)
        {
            coreContext.ConfigHandler.Download();
        }
        else if (_timesSinceReset >= ATTEMPTS_BEFORE_THROTTLE)
        {
            Task.Delay(SECONDS_TO_THROTTLE * 1000).ContinueWith((t) => { _timesSinceReset = 0; });
        }
    }
}


texts:
I'm working on a CTags plugin for Sublime Text. One of the open issues revolves around the fact that an in-memory sort of a tag file can cause some form of memory or buffer overflow errors (the stack in Sublime Text is limited to ~25 MB apparently). I've devised a simple external bucket sort to resolve this issue:

#/usr/bin/env python
#
# CSV external bucket sort

import codecs
import tempfile
import os

# column indexes
SYMBOL = 0
FILENAME = 1

TAG_FILE = 'tags'
OUT_FILE = ''.join([TAG_FILE, '_sorted_by_file'])

def sort():
    """External bucket sort of tab delimited CTag files"""
    temp_files = {}

    def get_file(filename):
        """Get a file from the store of files"""
        if not filename in temp_files:
            temp_files[filename] = tempfile.NamedTemporaryFile(delete=False)
            # close and reopen using codecs to avoid problems described here:
            #   http://stackoverflow.com/a/10490859/613428
            temp_files[filename].close()
            temp_files[filename] = codecs.open(
                temp_files[filename].name, 'w+', 'utf-8', 'ignore')
        return temp_files[filename]

    try:
        with codecs.open(TAG_FILE, 'r+', 'utf-8', 'ignore') as file_o:
            for _ in range(6):  # skip the header
                next(file_o)
            for line in file_o:
                temp_file_o = get_file(line.split('\t')[FILENAME])
                split = line.split('\t')
                split[FILENAME] = split[FILENAME].lstrip('.\\')
                temp_file_o.write('\t'.join(split))

        with codecs.open(OUT_FILE, 'w+', 'utf-8', 'ignore') as file_o:
            # we only need to sort the file names - the symbols were already
            # sorted!
            for key in sorted(temp_files):
                temp_files[key].seek(0)
                file_o.write(temp_files[key].read())
    finally:
        for key in temp_files:
            temp_files[key].close()
            os.remove(temp_files[key].name)

    os.remove(OUT_FILE)  # just for testing - remove when done

Here's what I intended to do:

For each line (a.k.a. tag) in a tag file
    Read line into memory
    Get the filename from the line.
    Use filename as key to a temp file and write whole this line to said file
Sort final list of keys (i.e. filenames)
For each file in sorted key list
    Append contents of file to sorted tag file
Close all files and delete temp files

And the performance:

$ python -m timeit -n 100 'import external_sort; external_sort.sort()'
100 loops, best of 3: 12 msec per loop

My question is this: is this as performant as it could be? Could I improve it in any way, e.g. missing corner cases?

NOTE: I'm aware that it's not really a true bucket sort as the buckets aren't arbitrary or equally sized (a project with many small files and few large files would result in unbalanced buckets). However, I'm counting on there being many average sized files and none big-enough to fill memory by themselves.


texts:
I wrote the following suffixes function. Given a list, it returns the list + all sub-lists.

  suffixes [1,2,3,4] == [[1,2,3,4], [2,3,4], [3,4], [4], []]

Please critique my implementation.

suffixes :: [a] -> [[a]]
suffixes []         = [] : []
suffixes xxs@(_:xs) = xxs : suffixes xs


texts:
This was inspired by Aggregate loans report without using Python standard aggregate or group functions question, but I've decided to approach it using pandas.

To recap, sample input:

MSISDN,Network,Date,Product,Amount
1,Network 1,12-Mar-2016,Loan Product 1,1000
2,Network 2,16-Mar-2016,Loan Product 1,1122
3,Network 3,17-Mar-2016,Loan Product 2,2084
4,Network 3,18-Mar-2016,Loan Product 2,3098
5,Network 2,01-Apr-2016,Loan Product 1,5671

Desired output:

Network,Product,Month\Year,Currency,Count
Network 1,Loan Product 1,03-16,1000,1
Network 2,Loan Product 1,03-16,1122,1
Network 2,Loan Product 1,04-16,5671,1
Network 3,Loan Product 2,03-16,5182,2

In other words, the task is to group the data from the input.csv file by Network, Product and month+year of the Date column, then calculate the sum of Currency column keeping track of counts in each group.

I've solved it via creating a separate Month\Year column first, loading the Date values into datetime objects and dumping into a month-year format, then grouping by the desired columns using .groupby() and then aggregating with sum and count with further renaming the columns to the desired column names:

from datetime import datetime

import pandas as pd

df = pd.read_csv('input.csv')
df['Month\Year'] = df['Date'].apply(lambda s: datetime.strptime(s, "%d-%b-%Y").strftime('%m-%y'))

grouped = df.groupby(['Network', 'Product', 'Month\Year'])['Amount']

df = grouped.agg(['sum', 'count']).rename(columns={'sum': 'Currency', 'count': 'Count'}).reset_index()
df.to_csv('output.csv', index=False)

Is this the most optimal and readable pandas-based solution? Can it be further improved?

I am particularly not quite happy with renaming columns after aggregation - there should be a more straightforward way to aggregate into the custom-named columns.


texts: Joining a product-application-customer relationship using Java 8 Streams

texts:
I have three classes: product, customer and application.

The schema of these classes are as follows:

class application {
     String productID;
     String customerID;
     String applicationId;
     String name;
 ....
  // getters and setters and associated constructors
}

class product {
    String name;
    String ID;
    ...
  // constructors and getters and setters
 }

class customer {
    String name;
    String ID;
    ...
    // constructors and getters and setters
}

The only way of connection between product and customer is through the application.

The problem in hand is to retrieve all products with their associated customers (appID and customerID) in this JSON format.

 [
   {
   "product": {
         // product details
    }
   "customers": [ {
         "application": <value_appID>,
         "ID": <value_customerID> } ]
  }
]

I have done this using a nested for loop:

for (Product product : products) {
    ProductInfo prodInfo = new
    ProductInfo();
    prodInfo.setProduct(product);
    List<CustomerInfo> associatedCustomerList = new ArrayList<>();
    for (Object res : searchResults.getResult()) {
        if ((product.getId()).equals((String) ((Map) res).get("productID"))) {
            CustomerInfo associatedCustomer = new CustomerInfo();
            associatedCustomer.setCustomerID((String) ((Map) res).get("customerID"));
            associatedCustomer.setApplicationId((String) ((Map) res).get("appId"));
            associatedCustomerList.add(associatedCustomer);
        }
        prodInfo.setCustomers(associatedCustomerList);
    }
    productInfo.add(prodInfo);
}

Here, searchResults contain the result from List<? extends Object>. CustomerDetails contain appId and customerId as attributes. ProductInformationWithAssociatedCustomer is the response class.

Furthermore, I have converted this into the following which utilizes Java 8 Stream API:

 List<ProductInfo> prodList = products.stream()
    .map(product -> {
        List<CustomerInfo> customerList =searchResults.getResult().stream()
            .filter(searchResult -> (product.getId()).equals((String) ((Map) searchResult).get("productID")))
            .map(searchResult -> new CustomerInfo((String) ((Map) searchResult).get("customerID"),(String) ((Map) searchResult).get("appId")))
            .collect(Collectors.toList());
        return new ProductInfo(product, customerList);
    }).collect(Collectors.toList());

This code is working fine.

The questions I have are:

Am I making correct/ optimal use of Java 8 stream features?
Provided, I want to do it using Java 8 Stream APIs only, should I do it in any better way?
What are the factors I need to consider while optimizing this type of codes.


texts:
The Tower Hopper problem gives us an array of values representing heights that express how far we can jump from a certain tower, and asks whether there's a way to get from tower[0] (0 indexed) to outside of the array.

For ex, if we have towers = [4, 2, 0, 0, 2, 0], we can jump from towers[0] to towers[4] and then outside of the bounds of the array. Or we could jump from towers[0] to towers[1] to towers[4] and then out of the array.
But if we had towers = [4, 2, 0, 0, 1, 0], there would be no way to hop out of the array and we should return False.

I wrote a recursive function that starts from the last array index.

I'm concerned that the way I wrote the function is not the most efficient. It seems to work but I'm thinking I might not have to pass in that many arguments. I very much welcome any other kind of criticism (style, syntax, design...).

I was also wondering (but maybe I should post this as another question) how to turn this into a dynamic programming format. Hints on how to do that (rather than a straight up solution) would be greatly appreciated.

int main(int argc, char const *argv[])
{

    int num_towers = 6;

    int towers[6] = {5, 4, 3, 3, 1, 0};

    printf("These towers are %s\n", is_hoppable(towers, num_towers - 1, num_towers) ? "hoppable" : "NOT hoppable");

    return 0;
}

int is_hoppable(int* towers, int jumpTower, int targetTower){

    if (jumpTower == 0){
        if (jumpTower + towers[jumpTower] >= targetTower)
            return 1;
        else
            return 0;
    }

    if (jumpTower + towers[jumpTower] >= targetTower)
        return is_hoppable(towers, jumpTower - 1, jumpTower);
    else
        return is_hoppable(towers, jumpTower - 1, targetTower);

}


texts: Levenshtein Distance of transitively similar words

texts:
The code's purpose is this: Two words are friends if they have a Levenshtein distance of 1. That is, you can add, remove, or substitute exactly one letter in word X to create word Y. A word’s social network consists of all of its friends, plus all of their friends, and all of their friends’ friends, and so on. Count the friends in the social network of a certain word.

My code is implemented using the Trie written by Steve Hanov. His code is here: http://stevehanov.ca/blog/index.php?id=114.

What I did was this:

social_links = set_up_dictionary_from_text('dictionary.txt')
tree = Trie()
for i in social_links:
    tree.insert(i)
def find(keyword):
    neighbors = [keyword]
    already_in_set = set()
    while len(neighbors) > 0:
        if neighbors[-1] not in already_in_set:
            temp = neighbors[-1]
            already_in_set.add(neighbors.pop())
            current_neighbors = search(tree, temp)
            neighbors.extend(current_neighbors)
        else:
            already_in_set.add(neighbors.pop())
    return(len(already_in_set))

This code works, but runs over 8 minutes for files that are over 100,000 words. Is there something I'm doing wrong? Or should I not use Python for this?


texts: Character Creation in Text Adventure; Proper use of Main and Global Values?

texts:
I'm still learning python so I decided to experiment by making a tiny text adventure. I'm only a student in highschool so I haven't had the chance to learn many common techniques used in code as most of my learning has been self taught, so I wanted to take this opportunity to have some kind of review of some of the techniques I use in this code.

Here it is in it's entirety:

class Character:
    def __init__(self, class_name, strength, dexterity, intelligence):
        self.class_name = class_name
        self.strength = strength
        self.dexterity = dexterity
        self.intelligence = intelligence
        self.health = strength*10

    def print_stats(self):
        return self.class_name + " Strength: " + str(self.strength) + " Dexterity: " + str(self.dexterity) + " Intelligence: " + str(self.intelligence)

    def print_stat_strength(self):
        return "Strength: " + str(self.strength)

    def print_stat_dexterity(self):
        return "Dexterity: " + str(self.strength)

    def print_stat_intelligence(self):
        return "Intelligence: " + str(self.strength)

    def print_stat_health(self):
        return "Max Health: " + str(self.health)

    def change_stat_strength(self, new_value):
        self.strength = new_value

    def change_stat_dexterity(self, new_value):
        self.dexterity = new_value

    def change_stat_intelligence(self, new_value):
        self.intelligence = new_value

def character_select():
    global player_class
    barbarian = Character("Barbarian", 20, 10, 10)
    archer = Character("Archer", 10, 20, 10)
    wizard = Character("Wizard", 10, 10, 20)

    print("Welcome to TEST TEXT ADVENTURE RPG. Choose a character!")
    print("(A): " + barbarian.print_stats())
    print("(B): " + archer.print_stats())
    print("(C): " + wizard.print_stats())

    while True:
        user_answer = input().upper()
        if user_answer == "A":
            player_class = barbarian
            break
        elif user_answer == "B":
            player_class = archer
            break
        elif user_answer == "C":
            player_class = wizard
            break
        else:
            print("Invalid input! Try again.")
    print("####CHARACTER CREATION COMPLETE####")

def main():
    character_select()
    print(player_class.print_stats())

main()

Looking at this, my main concern is how the main function is utilized. To my knowledge it is supposed to be relatively clean and made up of other functions, lacking a lot of original code of its own. Making the above, I came into an issue trying to use the player_class object that I created, since it was created in the character_select function, it could only be used there unless it was global. The global fix seems kind of clunky so I was wondering the proper way to implement this kind of thing.

One other concern that I can identity could be the built in functions in the Character class. Do I need to make a separate function for every single stat like strength, dexterity, intelligence, or is it possible to do something like this?

def change_stat(self, stat_to_change, new_number):
    self.stat_to_change = new_number

Now I'm asking this question because I tried the above code on my own to try to cut down on the amount of similar functions for each individual stat, but I couldn't seem to use it how I imagined.

Those are my main concerns but anybody reading this is welcome to bring up any other improper coding technique. I really don't want bad habits to manifest themselves and continue to appear if I can help it.


texts: Determining whether two two-digit numbers share a digit in common

texts:
I have solved a CodingBat problem: Given two ints, each in the range 10..99, return true if there is a digit that appears in both numbers, such as the 2 in 12 and 23. (Note: division, e.g. n/10, gives the left digit while the % "mod" n%10 gives the right digit.)

shareDigit(12, 23) → true
shareDigit(12, 43) → false
shareDigit(12, 44) → false

My working code is:

public boolean shareDigit(int a, int b) {
      boolean answer = false;
      int lefta = a/10;
      int righta = a % 10;
      int leftb = b/10;
      int rightb = b % 10;
      if(lefta == leftb || lefta == rightb || righta == leftb || righta == rightb){
        answer = true;
      }
      return answer;
}

It feels extremely inefficient, and I was wondering if anyone could improve it.


texts:
I am looking for a starting point to code plugins, primarily  for Zepto.js (with fall back for jQuery). These will provide reusable functions for Tumblr theming.

However, I can't seem to find anything in depth about writing a plugin (with Zepto) as the example, apart from a small snippet on the Zepto site: http://zeptojs.com/

The code below is pieced together from reading various 'jQuery' plugin tutorials, but I am not 100% sure how solid it is.

;(function($){
    $.extend($.fn, {
        pluginName: function(el, options) {
            // Set defaults
            this.defaults = {
                option: 'option',
                onComplete: function() {}
            };
            // Combine defaults / options
            var settings = $.extend({}, this.defaults, options);
            // Do stuff
            $.each(this, function() {

            });
            // Call back if needed
            settings.onComplete.call(this);
            // Return `this` for chain ability
            return this;
        }
    });
}(window.Zepto || window.jQuery));

According to the Zepto documentation, my plugins method will be added to the Zepto object. Is this acceptable?

I would also like the option to use private / public functions contained in the plugin for flexibility.

I apologise if my questions come across as confusing or novice, but any help / improvements would be greatly appreciated.


texts: Count the number of vowelgroups in a string

texts:
I've written a function that can count the vowel groups in a string.

def count_vowelgroups(woord):
    if woord[0].lower() in 'aeiouy':
        output = 1
    else:
        output = 0

    for i in range(1, len(woord)):
        if woord[i].lower() in 'aeiouy' and woord[i-1].lower() not in 'aeiouy':
            output += 1
    return output

It works fine, but not really pythonic! Who can help?

For example:

print(count_vowelgroups('Hello everyone!'))
6
print(count_vowelgroups('Alright'))
2
print(count_vowelgroups('Whaaaaaat!?'))
1
print(count_vowelgroups('Je pense donc je suis.'))
6


texts: Using a factory class for TextWriter than can be stubbed/mocked

texts:
This is my factory class:

/// <summary>
/// Inject TextWriterFactory into the class you need to test
/// In the unit test, use SetWriter() to set a different TextWriter (ex: StringWriter)
/// Add extra overloads for Create method if needed
/// </summary>
public class TextWriterFactory {
    private TextWriter _writer = null;
    public TextWriter Create(string path, bool append) {
        if (_writer != null)
            return _writer;

        return new StreamWriter(path, append);
    }

    public void SetWriter(TextWriter writer) {
        _writer = writer;
    }
}

This is how it's used in my test methods:

[TestMethod]
public void Test() {
    ...
    var textWriterFactory = new TextWriterFactory();
    textWriterFactory.SetWriter(new StringWriter());
    // inject into the class I am testing
}

And in my production code:

public void DoSomething() {
    using (TextWriter writer = _textWriterFactory.Create(template.LocalTempFilePath, false))
        writer.Write(template.FileContent);
    ...
}

Does that seem ok to you or is there a better way? I plan to use this everywhere in my code that needs to be tested. I'm using moq framework and SystemWrapper for other mscorlib methods I need to stub/mock.


texts:
I'm simulating a system of particles which interact with each other and move and rotate due to the interaction.  There are 2000 particles in total but each particle interacts with other particles and their image (I'm using a periodic boundary condition) if particles and their images have distances larger thanl0. I just consider image of particles in 8 near boxes to the main box.

y[N],x[N] are the position of points in the plane; dx[n] and dy[N] their changes in each time step. c shows different time steps. e_x and e_y shows x and y component of direction of each particle respect to x and y-axis.

int main()
{
  unsigned short int N, l0 , R0;
  double rho, v0, eta, dt, a, b, D;
  long c_equilib, c_prod, c_display;
     while (c < 1000000)
            {
         c++;
        for(unsigned short int i=0; i<2000; i++){
          double S_theta=0.0, S_x=0.0, S_y=0.0, S;
                    for(unsigned short int j=0; j<2000; j++)
                    {
                        if (j==i) continue;
                        for(int ky=-1; ky<=1; ky++)
                        {
                            for(int kx=-1; kx<=1; kx++)
                            {
                                double r_x_ij=x[i]-(x[j]+kx*L),
                                    r_y_ij=y[i]-(y[j]+ky*L),
                                r_ij=sqrt(pow(r_x_ij,2.0)+pow(r_y_ij,2.0));
                                if (r_ij >= l0)
                                {
                                    r_x_ij/=r_ij;
                                    r_y_ij/=r_ij;
                                    S_theta += (e_x[i]*e_x[j]+e_y[i]*e_y[j]) / pow(r_ij, 3) * ( 3.0* (r_x_ij*e_x[j]+r_y_ij*e_y[j]) *
                                                            pow(e_x[i]*r_y_ij - e_y[i]*r_x_ij, 2.0) -
                                                            e_x[i]*e_y[j] + e_y[i]*e_x[j] );

                                    S = ( 3.0* pow(r_x_ij*e_x[j]+r_y_ij*e_y[j], 2.0) -1.0 ) / pow(r_ij, 2.0);
                                    S_x += r_x_ij*S;
                                    S_y += r_y_ij*S;
                                }
                            }
                        }
                    }
        }
dx[i] += dt*a*S_x;
            dy[i] += dt*a*S_y;
        }
e_x[i]=cos(theta[i]);
e_y[i]=sin(theta[i]);
x[i]+=dx[i];
y[i]+=dy[i];
}
}

I'm looking to optimize the large loop of this C++ program.  This is one part of my simulation (I have ignored some calculations inside the loop to make the question simpler). This part is extremely time-consuming. How can I make it faster?


texts:
Our database has several tables that have a value that can be one of 4 things, so we made these columns instead have an id column with a foreign key to an enum table with an id and a value column to hold those 4 values. When interfacing this through an ORM, I came up with the following enum-like class to manage keeping things in sync:

using DataAccess.ECI.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace DataAccess.ECI
{

    public class StatusEnum
    {
        private string type;
        private static Dictionary<string, Status> lookupCache = null;
        private static List<StatusEnum> members= new List<StatusEnum>();
        private StatusEnum(string type)
        {
            this.type = type;
            members.Add(this);
        }
        //the text needs to be kept consitent with the Status table
        public static readonly StatusEnum ACTIVE = new StatusEnum("ACTIVE");
        public static readonly StatusEnum COMPLETED= new StatusEnum("COMPLETED");
        public static readonly StatusEnum DELETED= new StatusEnum("DELETED");
        public static readonly StatusEnum INPROGRESS= new StatusEnum("INPROGRESS");

        public static void Init(ECIContext ctx)
        {
            lookupCache=new Dictionary<string, Status>();
            foreach(StatusEnum member in members)
            {
                try
                {
                    lookupCache.Add(member.type, ctx.Status.Single(s => s.Name == member.type));
                }catch(Exception ex)
                {
                    throw new InvalidOperationException($"No record found with Name {member.type}",ex);
                }
            }
        }
        public Status asDBType()
        {
            if (lookupCache == null) throw new InvalidOperationException("Init(ECIContext) has not been called for this enum");
            return lookupCache[type];
        }
        public override string ToString()
        {
            return type;
        }
    }
}

I thought it works pretty well, but I'm concerned about a few things.

since it's mostly static methods, it forces lots of duplication when other enum tables are added that need the same code wrapper
if we forget to call init, this error isn't caught until late in the runtime

I would appreciate any comments on the code and suggestions for how to make it better.

EDIT:

for more context, we are using aspnet core, so the context is added in Startup.cs:ConfigureServices(IServiceCollection services) :

...
services.AddDBContext<ECIContext>(options=>
    options.UseSqlServer(/*connection string from config*/)
);
...

and Init is currently called in Startup.cs:Configure(IApplicationBuilder app,...):

...
ECIContext ctx=app.ApplicationServices.GetService<ECIContext>();
StatusEnum.Init(ctx);
...

this enum will be used like

ctx.Document.add(new Document{
    PageCount=4,
    Status=StatusEnum.ACTIVE.asDBType(),
    ...other properties...
});

which works because our ORM, entity framework core, adds a field for the foreign key linked table, and stores the id when appropriate


texts:
I have a simple app which is checking occurrences of values. If there is already occurrences which I am looking for, it display that. If not, it adds.

create table Strings
(
    StringID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
    , StringValue VARCHAR(100) NOT NULL
)

create table Links
(
    LinkID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
    ,Link VARCHAR(255) NOT NULL
)

CREATE TABLE Occurences
(
    OccurenceID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
    ,StringID INT NOT NULL
    ,LinkID INT NOT NULL
)

Class:

private SqlConnection conn;

public void Open()
{
    this.conn = new SqlConnection();
    this.conn.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
    this.conn.Open();
}

public void Close()
{
    this.conn.Close();
}

public string Obtain(string code)
{
    SqlConnection sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
    SqlCommand sqlCommand = new SqlCommand();
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = code;
    sqlConnection.Open();
    SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
    sqlDataReader.Read();
    string result = sqlDataReader.GetValue(0).ToString();
    sqlConnection.Close();
    return result;
}

public void Insert(string StringID, string LinkID)
{
    SqlConnection sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = @"Server=PC\SQLEXPRESS;Database=example;User=sa;Pwd=example;";
    SqlCommand sqlCommand = new SqlCommand();
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = string.Concat(new string[]
    {
        "INSERT INTO Occurences VALUES ('",
        StringID,
        "', '",
        LinkID,
        "')"
    });
    sqlConnection.Open();
    sqlCommand.ExecuteNonQuery();
    sqlConnection.Close();
}

Button click:

private void button1_Click(object sender, EventArgs e)
{

    try
    {
        sql.Open();
        StringID = sql.Obtain("SELECT StringID from dbo.Strings where StringValue='" + textBox1.Text + "'");
        LinkID = sql.Obtain("SELECT LinkID from dbo.Links where Link='" + textBox2.Text + "'");
        Occurence = sql.Obtain("SELECT OccurenceID from dbo.Occurences where StringID='" + StringID + "' and LinkID = '" + LinkID + "'");
        if (Convert.ToInt32(Occurence) > 0)
        {
            MessageBox.Show(Occurence);
        }
    }

    catch
    {
        sql.Insert(StringID, LinkID);
    }

    finally
    {
        sql.Close();

    }
}

Is this coded well? Should I change my catch to more specific? Should I do something like these?

If there is no StringValue in dbo.Strings then insert StringValue
If there is no Link in dbo.Links then insert Link


texts: Perl module validate quoted string literal, test with Test::LectroTest

texts:
I guess for some motivation: I ripped this out of a larger library I'm half-working on to parse S-expressions and cleaned it up a bit.

I'm trying to write a simple function that tests whether a string is a valid quoted string literal. Using Test::LectroTest to compare a fast version of a function using a regex against a slow version that uses a Perl for loop.

I have a couple complaints / style questions right off the bat:

Is the lib/QuotedString.pm the right place for the accept_string_slow function to live? I don't intend for people to actually use this function, it's just there to support the tests. Is there a way to hide it better?
I can't actually figure out how to influence how LectroTest generates strings. Since it picks characters uniformly at random, I decided the clearest thing to do would be to accept the string it produced but add quotations marks to exercise different edge cases.
The general style is probably bad. I don't write Perl professionally.

Directory layout:

.
|-- lib
|   `-- QuotedString.pm
`-- t
    `-- test_accept_string_generative.t

Here is lib/QuotedString.pm.

package QuotedString;

BEGIN {
    require Exporter;
    @ISA = qw[Exporter];
    @EXPORT_OK = qw[
        accept_string_regex
        accept_string_slow
    ];
};

use strict;
use warnings;

use Readonly;

Readonly my $string_pattern => qr/["](?:[^\\"]|[\\].|[\\]\n)*["]/;

sub accept_string_regex {
    my $string = shift;
    ($string =~ m/\A$string_pattern\z/) ? 1 : 0;
}

sub accept_string_slow {
    my $string = shift;
    return 0 if length($string) < 2;
    return 0 unless $string =~ /\A"/;
    return 0 unless $string =~ /"\z/;

    my $index = 1;
    my $final_checked_char = length($string) - 2;
    while ($index <= $final_checked_char) {
        my $char = substr($string, $index, 1);
        # if we encounter an unescaped ", we fail
        return 0 if $char eq '"';
        # \ consumes the next character fail if there is no next character before final "
        return 0 if $char eq '\\' and $index == $final_checked_char;

        # advance the index two positions if the current char is \
        # because the next one is escaped regardless of what it is
        # if the current character is not \, then advance one position
        if ($char eq '\\') {
            $index += 2;
        } else {
            $index += 1;
        }
    }
    return 1;
}

and the test t/test_accept_string_generative.t

#!/usr/bin/env perl
use strict;
use warnings;
use Test::LectroTest (
    trials => 2000
);

use QuotedString qw[accept_string_regex accept_string_slow];

Property {
    ##[ x <- String ]##
    accept_string_slow($x) eq accept_string_regex($x);
};

Property {
    ##[ x <- String ]##
    accept_string_slow('"' . $x) eq accept_string_regex('"' . $x);
};

Property {
    ##[ x <- String ]##
    accept_string_slow('"' . $x . '"') eq accept_string_regex('"' . $x . '"');
};


texts: Implementation of a threshold detection function in Python

texts:
I want to implement following trigger function in Python:

Input:

time vector t [n dimensional numpy vector]
data vector y [n dimensional numpy vector] (values correspond to t vector)
threshold tr [float]
Threshold type vector tr_type [m dimensional list of int values]

Output:

Threshold time vector tr_time [m dimensional list of float values]

Function:

I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)

For the moment I have next code:

import numpy as np
import matplotlib.pyplot as plt

def trigger(t, y, tr, tr_type):
    triggermarker = np.diff(1 * (y > tr))
    positiveindices = [i for i, x in enumerate(triggermarker) if x == 1]
    negativeindices = [i for i, x in enumerate(triggermarker) if x == -1]
    triggertime = []
    for i in tr_type:
        if i >= 0:
            triggertime.append(t[positiveindices[i - 1]])
        elif i < 0:
            triggertime.append(t[negativeindices[i - 1]])
    return triggertime

t = np.linspace(0, 20, 1000)
y = np.sin(t)
tr = 0.5
tr_type = [1, 2, -2]
print(trigger(t, y, tr, tr_type))
plt.plot(t, y)
plt.grid()

Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.

thanks!


texts:
I wrote this script that downloads an RSS feed and converts it to HTML. One of my only concerns is my variable naming because I suck at naming things.

# -*- coding: utf-8 -*-
"""Simple RSS to HTML converter."""

__version__ = "0.0.2"
__author__ = "Ricky L Wilson"

from bs4 import BeautifulSoup
from feedparser import parse as parse_feed

TEMPLATE = u"""

{title}

{title}
{summary}
"""

def entry_to_html(**kwargs):
    """Formats feedparser entry."""
    return TEMPLATE.format(**kwargs).encode('utf-8')

def convert_feed(url):
    """Main loop."""
    html_fragments = [entry_to_html(**entry) for entry in parse_feed(url).entries]
    return BeautifulSoup("\n".join(html_fragments), 'lxml').prettify()

def save_file(url, filename):
    """Saves data to disc."""
    with open(filename, 'w') as file_object:
        file_object.write(convert_feed(url).encode('utf-8'))

if __name__ == '__main__':
    save_file('http://stackoverflow.com/feeds', 'index.html')
    with open('index.html') as fobj:
        print fobj.read()


texts:
I have a Python script that generates a dictionary of all possible 3 digit password combinations. It essentially works by just nesting for loops. This is fine, but say I wanted to change it so it could generate 4, 5, 6, ... digit combinations. This would require me to keep adding more nested loops and changing the print statement.

How can I make my current code more efficient and apply the DRY principle? This way, if I wanted to change it to generate 4-digit codes, I could simply change a single variable rather then add an entire for loop.

Current code:

f=open('New Text Document.txt','w')
def getCombos(digits, caps, numbers):
    if(caps == True):
        if(numbers == True):
            for x in range(33, 126):
               for y in range(33, 126):
                   for z in range(33, 126):
                       print(chr(x) + "" + chr(y) + "" + chr(z))
                       f.write(chr(x) + "" + chr(y) + "" + chr(z) + "\n")

getCombos(3, True, True)

If I wanted to add a fourth digit:

f=open('New Text Document.txt','w')
def getCombos(digits, caps, numbers):
    if(caps == True):
        if(numbers == True):
            for x in range(33, 126):
               for y in range(33, 126):
                   for z in range(33, 126):
                       for m in range(33, 126):
                       print(chr(x) + "" + chr(y) + "" + chr(z) + "" + char(m))

getCombos(3, True, True)


texts: Node2D and Node3D classes implemented using a shared decorator

texts:
EDIT: I have made another go at this using metaclasses here. I think it's a much better approach.

I have the following classes. validator is a decorator that receives a class which defines validation criteria for a decorated function. ValidateKeys is the validation criteria for this example (other criteria I plan to include later are maximum, minimum, and rounding/decimal places). Node is a parent class with a decorated setter, and Node2D and Node3D are child classes differing only in the validation criteria each uses.

I'm wondering if this is a good solution, if there are problems with doing it this way (i.e., inheritance) that I'm not seeing, etc etc. Any criticism is welcome.

One thing that I don't like, and doesn't seem to make sense, is that I had to move the list of valid keys from the validator to the parent class itself (see old code version below). This doesn't really make sense to me because I'd like to separate the valid list from the implementation of the Node class [the Node class is just and example; I will transform it into something more general, for making Node (valid members: x,y), Element (valid members: i,j,k,l), Boundary (valid member: b) etc etc].

class validator(object):
    def __init__(self, TheValidator, *args, **kwargs):
        print("New validator Object")
        self.TheValidator = TheValidator(*args,**kwargs)
    def __call__(self,f):
        def wrapped_f(instance, *args,**kwargs):
            self.TheValidator(instance, *args, **kwargs)
            return f(instance,*args,**kwargs)
        return wrapped_f

class ValidateKeys(object):
    def __init__(self,*keysIterable):
        print("New ValidateKeys Object")
    def __call__(self, instance, **kwargs):
        for a in kwargs:
            if not a in instance.valid_keys:
                raise Exception()
        instance.__dict__.update(kwargs)

class Node(object):
    def __new__(klass, *valid_keys):
        Node.valid_keys = valid_keys
        return super(Node, klass).__new__(klass)
    @property
    def coords(self):
        return self.__dict__
    @coords.setter
    def coords(self,Coords):
        self.set_coords(**Coords)
    @validator(ValidateKeys)
    def set_coords(self,**Coords):
        pass

class Node3D(Node):
    def __new__(klass):
        return super(Node3D, klass).__new__(klass, 'x','y','z')

class Node2D(Node):
    def __new__(klass):
        return super(Node2D, klass).__new__(klass, 'x','y')

In case it helps make clear what I'm trying to accomplish, an older version of my solution is below prior to creating the Node parent class. I added the parent class to cut down on duplicate code, but to do that I had to refactor a lot, including moving valid_keys from the ValidateKeys class to the Node class.

class validator(object):
    def __init__(self, TheValidator, *args, **kwargs):
        self.TheValidator = TheValidator(*args,**kwargs)
    def __call__(self,f):
        def wrapped_f(instance, *args,**kwargs):
            self.TheValidator(instance, *args, **kwargs)
            return f(instance,*args,**kwargs)
        return wrapped_f

class ValidateKeys(object):
    def __init__(self,*keysIterable):
        self.valid_keys = keysIterable
    def __call__(self, instance, **kwargs):
        for a in kwargs:
            if not a in self.valid_keys:
                raise Exception()
        instance.__dict__.update(kwargs)

class Node3D(object):
    @property
    def coords(self):
        return self.__dict__
    @coords.setter
    def coords(self,Coords):
        self.set_coords(**Coords)
    @Validator(ValidateKeys, 'x','y','z')
    def set_coords(self,**Coords):
        pass

class Node2D(object):
    @property
    def coords(self):
        return self.__dict__
    @coords.setter
    def coords(self,Coords):
        self.set_coords(**Coords)
    @Validator(ValidateKeys, 'x','y')
    def set_coords(self,**Coords):
        pass