texts: Conditionally selecting random element from array

texts:
I'm building a clone of 2048 in C with SDL2, and I'm implementing the function that adds a number randomly to an empty cell on the board. The board is representd by a 2-Dim array board[BOARD_SIZE][BOARD_SIZE], and stores the exponent for the square value(10 for 1024 and so on). There must be a 90% chance of the cell being worth 1 (i.e. 2^1) against 10% of it being 2. Here's how I implemented this

void randCell(int _board[BOARD_SIZE][BOARD_SIZE]) {
    int row;
    int col;
    bool has_space = false;
    // Check if there's any empty spaces
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            if (_board[i][j] == EMPTY) has_space = true;
        }
    }
    // Randomly pick a cell until we find an empty one
    // TODO: Better way to find empty cells.
    if (has_space) {
        do {
            row = randRange(0, BOARD_SIZE - 1);
            col = randRange(0, BOARD_SIZE - 1);
        } while (_board[col][row]);
        // Fill the cell
        _board[col][row] = (randRange(1, 100) < 90) ? 1 : 2;
    }
}

How can I improve this? Could I somehow decrease the number of loops my while performs by only picking a random cell from the EMPTY ones?


texts: Trigger custom implicit conversion on "copy"

texts:
Is there anything horribly wrong with creating different representations of data behind the scenes when constructing a std::vector<T> from a std::vector<U>?

std::vector<Color> initialScene(Settings::HRes * Settings::VRes);

std::vector<Pixel> finalScene(std::begin(initialScene), std::end(initialScene));

With the Pixel(const Color&) constructor doing something along the lines of:

explicit Pixel(const Color& color) {
   // Basically swaps blue and red channels
   data[0] = color.blue;
   data[1] = color.green;
   data[2] = color.red;
}

Note: this is not exactly what the converting constructor does; it's more of an illustration.


texts: How to improve this array manipulation function?

texts:
The function takes 2 arguments: array: int[], cap: int

Members would be ranged from 0 to cap.

e.g.

array = [0,0,0,2,6,3,0,4,2,4,0]
cap = 6

The return value is a new array of same length based on these rules:

The function can only change values of consecutive elements which are > 0.  i.e. any where the original array has 0, the new array has 0 as well.
In a consecutive series of elements which are > 0, if the maximum of it equals cap, then in the new array they are changed to 1,1,...,1,cap of the same length. e.g.  0,2,6,4,0 -> 0,1,1,6,0
In a consecutive series of elements which are > 0, if the maximum of it is smaller than cap, then the elements in the new array are mapped to either 1 or maximum  (if the element value < maximum then 1, otherwise maximum ) . e.g.  0,2,5,5,0 -> 0,1,5,5,0

So the sample array would map to [0,0,0,1,1,6,0,4,1,4,0]

The following are my code which are implemented in both languages, it surprises me that F# takes same lines as C#.

I would like to suggestions to improve either language.

F#

open System

let private reorder cap (array: int[]) =
    if Array.isEmpty array then
        array
    else
        let max = array |> Array.max
        if max = cap then
            let newArray = Array.create array.Length 1
            newArray.[array.Length-1] <- cap
            newArray
        else
            array |> Array.map (fun elem -> if elem = max then max else 1)

let private getZeroes todo =
    todo |> Seq.takeWhile (fun elem -> elem = 0)
         |> Seq.toArray

let private getNumbers todo cap =
    todo |> Seq.takeWhile (fun elem -> elem <> 0)
         |> Seq.toArray
         |> reorder cap

let GetEquivalentPermutation (array: int[], cap) =

    let rec joinParts finished todo =
        if Seq.isEmpty todo then finished |> Seq.toArray
        else
            let zeroes = getZeroes todo
            let nextTodo = todo |> Seq.skip zeroes.Length
            let numbers = getNumbers nextTodo cap
            let finalTodo = nextTodo |> Seq.skip numbers.Length
            let newFinished = Seq.append (Seq.append finished zeroes) numbers
            joinParts newFinished finalTodo

    joinParts [] array

C#

    static int[] EquivalentOutput(int cap, int[] permutation)
    {

        IEnumerable<int> right = permutation;
        List<int> equivalentLine = new List<int>();

        while (right.Any())
        {
            var leftArray = right.TakeWhile(x => x != 0).ToArray();

            List<int> leftEquivalent;
            if (leftArray.Length == 0)
            {
                leftEquivalent = new List<int>();
            }
            else if (leftArray.Length != 1)
            {
                int max = leftArray.Max();
                if (max == cap)
                {
                    leftEquivalent = leftArray.Take(leftArray.Length - 1).Select(x => 1).ToList();
                    leftEquivalent.Add(cap);
                }
                else
                {
                    leftEquivalent = leftArray.Select(x => x < max ? 1 : max).ToList();
                }
            }
            else
            {
                leftEquivalent = leftArray.ToList();
            }
            equivalentLine.AddRange(leftEquivalent);
            equivalentLine.AddRange(right.SkipWhile(x => x != 0).TakeWhile(x => x == 0));
            right = right.SkipWhile(x => x != 0).SkipWhile(x => x == 0);

        }
        return equivalentLine.ToArray();
    }


texts:
My attempt at a simulation of one-handed Solitaire. Any comments welcome!

// Basic implementation of one handed solitaire by Andrew Ewen.
//
// Not sure if working correctly as it wins roughly 1/90 games whereas wikipedia states it
// is closer to 1/140.

function Card (suit, rank) {
    this.suit = suit;
    this.rank = rank;
}

Card.suits = ["Spades", "Hearts", "Clubs", "Diamonds"];
Card.prototype.toString = function () {
    var suit = Card.suits[this.suit];
    var rank = (this.rank + 1).toString();

    switch (this.rank) {
        case 0:
            rank = "Ace";
            break;
        case 10:
            rank = "Jack";
            break;
        case 11:
            rank = "Queen";
            break;
        case 12:
            rank = "King";
            break;
    }

    return rank + " of " + suit;
}

function debugLog(msg) {
    var enabled = false;
    if (enabled) console.log(msg);
}

var deck = function () {
    cards = [];
    // Create deck of cards
    for (var suit = 0; suit < 4; suit++) {
        for (var rank = 0; rank < 13; rank++) {
            cards.push(new Card(suit, rank));
        }
    }

    // Shuffle cards (Fisher-Yates)
    for (var i = cards.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i+1));
        var t = cards[j];
        cards[j] = cards[i];
        cards[i] = t;
    }
    return cards;
};

// Stats
var wins = 0;
var losses = 0;

for(var i = 0; i < 1000000; i++) {
    var pile = deck();
    var hand = [];
    var discard = [];

    var turns = 0;
    var gameOver = false;
    while (!gameOver) {
        debugLog("turn: " + turns++);

        Array.prototype.push.apply(hand, pile.splice(pile.length - 1, 1));
        // Keep drawing cards until there is either non left or we have enough
        while (hand.length < 4 && pile.length > 0) {
            hand.push(pile.pop());
        }

        // Check if we're on our last 2 cards.
        var last2 = hand.length < 4;
        // Always check last card in hand
        var cardA = hand[hand.length - 1];
        // If we're on the last two compare with the first, otherwise compare
        // with 4th from the end.
        var cardB = last2 ? hand[0] : hand[hand.length - 4];

        // Check for matches and discard accordingly
        var match = false;
        if(cardA.suit === cardB.suit) {
            var removed;
            if (last2) {
                removed = hand.splice(0, hand.length);
            } else {
                removed = hand.splice(hand.length - 3, 2);
            }
            Array.prototype.push.apply(discard, removed);
            match = true;
        } else if (cardA.rank === cardB.rank) {
            var removed;
            if (last2) {
                removed = hand.splice(0, hand.length);
            } else {
                removed = hand.splice(hand.length - 4, 4);
            }
            Array.prototype.push.apply(discard, removed);
            match = true;
        }

        if (match) { debugLog("Match: " + cardA + " -> " + cardB); }

        debugLog("hand: " + hand.length);
        debugLog("pile: " + pile.length);
        debugLog("discard: " + discard.length);
        debugLog("");

        // Detect win and loss conditions
        if (pile.length === 0 && !match) {
            debugLog("You lose...");
            losses += 1;
            gameOver = true;
        }
        if (pile.length === 0 && hand.length === 0) {
            debugLog("You win!");
            wins += 1;
            gameOver = true;
        }
    }
    console.log("Win rate: " + (wins/losses));
}


texts: Determine the ratio of the contents of a pot to the (metal) volume of of the pot

texts:
This is my first Python project, so:

create a pot with dimensions (radius, thickness of wall, thickness of base, height), fill it with food (to a specific height). Determine the ratio between the volume of the food and the volume of the (metal in the) pot.

I am aware that this code does not take handles, rims, dents and other funny stuff into consideration.

import math
pi = math.pi
class Pot:
    """create a pot with contents, determine the ratio between the contents and the pot"""

    def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.wall_width = wall_width
        self.inner_radius = inner_radius
        self.outer_radius = self.inner_radius + self.wall_width
        self.base_thickness = base_thickness
        self.height = height
        self.content_height = content_height

    def get_cylinder_volume(self,radius,height):
        cylinder_volume = pi * (radius ** 2) * height
        return cylinder_volume

    def get_pot_wall(self):
        inner_cylinder = self.get_cylinder_volume(self.inner_radius,self.height)
        outer_cylinder = self.get_cylinder_volume(self.outer_radius,self.height)
        pot_wall = outer_cylinder - inner_cylinder
        return pot_wall

    def get_pot_base(self):
        pot_base = self.get_cylinder_volume(self.inner_radius,self.base_thickness)
        return pot_base

    def get_pot_volume(self):
        pot_volume = self.get_pot_base() + self.get_pot_wall()
        return pot_volume

    def get_content(self):
        content = self.get_cylinder_volume(self.inner_radius,self.content_height)
        return content

    def get_ratio(self):
        ratio = self.get_content()/self.get_pot_volume()
        return ratio

    def check_ratio(self,desired):
        if (self.get_ratio() < desired):
            print ("too small")
        else:
            print (self.get_ratio())


texts:
I have these 2 version of code. Both are looking for all primes under a certain ceiling value.
The first is testing against the set of all odd numbers.
The second in testing against the set of all 6k-1 and 6k+1.
In theory, the second version should be faster than the first.
However the result states otherwise.
For under 1 million, the first perform for 1.477835 seconds, while the second perform for 1.521462 seconds.
For under 10 million, the first perform for 30.929565 seconds, while the second perform for 32.825142 seconds.
I have not test these under a different machine.
I could not figure out why I'm getting these results. Because, the second version is suppose to eliminate more composite numbers than the first. However, it perform worse, quite significantly.
I suspect this might be caused by my method of implementation. But even if that were the case, I still wouldn't have the slightest idea of why.
Could it be because of I'm having more nested loops? Or is it to do with memory access? Is it maybe a python's quirk where the implementation details matters? Maybe in some way the first version is simpler and therefore can be easily better optimized by python compared to the second?
If someone could provide some explanations, suggestions, even solutions or alternatives, that would be much appreciated.
#!/usr/bin/env python3.8

import sys
import time
import math

if len(sys.argv) != 2:
    print('usage:')
    print('    (ceiling)')
    print('        Find primes less than ceiling.')
    sys.exit(-1)

try:
    ceiling = int(sys.argv[1])
except:
    print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1]))
    sys.exit(-2)

if ceiling < 3:
    print('Minimum ceiling value is 3.')
    sys.exit(-3)

prime = [3]

# start benchmark
bench_start = time.perf_counter()

# range(start, end, step) does not include end
# step = 2 to avoid checking even numbers
for i in range(5, ceiling + 1, 2):
    # test only against factors less than the square root
    root = math.sqrt(i)
    for j in prime:
        if j > root:
            prime.append(i)
            break
        if i % j == 0:
            break

# end of benchmark
bench_end = time.perf_counter()

# prepend 2 to the prime list since it was skipped
prime.insert(0, 2)

print(prime)
print('Number of, primes less than {0}, found: {1}'.format(ceiling, len(prime)))

# benchmark report
print('Time elapsed: {:f}s'.format(bench_end - bench_start))

sys.exit(0)

#!/usr/bin/env python3.8

import sys
import time
import math

if len(sys.argv) != 2:
    print('usage:')
    print('    (ceiling)')
    print('        Find primes less than or equal to ceiling.')
    sys.exit(-1)

try:
    ceiling = int(sys.argv[1])
except:
    print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1]))
    sys.exit(-2)

if ceiling < 3:
    print('Minimum ceiling value is 3.')
    sys.exit(-3)

prime = [3]

# start benchmark
bench_start = time.perf_counter()

# range(start, end, step) does not include end
# test only for 6k-1 and 6k+1
# use (ceiling+1)+1 in case of ceiling = 6k-1
for h in range(6, ceiling+2, 6):
    for i in [h-1, h+1]:
        # test only against factors less than the square root
        root = math.sqrt(i)
        for j in prime:
            if j > root:
                prime.append(i)
                break
            if i % j == 0:
                break

# end of benchmark
bench_end = time.perf_counter()

# when ceiling = {6k-1, 6k}, remove 6k+1
if prime[-1] > ceiling:
    prime.pop()

# prepend 2 to the prime list since it was skipped
prime.insert(0, 2)

print(prime)
print('Number of, primes less than or equal to {0}, found: {1}'.format(ceiling, len(prime)))

# benchmark report
print('Time elapsed: {:f}s'.format(bench_end-bench_start))

sys.exit(0)
```


texts:
I made this as a personal challenge. It seems to work fine as I can't find any bugs and am happy with how it runs, but I am interested in what I should do to make the code more professional.

Note: This code was tested in Python 3.7.4.

class TicTacToe:
    def __init__(self):
        self.p1 = '\U00002B55'
        self.p2 = '\U0000274C'
        self.draw = [0,1,2,3,4,5,6,7,8]
        self.counte = 0
        self.Print()
    def fillNumber(self,inputnumber):
        self.counte = self.counte + 1
        if self.counte % 2 == 0 :
            player = self.p2
        else :
            player = self.p1
        self.draw[inputnumber] = player
    def condition(self):
        if (self.draw[0] == self.draw[1] and self.draw[1] == self.draw[2]) :
            return self.draw[0]
        elif (self.draw[3] == self.draw[4] and self.draw[4] == self.draw[5]) :
            return self.draw[3]
        elif (self.draw[6] == self.draw[7] and self.draw[7] == self.draw[8]) :
            return self.draw[6]
        elif (self.draw[0] == self.draw[3] and self.draw[3] == self.draw[6]) :
            return self.draw[0]
        elif (self.draw[1] == self.draw[4] and self.draw[4] == self.draw[7]) :
            return self.draw[1]
        elif (self.draw[2] == self.draw[5] and self.draw[5] == self.draw[8]) :
            return self.draw[2]
        elif (self.draw[0] == self.draw[4] and self.draw[4] == self.draw[8]) :
            return self.draw[0]
        elif (self.draw[6] == self.draw[4] and self.draw[4] == self.draw[2]) :
            return self.draw[6]
        else:
            return False
    def Print(self):
        for i in range(1,10) :
            print(self.draw[i-1],end=" ")
            if i % 3 == 0 :
                print()

class Game(TicTacToe):
    def start(self):
        try :
            inputnumber = int(input('Input number 0 to 8 \n'))
        except ValueError :
            self.start()
        if 0 <= inputnumber <= 8 :
            if (self.draw[inputnumber] == '\U00002B55') or (self.draw[inputnumber] == '\U0000274C') :
                print("This place is already paused")
                self.start()
            else :
                self.fillNumber(inputnumber)
        else :
            self.start()
        self.Print()
        self.check()
    def check(self):
        if self.condition() == False :
            self.start()
        elif self.condition() == '\U00002B55' :
            print(self.condition()," Player one is winner")
        elif self.condition() == '\U0000274C' :
            print(self.condition()," player two is winner")

if __name__=="__main__":
    obj=Game()
    obj.start()


texts:
At our company we use an SQLite Database to manage our Drawing IDs (CAD Drawings). The code is written in Python and I need to update it. I think the code I have has some problems, but I am quite unsure so I hope to get feedback and criticism from you all!

1. What my code does:

It saves the ID, Title and Project Number of the Drawing in a SQLite Database
Therefore it has a function GetID to get the latest ID and create a new one from it

Our Drawing IDs look like this "DR0000001". So I need to split the string, convert it to an Integer and add +1. Then rebuild the ID and return it to the OnSave function.

Then if false is not returned I start the save process.

2. Problems I think I have with this code:

I think the time between getting the recent ID and saving the new one to the DB is susceptible to errors like double usage of IDs.
I really think this isn't a professional way to do this and I want to learn the correct way.

3. Here is the Code we used up to this point:

def GetID(self):
    try:
        conn = sqlite3.connect(SQL_PATH)
        c = conn.cursor()
        c.execute("SELECT DrawingID FROM Drawing LIMIT 1 OFFSET (SELECT COUNT(*) FROM Drawing)-1")
        recent_drawing_id = c.fetchall()

        new_drawing_id = "DR"+str(int(recent_drawing_id[0][0][2:])+1).zfill(len(recent_drawing_id[0][0][2:]))

        return new_drawing_id
    except:
        wx.MessageBox("Couldn't get new Drawing ID!", "Info", wx.OK | wx.ICON_INFORMATION)
        return False

def OnSave(self, event, mode):
    drawingID = self.GetID()

    if drawingID != False:
        conn = sqlite3.connect(SQL_PATH)
        c = conn.cursor()

        titel = self.tc2.GetValue()
        project_number = self.tc3.GetValue()

        try:
            c.execute("INSERT into Drawing (DrawingID,Titel,ProjectNumber) values (?,?,?)", (userID,titel,project_number))
            conn.commit()
            c.close()
            return
        except:
            wx.MessageBox("Couldn't create new Drawing entry!", "Info", wx.OK | wx.ICON_INFORMATION)
            return
    else:
        return


texts: Outputting all possible words which fit a string of letters

texts:
I got inspired by this C# question. It asks to write a program to output all possible words (included in a dictionary) which fit a string of letters obtained by swiping the finger over the keyboard, as is often done with mobile keyboards.

  Description

  Software like Swype and SwiftKey lets smartphone users enter text by dragging their finger over the on-screen keyboard, rather than
  tapping on each letter.

  You'll be given a string of characters representing the letters the user has dragged their finger over.

  For example, if the user wants "rest", the string of input characters might be "resdft" or "resert".
      Input

  Given the following input strings, find all possible output words 5 characters or longer.

qwertyuytresdftyuioknn
gijakjthoijerjidsdfnokg

  Output

  Your program should find all possible words (5+ characters) that can be derived from the strings supplied.

  Use http://norvig.com/ngrams/enable1.txt as your search dictionary.

  The order of the output words doesn't matter.

queen question
gaeing garring gathering gating geeing gieing going goring

  Notes/Hints

  Assumptions about the input strings:

  QWERTY keyboard
  Lowercase a-z only, no whitespace or punctuation
  The first and last characters of the input string will always match the first and last characters of the desired output word
  Don't assume users take the most efficient path between letters
  Every letter of the output word will appear in the input string

The function read_vocabulary reads the file and saves the words in a nested dictionary structure, where the first key is the first letter of the word and the second key the last letter of the word (this improves running time by about a factor 2 with respect to a simple set).

I saved the linked word list as dictionary.txt on my computer.

The find_words function tries to find all characters of a word (with the right first and last letter) in the pattern string and yields it if it found all.

The call to sorted in the last part is not necessary from the defined interface (any ordering is fine), but I like it better this way.

All comments are welcome, especially about improving readability of the code.

import string
from collections import defaultdict

def read_vocabulary(file_name):
    vocabulary = {letter: defaultdict(set) for letter in string.lowercase}
    with open(file_name) as dict_file:
        for word in dict_file:
            word = word.strip().lower()
            vocabulary[word[0]][word[-1]].add(word)
    return vocabulary

def find_words(vocabulary, pattern, length=5):
    """
    Search `vocabulary` for words matching `pattern` generated by
    swiping the finger over the keyboard.

    Yields all matching words

    >>> vocabulary = {'q': {'n': {'queen'}, 'r': {'qualor'}}}
    >>> list(find_words(vocabulary, 'qwertyuytresdftyuioknn'))
    ['queen']
    """
    for word in vocabulary[pattern[0]][pattern[-1]]:
        if len(word) >= length:
            i = 1
            for character in word[1:-1]:
                try:
                    i = pattern.index(character, i)
                except ValueError:
                    break
            else:
                yield word

if __name__ == "__main__":
    words = ["qwertyuytresdftyuioknn",
             "gijakjthoijerjidsdfnokg",
             "cghhjkkllooiuytrrdfdftgyuiuytrfdsaazzseertyuioppoiuhgfcxxcfvghujiiuytrfddeews"]
    vocabulary = read_vocabulary("dictionary.txt")
    for word in words:
        # print word
        print " ".join(sorted(find_words(vocabulary, word), key=len, reverse=True))

Regarding run-time:

With the 1 million random characters, as linked at the other question, this code runs in about 0.14 seconds (as determined by python -m cProfile script.py), which includes reading the 1M characters from a file (because they are too big to just paste them in...).


texts: InnoDB Row Locking with Transaction & Helper

texts:
I have recently started to work with InnoDB as well trying to use "helper" functions. The code below seems to work correctly however I am not sure if the true behavior in the background is what I am expecting. Here is the code:

    try{
        $mysqli->begin_transaction();
        $sql1 = "SELECT password, active FROM users WHERE user_id=? LIMIT 1 FOR UPDATE";
        run($mysqli, $sql1, [$user_id]);
        $sql2 = "UPDATE users SET password=?, active=? WHERE user_id=?";
        run($mysqli, $sql2, [$new,$active,$user_id]);
        $mysqli->commit();
        header("Location: ../login.php");
    }catch(exception $e){
        error($mysqli);
    }

function run($mysqli, $sql, $params, $types = ""){
    $types = $types ?: str_repeat("s", count($params));
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt;
}

Basically what I am needing to know is if my LOCK in the first statement is actually taking place and remaining in place until the end of the transaction. I havent been able to find decent examples combining transactions, prepared statements, and row level locking.


texts: Django Notification Model with a generic relation

texts:
I wanted to implement notifications for my app, so that a user would know if another user, liked, commented on, or followed another user. It works, but I feel like it's very limited which I need to improve.

The model looks like this:

class Notification(models.Model):
    receiver = models.ForeignKey(User, related_name='notifications')
    sender = models.ForeignKey(User, related_name='sent_notifications', blank=True, null=True)

    object_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    object = GenericForeignKey('object_type', 'object_id')

    type = models.CharField(max_length=3, choices=config.NOTIFICATION_TYPE_OPTIONS)
    unread = models.BooleanField(default=True)

    slug = models.SlugField(max_length=255, unique=False, default='notification')

    # Other
    date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True)
    date_modified = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True)

Here it is explained:

Receiver is the person receiving the notification
The sender, the oposite of receiver.
Object fields, is the generic relation. It might relate to a comment object, a like object, or a follow object, these objects then nest to the content in question.
What type of notification it is. Can be 'Comment', 'Like', 'Follow'
Slug is used to determine if the notification has been posted before, as to avoid spamming the user if another user decides to spam something that would create notifications.

My issue with this is:

How do I handle notifications once they're pointing to an object that has been deleted? (A user deletes the post a comment was on, or the comment itself)
How do I avoid unecessary database queries when retrieving notificiations with nested content?
Finally, displaying a notification is finicky, as there has to be lots of conditions on what type of notification, what type of object it's pointing to, what type of content the object is on (Did the user like a post or a comment?)


texts: Is my Java SQL connection secure from hackers?

texts:
I would like to know if my java db class is enough protected against hackers.  (I'm currently developing an Android application).  I protect it with a infos.properties file which contains every information that I need.

final class DB {
static final String DRIVER;
static final String URL;
static final String USER;
static final String PASSWORD;

static {
Properties prop = new Properties();
try {
    prop.load(new FileInputStream("infos.properties"));
} catch (IOException e) {
    e.printStackTrace();
}
DRIVER = prop.getProperty("DRIVER");
URL = prop.getProperty("URL");
USER = prop.getProperty("user");
PASSWORD = prop.getProperty("password");
}

public static ResultSet doQuery(String query)
{
    try {
        Class.forName(DRIVER);
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
        return (rs);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
}

If it is not enough protected, what should I do then ?


texts:
Given a tuple of elements, in elementTupleParam and the number in each combination r, we compute all the possible combinations of r elements, in a list of tuples. This is a recursive implementation.

One "challenge" is the inputs r, n, elementTuple, and the list holding the results, combinationList, are shared for all invocations of the recursive function. One method is to use global variables and bind them like below; which I think is rather ugly/bloated. Another method is to pass these are parameters to the recursive function, which may result in long parameter lists. Yet another is to make partialCombinations an inner function of getCombinations.

Another issue is the choice of data structure to hold the partial combinations and the result. I chose tuple because it's immutable: prevTuple is shared across many subsequent invocations, and is less prone to errors caused by accidental modifications.

What do you think? Any thoughts on these or other aspects would be appreciated.

r = 0
n = 0
elementTuple = ()
combinationList = []

# get the vanilla combinations, nCr in number
def getCombinations(elementTupleParam, rParam):
    global r
    global n
    global elementTuple
    global combinationList

    r = rParam
    elementTuple = tuple(elementTupleParam)
    n = len(elementTuple)
    combinationList = []

    if r == 0 or n == 0 or r > n:
        return combinationList

    partialCombinations((), -1)

    return combinationList

def partialCombinations(prevTuple, prevVisitedIndex):
    for thisIndex in range(prevVisitedIndex + 1, n):
        thisTuple = prevTuple + (elementTuple[thisIndex],)

        # If we exhausted all indices and have not formed a long enough tuple, then this is a dead-end, and don't do anything
        if thisIndex == n - 1 and not len(thisTuple) == r:
            continue

        if len(thisTuple) == r: # Found combination
            combinationList.append(thisTuple)
            continue

        partialCombinations(thisTuple, thisIndex)

#sanity check, should be moved to a unit test in another file
if __name__ == '__main__':
    result = getCombinations((2,3,4), 2)
    print(result)


texts: Presenting long string literals (URLs) in Python

texts:
I have a web scraping application that contains long string literals for the URLs. What would be the best way to present them (keeping in mind that I would like to adhere to PEP-8.

URL = "https://www.targetwebsite.co.foo/bar-app/abc/hello/world/AndThen?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL)

I had thought to do this:

URL_BASE = "https://www.targetwebsite.co.foo/"
URL_SUFFIX = "bar-app/abc/hello/world/AndThen"
URL_ARGUMENTS = "?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL_BASE + URL_SUFFIX + URL_ARGUMENTS)

But there are many lines and it's not a standard way of representing a URL.


texts: SwiftUI Passing closure between sibling views

texts:
This is my current View hierarchy:

ParentView:View {
     ChildView1: UIViewRepresentable
     ChildView2: View
}

In ChildView2 I have a button who's action I want to pass to ChildView1. That action is a @Binding on ChildView2, a @State in ParentView where it also is declared, and also a @Binding on ChildView1, where the action takes place.

This is my code:

typealias OnClickHandler = (() -> Void)

struct ParentView: View {
    @State var onClick: OnClickHandler = { }

    var body: some View {
        ZStack {
             VStack {
                ChildView1(onClick: $onClick)
            }

            VStack(alignment:.trailing) {
                Spacer()
                HStack {
                    Spacer()
                    ChildView2(onClick: $onClick)
                }.padding(EdgeInsets(top: 0, leading: 0, bottom: 30, trailing: 5))
            }
        }
    }
}

struct ChildView2: View {
    @Binding var onClick: OnClickHandler

    var body: some View {
        VStack {
            Button(action: onClick) {
                Image("SexyImage")
            }
    }
}

struct ChildView1: UIViewRepresentable {
    @Binding var onClick: OnClickHandler

    func makeUIView(context: Context) -> UIView {
        let view = UIView()

        //"Modifying state during view update, this will cause undefined behavior"
        //if I don't send it to a background thread.
        DispatchQueue.global(qos: .background).async {
            self.onClick = self.foo
        }

        return view
    }

    public func foo() {
        print("bar")
    }

    internal func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
}

After a couple of days of trial and error, this is the best (and only) solution I found. I use a background thread, otherwise I get a warning for modifying the state during UI update.

I'm curious if there is a better solution.


texts:
I implemented the inversion count algorithm using the merge sort approach for this question.

The question begins with a number t = number of test cases and then for each test case you input size of array and then the array entries.

For each test case we have to find the number of inversions = number of shifts made by insertion sort algorithm.

I was surprised to see that only 2 test case passed out of 13 and rest all time out. Can somebody suggest a way I should go about speeding up my code?

Kindly ignore the OOP principles for the time being.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class So {
    private static BufferedReader br;
    private static int n,index,t,noi=0;
    private static int []arr;
    private static int []ans;
    public static void main(String[] args)throws IOException {
        int i,k=1;int s,st,j;
        br=new BufferedReader(new InputStreamReader(System.in));
        String []str;
        t=Integer.parseInt(br.readLine());
        ans=new int[t];
        for(i=0;i<t;++i)
        {
         noi=0;
         n=Integer.parseInt(br.readLine());
         arr=new int[n];
         str=br.readLine().split(" ");
         for(k=0;k<n;++k)
          arr[k]=Integer.parseInt(str[k]);
         ms(0,n-1);
         ans[i]=noi;
        }
        for(int e:ans)
         System.out.println(e);
    }
    public static void ms(int l,int r)
    {
        if(r-l>0)
        {
            int mid=(l+r)/2;
            ms(0,mid);
            ms(mid+1,r);
            merge(l,r);
        }
    }
    public static void merge(int l,int r)
    {
        int []arr2=new int[r-l+1];
        int j,k,mid=(l+r)/2;
        k=mid+1;int i=0;
        j=l;
        while(j<=mid&&k<=r)
        {
            if(arr[j]<=arr[k])
             arr2[i++]=arr[j++];
            else {arr2[i++]=arr[k++];noi+=mid-j+1;}
        }
        System.arraycopy(arr,j,arr2,i,mid-j+1);
        System.arraycopy(arr,k,arr2,i,r-k+1);
        System.arraycopy(arr2,0,arr,l,r-l+1);
    }
}


texts:
This function accepts a cloud of points, and returns those points that are within delta distance of the average (mean) position.

def points_average(points,delta):
    """ this function will check, for every point in points
    what are the points that are near the point (below a distance delta)
    it will then average every such points, creating a new list of points.
    This will continue until we arrive at a fixed amount of points """

    L = math.inf
    n = 0

    while L > len(points):

        L = len(points)

        points2 = []

        for i in xrange(len(points)):

            pt = points[i]
            d = (pt[0]-points[:,0])**2.+(pt[1]-points[:,1])**2.
            pts = points[d<delta**2.]

            x = np.average(pts[:,0])
            y = np.average(pts[:,1])

            points2 += [[x,y]]

        points2 = np.array(points2)
        points = np.unique(points2,axis=0)
        print len(points)

    return points

The function can be tested with:

import numpy as np

delta = 1
points = np.random.uniform(0,100,(500,2))
new_pts = simplify_by_avg_weighted(points,delta)

Please review the code for any improvements.  In particular, I would like to replace the for loop with a numpy vectorized version - any advice towards that would be welcome.


texts:
I have a situation when  there could be and could not be values in database, which is why i return optional, so the response object that goes back to the UI could be different depending on the existing or not values.
Examples :
 new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(),emailFromAuditMessage, tokeDateAndTimeStamp)

As you can see it where it says object.get() its me getting value from the optional.
I would like to avoid numerous if blocks saying if value is Present then add object to the response constructor so currently I am not checking the optional with is present and passing values to the constructor of a response object and inside the constructor i do certain checks and based on checks i either return null or do some operations with not null value and its fine it does the job, however code does not looks good since  it highlights get() in optional objects when i do not proceed with checks before passing it to my response object.
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserLogsResponse {

    private final String latestSentEmailStamp;
    private final String latestDocumentRetrievalStamp;
    private final String privateEmail;
    private final String loginTimeStamp;

    public UserLogsResponse(LocalDateTime latestSentEmailStamp, LocalDateTime latestDocumentRetrievalStamp, String privateEmail, LocalDateTime loginTimeStamp) {
        this.latestSentEmailStamp = latestSentEmailStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(latestSentEmailStamp);
        this.latestDocumentRetrievalStamp = latestDocumentRetrievalStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(latestDocumentRetrievalStamp);
        this.privateEmail = privateEmail == null ? null : new Email(privateEmail).hideSomeEmailCharacters();
        this.loginTimeStamp = loginTimeStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(loginTimeStamp);
    }
}

  public UserLogsResponse getUserLogs(HttpServletRequest request) {
    UserEntity userEntity = currentUser.get();
    Optional<LocalDateTime> tokeDateAndTimeStamp = tokenService.getPreviousLoginStamp(request,userEntity, LocalDateTime.now());
    Optional<LocalDateTime> latestRetrievedDocumentDateAndTime = auditRepository.getLatestRetrievalDocumentDateAndTime(userEntity.getId());
    Optional<AuditEntity> auditEntity = auditRepository.getLatestSendEmailDateAndTime(userEntity.getId());
    String emailFromAuditMessage = new AuditMessageExtractor(auditEntity.get().getMessage()).extractEmail();
    return tokeDateAndTimeStamp.map(localDateTime -> new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(), emailFromAuditMessage, localDateTime))
            .orElseGet(() -> new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(),emailFromAuditMessage, null));
}

Would appreciate any suggestions, as I said everything works and its good but if i was another developer and saw optional objects without ifPresent check it would be confusing.


texts: Iterative version of a permutations algorithm

texts:
For learning purposes, I've written an iterative version of a recursive algorithm for generating the set of permutations for a given set of unique integers.

Can I make any improvements to increase readability and performance?

I've also read in various sources that when transforming a recursive algorithm into an iterative one, the stack data-structure is often used to 'substitute' the call stack used in the recursive case. I'm not using a std::stack here but could I have used one to simplify my implementation?

using std::vector;

vector<vector<int>> permutations(vector<int> integers) {
    vector<vector<int>> curr_perms;

    if (integers.size() <= 1) {
        curr_perms.push_back(integers);
        return curr_perms;
    }

    size_t sz = integers.size();

    vector<vector<int>> next_perms;

    // initialise with the one permutation of the last single element
    vector<int> t = { integers[sz - 1] };
    curr_perms.emplace_back(t);

    // backwards iterating a sequence of at least two elements
    for (int i = sz - 2; i >= 0; --i) {
        auto first = integers[i];

        for (const auto &s : curr_perms) {
            for (auto j = 0U; j < s.size() + 1; ++j) {
                vector<int> p(s.begin(), s.end());  // make a copy
                p.insert(p.begin() + j, first);     // shuffle in 'first' element
                next_perms.push_back(std::move(p)); // and add this as a new permutation
            }
        }

        // permutations found in this iteration are the input for the next
        std::swap(next_perms, curr_perms); // <-- is this needlessly copying all the elements?
        next_perms.clear();
    }

    return curr_perms;
}


texts: Convert a date string to a DateTime object in C#

texts:
I was just wondering if my code contains defects or if there was a more efficient or general way to convert string to DateTime object. In the input, I have a string in the UTC format.

public static DateTime ParseDateTime(string dateString)
    {
        DateTime dateTime;
        if (!DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
        {
            if (!DateTime.TryParse(dateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out dateTime))
            {
                try
                {
                    dateTime = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
                }
                catch (FormatException)
                {
                    // Try to extract at least year from the string (the longest digits substring)
                    var yearMatch = Regex.Matches(dateString, @"\d{4}").Cast<Match>().FirstOrDefault();
                    if (yearMatch == null || string.IsNullOrWhiteSpace(yearMatch.Value))
                    {
                        throw;
                    }

                    // Only year really matters for Max and Min values of DateTime
                    var year = int.Parse(yearMatch.Value, CultureInfo.InvariantCulture);

                    // Try to determine what do we have (Min or Max value)
                    if (year == DateTime.MaxValue.Year)
                    {
                        dateTime = DateTime.MaxValue;
                    }
                    else
                    {
                        if (year == DateTime.MinValue.Year)
                        {
                            dateTime = DateTime.MinValue;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }

        dateTime = dateTime.ToUniversalTime();
        return dateTime;
    }


texts: Find all combinations of numbers of a set that add up to a given target - avoid for loops

texts:
I am thinking about the following problem:
Consider a 3-numbers lock, i.e. a lock which has three little number wheels that opens whenever the sum of these three numbers equals 75. I know, this doesn't make sense for a lock, but just imagine this. The number wheels have numbers 3, 15, 17, 35, 40, 25, 5, 13. I am allowed to use numbers multiple times, i.e. in order to reach 75, I could use the combination 25, 25, 25.
I want to come up with all possible combinations to solve this puzzle. I have a solution and it works fine for just 3 different number wheels. But since I am using 3 for-loops for this, I know I cannot extend this code to work for, say a 100 number-wheels lock. I don't even know if this was possible (maybe recursively, but I always have troubles understanding recursion). Anyways, I really want to make this code look a little nicer. It is okay for me to leave the number of iterations the same, but I really want to get rid of the 3 for-loops, because I kind of want to extend this code to be a 10-numbers lock and in that case I would have 10 for-loops which looks ridiculous. There should be a way to leave out the for loops, I think
So, enough said. Here is my solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestClass {

    public static void main(String[] args) {

        List<List<Integer>> solutions = new ArrayList<>();
        List<Integer> combinations = new ArrayList<Integer>();

        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(3);
        numbers.add(15);
        numbers.add(17);
        numbers.add(35);
        numbers.add(40);
        numbers.add(25);
        numbers.add(5);
        numbers.add(13);

        int target = 75;

        int var1 = 3;
        int var2 = 3;
        int var3 = 3;

        for (int i = 0; i < numbers.size(); i++) {
            var1 = numbers.get(i);
            for (int j = 0; j < numbers.size(); j++) {
                var2 = numbers.get(j);
                for (int k = 0; k < numbers.size(); k++) {
                    var3 = numbers.get(k);

                    int sum = var1 + var2 + var3;
                    if (sum == target) {
                        combinations.add(var1);
                        combinations.add(var2);
                        combinations.add(var3);

                        Collections.sort(combinations);
                        if (!solutions.contains(combinations)) {
                            solutions.add(combinations);
                        }
                        combinations = new ArrayList<>();
                    }
                }
            }
        }

        for (List<Integer> solution: solutions) {
            System.out.println(solution);
        }

    }
}

Any ideas, please share them with me :-)


texts:
Right now I'm solving this problem on codewars.com. I'm not sure about how to optimise the code further. Or is my algorithm inefficient? If it's an algorithmic issue, could someone help me how to go about it?

import java.util.Arrays;

class Epidem {

    public static int epidemic(int tm, int n, int s0, int i0, double b, double a) {
        // your code
     double dt = tm/n;
     double s1,i1,r,j;
     r=0;j=0;

     while(j<=tm)
      {
      s1 = s0 - dt*b*s0*i0;
      i1 = i0 + dt*(b*s0*i0 - a*i0);
      r = r + dt * i0 * a;
      s0 = (int) s1;
      i0 = (int) i1;
      j+=dt;
      }

     return (int) i0;

    }
}

It fails in the following cases:

int tm = 18 ;int n = 432 ;int s0 = 1004 ;int i0 = 1 ;double b = 0.00209 ;double a = 0.51;

    tm = 12 ;n = 288 ;s0 = 1007 ;i0 = 2 ;b = 0.00206 ;a = 0.45;

    tm = 13 ;n = 312 ;s0 = 999 ;i0 = 1 ;b = 0.00221 ;a = 0.55;

    tm = 24 ;n = 576 ;s0 = 1005 ;i0 = 1 ;b = 0.00216 ;a = 0.45;

    tm = 24 ;n = 576 ;s0 = 982 ;i0 = 1 ;b = 0.00214 ;a = 0.44;

    tm = 20 ;n = 480 ;s0 = 1000 ;i0 = 1 ;b = 0.00199 ;a = 0.53;

    tm = 28 ;n = 672 ;s0 = 980 ;i0 = 1 ;b = 0.00198 ;a = 0.44;

    tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41;

    tm = 13 ;n = 312 ;s0 = 993 ;i0 = 2 ;b = 0.0021 ;a = 0.51;

    tm = 28 ;n = 672 ;s0 = 999 ;i0 = 1 ;b = 0.00197 ;a = 0.55;


texts:
I have two functions. Both have to have unique elements, one with Integers and the other a String which returns a list of Char. My runtime is currently quite high and I'm not allowed to use imports, but I was wondering how to improve them:
uniqueInt:: [Int] -> [Int]
uniqueInt[] = []
uniqueInt xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]

Example:
uniqueInt [1,2,1,3,1,2] = [1,2,3]
uniqueString :: String -> [Char]
uniqueString ""=[]
uniqueString xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]

Example: uniqueString "hello"="helo"


texts:
I would prefer a review of:

Efficiency
Standards
Different approaches

Here's the code:

program bubbleSort;
var
        toSort: array[1..5] of integer = (3, 25, 2, 69, 1);
        passChanges: boolean = true;
        counter, index, temp: integer;
begin
        while passChanges do
        begin
                index := 1;

                passChanges := false;

                for index := 1 to length(toSort) - 1  do
                begin
                        if (toSort[index] > toSort[index +1]) then
                        Begin
                                temp := toSort[index + 1];
                                toSort[index + 1] := toSort[index];
                                toSort[index] := temp;
                                passChanges := true;
                        end;
                end;
        end;

        for counter := 1 to length(toSort) do
                writeln(toSort[counter]);

        readln;
end.


texts:
I'm working on a clientside iOS app for my school that involves students purchasing things, and I wrote a String extension for formatting a String into USD. Is there a way to improve this or make it more "swifty"?

extension String {
    var usdFormat: String {
        var str = self
        var postDec = str.components(separatedBy: ".")
        switch postDec[1].count {
        case 0: str.append("00")
        case 1: str.append("0")
        default: break
        }

        str = "$" + str

        return str
    }
}


texts:
I'm trying to write efficient code for calculating the chain-length of each number.

For example, 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
It took 13 iterations to get 13 down to 1, so collatz(13) = 10.

Here is my implementation:

def collatz(n, d={1:1}):
    if not n in d:
        d[n] = collatz(n * 3 + 1 if n & 1 else n/2) + 1
    return d[n]

It's quite efficient, but I'd like to know whether the same efficiency (or better) can be achieved by an iterative one.


texts: Check if there's exactly one match in a vector

texts:
The challenge is to iterate over the vector only once and return the value within the range of the zero. However, if there are no matches or more than 1 match, deliver an error. The vector is unsorted and has no guarantee on it's size or the range of data.
More technically, the number of data accesses into the vector can't exceed N + 1 (access to iterators doesn't count)

I did this with a simple loop with 2 nested checks, and was wondering if there was a stdlib based or a better algorithmic solution that I'm not able to find.

Maybe ranges can help, but I'm limited to c++17 here, though the only c++17 feature I'm using is std::optional for error handling.

#include <optional>
#include <vector>

std::optional<int> get_unambiguous(const std::vector<int> &data,
                                    const int range,
                                    const int zero = 0)
{
    std::optional<int> found;
    for (const auto& item: data)
    {
        if (std::abs(item - zero) < range) {
            if (found) {
                return {};
            }
            found = item;
        }
    }
    return found;
}


texts:
I have solved this simple challenge on Advent of Code:

  Santa is trying to deliver presents in a large apartment building, but
  he can't find the right floor - the directions he got are a little
  confusing. He starts on the ground floor (floor 0) and then follows
  the instructions one character at a time.

  An opening parenthesis, (, means he should go up one floor, and a
  closing parenthesis, ), means he should go down one floor.

  The apartment building is very tall, and the basement is very deep; he
  will never find the top or bottom floors.

This is my first time trying out Lisp (and functional programming at all) and would like to see if there is anything that I could do better, or more "functionally".

I wrote the function in a manner to be quite generic, i.e., it can take any input string, and any two characters. It returns a list containing the amount of up and down characters along with the difference between the two (which is the answer to the challenge). Demo on Coding Ground

(defun count-up-down-characters-with-difference (input-string up-char down-char)
    "Given a string of any length, iterate each character of the string looking for up- and down-characters
        provided by the caller, and return the number of each, as well as the difference between them."
    (setf count-up 0)
    (setf count-down 0)
    (loop for c across input-string do
        (if (char-equal c up-char)
            (incf count-up))
        (if (char-equal c down-char)
            (decf count-down)))
    (list count-up count-down (+ count-up count-down)))

Example generic usage:

(setf night-before-xmas "'Twas the night before Christmas, when all through the house, Not a creature was stirring, not even a mouse; The stockings were hung by the chimney with care, In hopes that St. Nicholas soon would be there;")
(time (print (count-up-down-characters-with-difference night-before-xmas #\e #\a)))
;; prints:
;(21 -10 11)
;Real time: 5.97E-4 sec.
;Run time: 5.7E-4 sec.
;Space: 1400 Bytes


texts:
I need to place a Google map in Colorbox overlay and am wondering if there's a better way to do this.  I've just started out with Google's tutorial so there's nothing fancy going on.

Right now I'm hiding the div that Google loads the map into:

Here's the call to Colorbox:

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

$(document).ready(function(){

    $("#farm_on_google_maps").colorbox({
        inline: true,
        width:700,
        height:450,
        href : '#map_canvas'
        });
});

Even though it works, I wonder if the map could be loaded directly into Colorbox.


texts: Increase efficiency for an R simulator of the Monty Hall Puzzle

texts:
The Monty Hall Problem is a simple puzzle involving probability that even stumps professionals in careers dealing with some heavy-duty math.  Here's the basic problem:

Suppose you're on a game show, and you're given the choice of three doors: Behind one      door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who      knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

You can find numerous explanations of the solution here:
http://en.wikipedia.org/wiki/Monty_Hall_problem
Goal of my simulation: Prove that a switching strategy will win you the car 2/3 of the time.

I got curious and wanted to write a little function that simulates the problem many times and returns the proportion of wins if you switched and the proportion of wins if you stayed with your first choice.  The function then plots the cumulative wins.

This function takes a long time to run once I get to about 10,000 simulations.  I know I don't need this many simulations to prove this but I'd love to hear some ideas on how to make it more efficient.  Thanks for your feedback!

Monty_Hall=function(repetitions){
doors=c('A','B','C')
stay_wins=0
switch_wins=0
series=data.frame(sim_num=seq(repetitions),cum_sum_stay=replicate(repetitions,0),cum_sum_switch=replicate(repetitions,0))
for(i in seq(repetitions)){
    winning_door=sample(doors,1)
    contestant_chooses=sample(doors,1)
    if(contestant_chooses==winning_door)
        stay_wins=stay_wins+1
    else
        switch_wins=switch_wins+1
    series[i,'cum_sum_stay']=stay_wins
    series[i,'cum_sum_switch']=switch_wins
}
plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins',
xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l')
lines(series$sim_num,series$cum_sum_stay,col=4)
legend('topleft',legend=c('Cumulative wins from switching',
'Cumulative wins from staying'),col=c(2,4),lty=1)
result=list(series=series,stay_wins=stay_wins,switch_wins=switch_wins,
proportion_stay_wins=stay_wins/repetitions,
proportion_switch_wins=switch_wins/repetitions)
return(result)
}
#Theory predicts that it is to the contestant's advantage if he
#switches his choice to the other door.  This function simulates the game
#many times, and shows you the proportion of games in which staying or
#switching would win the car.  It also plots the cumulative wins for each strategy.
Monty_Hall(100)


texts:
I want to join two fragments into one string with a separator, but when one of the fragments is empty I only want one of them.

I have two implementations. The first is long and slightly repetitive, but I believe it is easier to understand, since it is a more step-by-step description of the process. The second is way shorter, but less self-explanatory. It uses the Where method, and it may not be clear to everybody what the semantics of $_ are. Maybe both approaches can even be merged into an even better implementation.

Which would you recommend?

Version 1:

if ($Fragment1.Length -ne 0 -and $Fragment2.Length -ne 0) {
    $String = $Fragment2 + $Seperator + $Fragment2
} elseif ($Fragment1.Length -ne 0) {
    $String = $Fragment1
} elseif ($Fragment2.Length -ne 0) {
    $String = $Fragment2
} else {
    $String = $null
}

Version 2:

$String =
    @($Fragment2, $Fragment1).Where({$_.Length -ne 0}) -join $Seperator


texts: Switching to next select field by class of parent

texts:
This emulates behavior of tab and shifttab with → and ←.

I.e., switch focus to the next/previous select field with parent class .tab (which are not siblings in the DOM.)

It works, but is there any way to make it more elegant? Especially the if/then and the limit to range. I'm fairly new to JavaScript.

$(document).on('keydown', '.tab select', function (e) {
    let tabs = $(".tab select");                        //get all tabs
    let tab = tabs.index($($(document.activeElement))); //focused tab
    if (e.which == 37) {                                //left arrow
        tab -= 1;
    } else {
        if (e.which == 39) {                            //right arrow
            tab += 1;
        }
    };
    tab = Math.min(tabs.length, Math.max(tab, 0));      //stay in range
    tabs.eq(tab).focus()
});


texts: Upload Image From URL via PHP (In a safe way)

texts:
I'm trying to make a simple code to upload an image directly from a url. However I have concerns about the safety of my code since a user can submit any url. How I can make it more safe?
All the good examples I found are always related to files uploaded via a form.
So I'm having difficulties in improving this code.
$img_url = "https://i.ytimg.com/vi/wSdT-SArM2Q/maxresdefault.jpg";

function getimg($url)
{
  $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
  $headers[] = 'Connection: Keep-Alive';
  $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
  $user_agent = 'php';
  $process = curl_init($url);
  curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($process, CURLOPT_HEADER, 0);
  curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
  $return = curl_exec($process);
  curl_close($process);
  return $return;
}

$imagename = basename($img_url);
if (file_exists('./upload/' . $imagename)) {
  //
}

$image = getimg($img_url);
file_put_contents('upload/' . $imagename, $image);


texts: Implementing a generic class and choosing a collection based on a type

texts:
In this topic here I have aksed for help to sort out an error while creating a generic class whose method can return a different collection given a type. I received the answer and working solution but I have a feeling the problem is not sorted in proper way. That is why I came here for a review.

The reason for having a generic class is is that I use DI and pass either DbContext to collect data from a database or another Object to "collect" data from collections. The DI is done in the main Program. The interface is generic to handle DbContext and then fetching particular collection given a type: DbContext.Set<>(). The FetchDataFromCollection is also generic, so is FetchDataFromDatabase because this is how DbCOntext works.

Is there any other way to sort it out and for instance avoid if ... else blocks? I was thinking to make another class ModelBase, inherits from it into concrete implementations, which would return a specific collection and inject such class into FetchFromCollection but then I would have to make this decition by myself which class to inject to get proper collection in FetchFromCollection. What I would have is a method which would decide to return a particular collection given a type.

I don't know if it's possible. Below are the three program components.

IFetchData:

public interface IFetchData<TEntity>
{
    IEnumerable<TEntity> GetItems();
}

Then I have created these two classes:

FetchFromDatabase:

public class FetchFromDatabase<TEntity> : IFetchData<TEntity>
    where TEntity : class
{
    private readonly MainDBContextBase context;

    public FetchFromDatabase(MainDBContextBase context)
    {
        if (context == null)
            throw new ArgumentNullException("DB context");
        this.context = context;
    }

    public IEnumerable<TEntity> GetItems()
    {
        return context.Set<TEntity>();
    }
}

FetchFromCollection:

public class FetchFromCollection<TEntity> : IFetchData<TEntity>
    where TEntity : class
{
    // ModelBase<TEntity> models;

    private readonly InitializeComponents components;
    private ModelModules modules;
    private ModelSpecializations specializations;
    private ModelTeachers teachers;
    private ModelStudents students;

    public FetchFromCollection(InitializeComponents components)
    {
        if (components == null)
            throw new ArgumentNullException("Context");
        this.components = components;
    }

    public IEnumerable<TEntity> GetItems()
    {
        if (typeof(TEntity) == typeof(Module))
        {
            if (modules == null)
                modules = new ModelModules(components);
            return (IEnumerable<TEntity>)modules.Set();
        }
        if (typeof(TEntity) == typeof(Specialization))
        {
            if (specializations == null)
                specializations = new ModelSpecializations(components);
            return (IEnumerable<TEntity>)specializations.Set();
        }
        if (typeof(TEntity) == typeof(Module))
        {
            if (teachers == null)
                teachers = new ModelTeachers(components);
            return (IEnumerable<TEntity>)teachers.Set();
        }
        else
        {
            if (students == null)
                students = new ModelStudents(components);
            return (IEnumerable<TEntity>)students.Set();
        }
    }
}


texts: Implementation of merge sort and bubble sort

texts:
I'm new to Go and looking for a review of my merge sort and bubble sort implementations. What can be done better? Can my code be cleaner/clearer?

// algos.go
// (C) 2014 splashinn
// Implement two types of sorting algorithms; merge sort and bubble sort

package main

import (
    "fmt"
    "time"
    "math/rand"
)

func main() {

    var n int
    fmt.Printf("How long of an array should we sort? (≤1000) ")
    _, err := fmt.Scanf("%d", &n)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    if n > 1000 {
        fmt.Println("Error:", n, "> 1000 - too long!")
        return
    } else if n < 1 {
        fmt.Println("Error:", n, "< 1")
        return
    }

    array := make([]int, n)
    rand.Seed(time.Now().UTC().UnixNano())

    fmt.Println("Original Array:")
    for i := range array {
        array[i] = rand.Intn(10000)
        fmt.Printf("%d\t", array[i])
    }
    fmt.Println()

    bubbleSortedArray := BubbleSort(array)

    fmt.Println("Bubble Sorted Array: ")
    for i := range bubbleSortedArray {
        fmt.Printf("%d\t", bubbleSortedArray[i])
    }
    fmt.Println()

    mergeSortedArray := MergeSort(array)

    fmt.Println("Merge Sorted Array: ")
    for i := range mergeSortedArray {
        fmt.Printf("%d\t", mergeSortedArray[i])
    }
    fmt.Println()
}

// Implementing bubble sort
func BubbleSort(inputArray []int) (sortedArray []int) {
    array := make([]int, len(inputArray))
    copy(array, inputArray)
    for i := 0; i < len(array)-1; i++ {
        for j := 0; j < len(array)-1; j++ {
            if array[j] > array[j+1] {
                // Idiomatic Go swap
                array[j], array[j+1] = array[j+1], array[j]
            }
        }
    }
    return array
}

// Implementing a top-down merge sort
// Adapted from the Merge Sort C code from Wikipedia
func MergeSort(array []int) (sortedArray []int) {
    sortedArray = make([]int, len(array), cap(array))
    splitMerge(array, sortedArray)
    return array
}

func splitMerge(A []int, B []int) {
    if(len(A) < 2) {   // if run size == 1, consider it sorted
        return
    }
    // recursively split runs into two halves until run size == 1,
    // then merge them and return back up the call chain
    iMiddle := len(A) / 2              // iMiddle = mid point
    splitMerge(A[:iMiddle], B[:iMiddle])  // split / merge left  half
    splitMerge(A[iMiddle:], B[iMiddle:])  // split / merge right half
    merge(A, B, iMiddle)  // merge the two half runs
    copy(A, B)             // copy the merged runs back to A
}

func merge(A []int, B []int, iMiddle int) {
    i0 := 0
    i1 := len(A) / 2
    iEnd := len(A)

    for j := range A {
        // If left run head exists and is <= existing right run head.
        if (i0 < iMiddle && (i1 >= iEnd || A[i0] <= A[i1])) {
            B[j] = A[i0]
            i0++  // Increment i0 after using it as an index.
        } else {
            B[j] = A[i1]
            i1++  // Increment i1 after using it as an index.
        }
    }
}


texts:
I've been using PHP labels in my Controllers for code folding. PHP labels are actually used with goto statements. But I'm using labels only because it's so much easier to fold my code in different IDEs using labels + curly braces, and I can use labels as titles for different sections of the code.

Here's an example. Take a look at SettingCartFields label.

<?php

namespace App\Http\Controllers;

use App\Cart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller
{
    public function create(Request $request)
    {
        $cart = new Cart;

        SettingCartFields: {
            $cart->field1 = $request->field1;
            $cart->field2 = $request->field2;
            $cart->field3 = $request->field3;
            $cart->field4 = $request->field4;
            $cart->field5 = $request->field5;
            $cart->field6 = $request->field6;
        }

        $cart->save();
    }
}

I have a few questions, are there any performance issues with this? Am I introducing some kind of overhead by adding a lot of labels in my code? Is there any better way to do this?


texts: Simple function to turn array of objects to array of key value pairs

texts:
I have an application that has a lot of very complex objects that in most cases I only need to access an id value and a name value from. I'd like to reduce the overhead of serializing these large objects to JSON.  This is a simple function I created that takes an array of objects and returns an array of structures that contains only two keys, an id and a value.  This also needs to be compatible with CF8 servers.

I'd like to get some feedback on ways to make the code more expressive and any ways I can optimize this as well.

<cffunction name="toKeyValuePairArray" returntype="Array" output="false" access="public">
    <cfargument name="theArray" type="Array" required="true" hint="an array of objects" />
    <cfargument name="idGetterFunctionName" type="string" />
    <cfargument name="valueGetterFunctionName" type="string" />
        <cfset var local = structNew() />
        <cfset var retArray = [] />
        <cfset var obj = {} />
        <cfloop array="#arguments.theArray#" index="local.theComponent">
            <cfset obj = {} />
            <cftry>
                <cfinvoke component="#local.theComponent#" method="#arguments.idGetterFunctionName#" returnvariable="local.id" />
                <cfinvoke component="#local.theComponent#" method="#arguments.valueGetterFunctionName#" returnvariable="local.value" />

                <cfset obj.id = local.id />
                <cfset obj.value = local.id />

                <cfset arrayAppend(retArray,obj) />
            <cfcatch></cfcatch>
            </cftry>
        </cfloop>

        <cfreturn retArray />
</cffunction>


texts:
I'm trying to make a VBA code to arrange k-element subset of an n-set into some sequence. In other word, I'm trying to list all of k-permutations of n member set. For example, let's try to list all of 2-permutations of set {A,B,C} where each characters are located in the cells of Range("A1:C1"). Here are all the permutations:

{A,B}       {A,C}       {B,A}       {B,C}       {C,A}       {C,B}

The following code to implement the above task works fine if there's no duplicate in each of characters of data input:

Sub Permutation()
Dim Data_Input As Variant, Permutation_Output As Variant
Dim Output_Row As Long, Last_Column As Long

Rows("2:" & Rows.Count).Clear
Last_Column = Cells(1, Columns.Count).End(xlToLeft).Column
Data_Input = Application.Transpose(Application.Transpose(Range("A1", Cells(1, Last_Column))))

k = InputBox("Input the value of k for P(" _
    & UBound(Data_Input) & " , k) where k is an integer between 2 and " _
    & UBound(Data_Input) & " inclusive.", "Permutation", 1)

If k >= 2 And k <= UBound(Data_Input) Then
    Output_Row = 2
    ReDim Permutation_Output(1 To k)
    Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, 1)
Else
    MsgBox "The input [" & k & "] is invalid. The input must be an integer between 2 and " _
    & UBound(Data_Input) & " inclusive."
End If

End Sub

Function Permutation_Generator(Data_Input As Variant, Permutation_Output As Variant, _
                               Output_Row As Long, Output_Index As Integer)
Dim i As Long, j As Long, P As Boolean

For i = 1 To UBound(Data_Input)
    P = True
    For j = 1 To Output_Index - 1
        If Permutation_Output(j) = Data_Input(i) Then
            P = False
            Exit For
        End If
    Next j
    If P Then
        Permutation_Output(Output_Index) = Data_Input(i)
        If Output_Index = k Then
            Output_Row = Output_Row + 1
            Range("A" & Output_Row).Resize(, k) = Permutation_Output
        Else
            Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, Output_Index + 1)
        End If
    End If
Next i
End Function

I am hoping I can get some help to improve its performance and to better its algorithm in order to make a good partial anagram generator, i.e. it must be able to work if there are the duplicate characters. For example, let's test to list all of characters in my name: ANA. The output should be ANA, AAN, and NAA, but my code returns nothing. For 2-permutations of my name should be AN, AA, and NA yet my code returns AN, NA, AN, and NA. I have a feeling the culprit is the following statements:

        If Permutation_Output(j) = Data_Input(i) Then
            P = False
            Exit For
        End If

though I'm not so sure. I'd be eternally grateful if someone here could help me.


texts:
Please review my code and help me to improve it.

#include <iostream>
#include <vector>
#include <limits>
#include <map>

class Graph
{
    int vertex_count;

    enum { INF = std::numeric_limits<int>::max() };

    struct Vertex
    {
        int id;
        int distance;
        Vertex * parent;

        Vertex(int _id) : id(std::move(_id)),
                          distance(INF),
                          parent(nullptr)
                          {}
    };
    std::vector<Vertex> vertices;
    //std::pair<int, int> edge;
    std::map<std::pair<int, int>, int> edge_weight;

  public:
    Graph(int);
    void add_edge(int, int, int); //source, destination, weight
    bool bellman_ford(int); //source
    void distance_from_source();

  private:
    void initialize_single_source(int); //source
    void relax(int, int, int); //source, destination, weight
};

Graph::Graph(int v)
{
    vertex_count = v;
    for (int i = 0; i < vertex_count; i++)
    {
        vertices.push_back(Vertex(i));
    }
}

void Graph::initialize_single_source(int src)
{
    vertices[src].distance = 0;
}

void Graph::add_edge(int src, int dest, int weight)
{
    edge_weight.insert(std::make_pair( std::make_pair(src, dest), weight ));
}

void Graph::relax(int src, int dest, int weight)
{
    auto wt =  edge_weight.find(std::make_pair(src, dest));
    if (vertices[dest].distance > (vertices[src].distance + wt->second))
    {
        vertices[dest].distance = (vertices[src].distance + wt->second);
        vertices[dest].parent = &vertices[src];
    }
}

bool Graph::bellman_ford(int src)
{
    initialize_single_source(src);
    for (int i = 0; i < vertex_count - 1; i++)
    {
        for (auto it = edge_weight.begin(); it != edge_weight.end(); it++)
        {
            relax(it->first.first, it->first.second, it->second);
        }
    }

    for (auto it = edge_weight.begin(); it != edge_weight.end(); it++)
    {
        if (vertices[it->first.second].distance > (vertices[it->first.first].distance + it->second))
           return false;
    }
    return true;
}

void Graph::distance_from_source()
{
    std::cout << "Vertex\t\tDistance from Source\n";
    for (int i = 0; i < vertex_count; i++)
    {
        std::cout << vertices[i].id <<"\t\t" << vertices[i].distance <<"\n";
    }
}

int main()
{
    Graph grp(5);
    grp.add_edge(0, 1, 6);
    grp.add_edge(0, 2, 7);
    grp.add_edge(1, 3, 5);
    grp.add_edge(1, 4, -4);
    grp.add_edge(1, 2, 8);
    grp.add_edge(2, 3, -3);
    grp.add_edge(2, 4, 9);
    grp.add_edge(3, 1, -2);
    grp.add_edge(4, 0, 2);
    grp.add_edge(4, 3, 7);

    bool res = grp.bellman_ford(0);
    if (res == true)
       std::cout << "Graph contains no negative cycle \n";
    else
       std::cout << "Graph conatins negative cycle \n";

    grp.distance_from_source();
}


texts:
Below is attempt to catch potential deadlocks at runtime in C#. Basically this class allows user to acquire locks in a pre-defined order only. I ran some basic tests and it appears to work. Please review and let me know if you find something wrong with implementation.

public class OrderedLock
{
    [ThreadStatic]
    static HashSet<int> mAcquiredLocks;
    static ConcurrentDictionary<int, object> mCreatedLocks = new ConcurrentDictionary<int, object>();

    private int mId;
    private ThreadLocal<int> mRefCount = new ThreadLocal<int>(false);
    private ReaderWriterLockSlim mLock;

    public OrderedLock(int id)
    {
        if (!mCreatedLocks.TryAdd(id, null)) throw new ApplicationException("Duplicate identifier detected");

        mId = id;
        mRefCount.Value = 0;
        mLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    }

    public void AcquireReadLock()
    {
        CheckLockOrder();
        mLock.EnterReadLock();
    }

    public void AcquireWriteLock()
    {
        CheckLockOrder();
        mLock.EnterWriteLock();
    }

    public void ReleaseReadLock()
    {
        mRefCount.Value -= 1;
        mLock.ExitReadLock();
        if (mRefCount.Value == 0) mAcquiredLocks.Remove(mId);
    }

    public void ReleaseWriteLock()
    {
        mRefCount.Value -= 1;
        mLock.ExitWriteLock();
        if (mRefCount.Value == 0) mAcquiredLocks.Remove(mId);
    }

    private void CheckLockOrder()
    {
        if (mAcquiredLocks == null) mAcquiredLocks = new HashSet<int>();
        if (!mAcquiredLocks.Contains(mId))
        {
            if (mAcquiredLocks.Count > 0 && mAcquiredLocks.Max() > mId)
                throw new ApplicationException("Invalid order of locking detected");
            else
                mAcquiredLocks.Add(mId);
        }

        mRefCount.Value += 1;
    }
}


texts:
Edit 1 after first review: I changed to use malloc / free since apparently it's also easier to optimize than new[] / delete[] : https://godbolt.org/g/CZy28o ; of course this adds an additional requirement on the alignment.

template <class T>
struct pod_allocator
{
    static_assert(std::is_pod_v<T>, "can only be used with POD types");
    static_assert(alignof(T) <= alignof(std::max_align_t), "type must not have specific alignment requirements");
    using value_type = T;
    auto allocate(std::size_t num)  { return (T*) malloc(sizeof(T) * num); }
    void deallocate(T* p, std::size_t)   { free(p); }
};

The incentive here is to allow some compilers (clang as of clang-6.0 for instance) to remove allocations in some cases, by observing that they are able to optimize out new/delete pairs but not ::operator new/::operator delete pairs : see the following in https://godbolt.org/g/jumtCU

#include <algorithm>
#include <numeric>
#include <cinttypes>
int foo(int* src)
{
   constexpr int n = 10;
   auto x = new int[n];
   for(int i = 0; i < n; i++)
   {
       if(i%2 == 0)
         x[i] = src[n - i - 1] * 2;
       else
         x[i] = src[i] * src[i];
   }
   int z = 0;
   if(x[1] < 1) z = 10;
   else z = x[2] + x[4] - x[1] - x[3];

   delete[] x;

   return z;
}

While the vector version... well... produces "suboptimal" assembly: https://godbolt.org/g/cZvSRb .

#include <algorithm>
#include <numeric>
#include <cinttypes>
#include <vector>
int foo(int* src)
{
   constexpr int n = 10;
   std::vector<int> x(n);
   for(int i = 0; i < n; i++)
   {
       if(i%2 == 0)
         x[i] = src[n - i - 1] * 2;
       else
         x[i] = src[i] * src[i];
   }
   int z = 0;
   if(x[1] < 1) z = 10;
   else z = x[2] + x[4] - x[1] - x[3];

   return z;
}

Hence, here is the code of the allocator, which allows us to claim back much better codegen (https://godbolt.org/g/hvPY14) :

template <class T>
class pod_allocator
{
  public:
    static_assert(std::is_pod_v<T>, "can only be used with POD types");
    using value_type = T;
    using pointer = T*;
    using const_pointer = const T*;
    using reference = T&;
    using const_reference = const T&;
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;
    using is_always_equal = std::true_type;

    constexpr T* address(T& value) const noexcept { return &value; }
    constexpr const T* address(const T& value) const noexcept { return &value; }

    constexpr auto max_size() const noexcept {
        return std::numeric_limits<std::size_t>::max() / sizeof(T);
    }

    auto allocate(std::size_t num) { return new T[num]; }
    void deallocate(T* p, std::size_t) { delete[] p; }

    constexpr void construct(T*, const T&) noexcept { }
    constexpr void destroy(T*) noexcept { }
};

template<class T1, class T2>
constexpr bool operator==(const pod_allocator<T1>&, const pod_allocator<T2>&) noexcept { return true; }

template<class T1, class T2>
constexpr bool operator!=(const pod_allocator<T1>&, const pod_allocator<T2>&) noexcept { return false; }

template<typename T>
using pod_vector = std::vector<T, pod_allocator<T>>;

Are there some subtle bugs that I could be introducing this way ? (not counting of course the lack of value-initialization, which is, in this case, a feature and not a bug).


texts: List of variables, split based on pattern

texts:
In my application i keep repeating writing this pattern. I just cant figure out how to write it better. Coming to you for suggestions:

        if ($_POST['x'] = 1) {add_remove($one, array($two,$three,$four,$five));}
        if ($_POST['x'] = 2) {add_remove($two, array($one,$three,$four,$five));}
        if ($_POST['x'] = 3) {add_remove($three, array($one,$two,$four,$five));}
        if ($_POST['x'] = 4) {add_remove($four, array($one,$two,$three,$five));}
        if ($_POST['x'] = 5) {add_remove($five, array($one,$two,$three,$four));}


texts: Conditionally displaying a notice about free shipping in Woocommerce

texts:
I wrote PHP code to display a Woocommerce notice - "free shipping for $40 & under" only once on shop page and once on cart page, but also in cart should not be more than 40$.  The code works, but i am not sure that it is the best way to do it:

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$shop_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") ."://$_SERVER[HTTP_HOST]/shop/";

$cart_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") ."://$_SERVER[HTTP_HOST]/cart/";

$first_time_shop = false;

if ((!isset($_COOKIE["mynoticeshop"]))&&($actual_link == $shop_link))
{
    $first_time_shop = true;
    setcookie("mynoticeshop", "mynoticesaleshop", time() + 600, $shop_link);
}
if ($first_time_shop) {
   function sp_custom_notice() {
        $subtotal = WC()->cart->subtotal;
        $free_shipping_threshold = 40;
        if ($subtotal < $free_shipping_threshold) {
        wc_add_notice( 'free shipping for $40 & under', 'notice' );
    }
}

add_filter( 'woocommerce_init', 'sp_custom_notice' );
}

$first_time_cart = false;
if ((!isset($_COOKIE["mynoticecart"]))&&($actual_link == $cart_link)) {
    $first_time_cart = true;
    setcookie("mynoticecart", "mynoticesalecart", time() + 600, $cart_link);
}
if ($first_time_cart) {
   function sp_custom_notice() {
        $subtotal = WC()->cart->subtotal;
        $free_shipping_threshold = 40;
        if ($subtotal < $free_shipping_threshold) {
        wc_add_notice( ' free shipping for $40 & under', 'notice' );
    }
}

add_filter( 'woocommerce_init', 'sp_custom_notice' );
}

I am new to Programming and I am interested to know if there is a better and shorter solution of this code?


texts: Quick sort implementation in JavaScript in prototype style

texts:
I have implemented quickly the quick sort algorithm in JavaScript using prototype based style.

The code is rather short (http://jsfiddle.net/b8mfY/):

<script>

"use strict";

var Sort = function( inputArray ) {
    this.arrayTest = undefined;
    this.init( inputArray );
};
Sort.prototype.init = function( inputArray ) {
    if ( inputArray instanceof Array && inputArray.length > 0 ) {
        this.arrayTest = inputArray;
        this.DumpArray( this.arrayTest );
        this.QuickSort( this.arrayTest, 0, this.arrayTest.length - 1 );
        this.DumpArray( this.arrayTest );
    }
    else console.log( 'Input argument isn\'t an array object or its length equals zero.' );
};
Sort.prototype.QuickSort = function( data, first, last ) {
    var i = first;
    var j = last;
    var x = data[ Math.ceil( ( first + last ) / 2 ) ];

    do {
        while ( data[ i ] < x ) i++;
        while ( data[ j ] > x ) j--;

        if ( i <= j ) {
            if ( i < j ) {
                if ( data[ i ] !== data[ j ] ) {
                    var tempItem = data[ i ];
                    data[ i ] = data[ j ];
                    data[ j ] = tempItem;
                }
            }
            i++;
            j--;
        }

    } while ( i <= j );

    if ( i < last ) this.QuickSort( data, i, last );
    if ( first < j ) this.QuickSort( data, first, j );
}
Sort.prototype.DumpArray = function() {
    var output = 'The content of array: [ ';

    if ( this.arrayTest instanceof Array && this.arrayTest.length > 0 ) {
        this.arrayTest.forEach( function( item ) {
            output = output.concat( [ item, ', ' ].join( '' ) );
        });
    }
    else console.log( 'Can\'t dump the input array. It\'s not an array object or its length equals zero.' );

    output = output.substring( 0, output.length - 2 );
    output = output.concat( ' ].' );
    console.log( output );
};

window.onload = new Sort([
    10,
    1,
    27,
    4090,
    100000,
    2222,
    4934
]);

</script>

I'm asking for a code review of the quick sort implementation part more than other details.


texts: Calculate all cyclic subgroups of a group under multiplication of modulo n (group theory)

texts:
The task was to calculate all cyclic subgroups of a group \$ \textbf{Z} / n \textbf{Z} \$ under multiplication of modulo \$ \text{n} \$ and returning them as a list of lists. The first level has all subgroups and the secend level holds the elements of these groups.

The programm first calculates the numbers \$ \text{g} \$ that are coprimes of \$ \text{n} \$. Each element of a cyclic subgroup can than be obtained by calculating the powers of \$ \text{g} \$.

A explanation of what cyclic groups are can be found on wikipedia: Group (mathematics).

# coding=utf-8

"""Basic usage:
$ python subgroups.py 1
[[1]]
$ python subgroups.py 7
[[1], [1, 2, 4], [1, 2, 3, 4, 5, 6], [1, 6]]
"""

import argparse
from fractions import gcd

def main():
    """Prints out the results of `calculate_subgroups()`
    """

    parser = argparse.ArgumentParser()
    parser.add_argument('modulus', type=int)
    args = parser.parse_args()

    if args.modulus > 0:
        print(calculate_subgroups(args.modulus))
    else:
        print("Please enter an integer > 0.")

def calculate_subgroups(modulus):
    """For a group of integers modulo n, n is called the `modulus`. With the
    modulus of a cyclic group, calculate all subgroups of Z/nZ.
    See Wikipedia for reference:
    http://en.wikipedia.org/wiki/Group_(mathematics)#Modular_arithmetic

    Basic usage:
    >>> calculate_subgroups(1)
    [[1]]
    >>> calculate_subgroups(4)
    [[1], [1, 3]]
    >>> calculate_subgroups(7)
    [[1], [1, 2, 4], [1, 2, 3, 4, 5, 6], [1, 6]]
    >>> calculate_subgroups(9)
    [[1], [1, 2, 4, 5, 7, 8], [1, 4, 7], [1, 8]]
    >>> calculate_subgroups(18)
    [[1], [1, 5, 7, 11, 13, 17], [1, 7, 13], [1, 17]]
    """

    # All cyclic groups have the trivial subgroup [1]
    subgroups = [[1]]
    coprimes = get_coprimes(modulus)

    for i in range(1, len(coprimes)):
        # Subgroups of cyclic groups always contain 1
        potential_subgroup = [1]

        exponent = 1
        coprime_potency = pow(coprimes[i], exponent, modulus)
        while coprime_potency != 1:
            potential_subgroup.extend([coprime_potency])
            exponent += 1
            coprime_potency = pow(coprimes[i], exponent, modulus)

        potential_subgroup = sorted(potential_subgroup)

        if potential_subgroup not in sorted(subgroups):
            subgroups.append(potential_subgroup)

    return subgroups

def get_coprimes(number):
    """Returns the coprimes of a number as a list.
    Basic usage
    >>> get_coprimes(7)
    [1, 2, 3, 4, 5, 6]
    >>> get_coprimes(10)
    [1, 3, 7, 9]
    """

    coprimes = []

    for i in range(1, number + 1):
        if gcd(number, i) == 1:
            coprimes.extend([i])

    return coprimes

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main()


texts: How to avoid mounting SQL by concatenating strings?

texts:
I found myself mounting a query by concatenating strings. This just seems wrong. Any ideas of how to avoid this kind of situation?

I'm using Rails 4, and I don't see how can Arel make things better for my case.

 def self.search(params)
    # query example
    # SELECT "jobs".* FROM "jobs"  WHERE (telecommute = 'f' AND ( freelance = 't' ) AND country = 'German')
    query = 'telecommute = ?'
    args = [params[:telecommute] == 'true']

    work_types = %W(full_time contractor freelance)
    accepted_work_types = params.find_all{ |k,v| work_types.include?(k) }.map{ |k,v| k }
    if accepted_work_types.any?
      query += " AND ( #{accepted_work_types.map{ |wt| "#{wt} = ?"}.join(" OR ")} )"
      args += accepted_work_types.map{ |wt| true }
    end

    [:city, :state, :country].each do |index|
      unless params[index].blank?
        query += " AND #{index} = ?"
        args << params[index]
      end
    end

    Job.where(query, *args)
  end


texts: C++: Am I managing memory the right way?

texts:
Also, how would I go about putting my class in another file? Thanks!

#include <iostream>

using std::cout;
using std::endl;

class Array
{

int *arrayPointer;
public:

  Array(int size);
  ~Array();

  int get(int index);
  void set(int index, int value);

protected:
  int array[];
  int size;
};

Array::Array(int theSize){
  size = theSize;
  arrayPointer = new int[size];
}

Array::~Array(){
  delete[] arrayPointer;
}

int Array::get(int index){
  return *(arrayPointer + index);
}

void Array::set(int index, int value){
  if(index >= size || index < 0){
    cout << "Ooops, index out of bounds" << endl;
  }
  else{
    *(arrayPointer + index) = value;
  }
}

/* Let's see it in action now! */

int main(){
  int size = 3;
  Array array (size);
  array.set(0, 1);
  array.set(1, 2);
  array.set(2,3);
  cout << "Index 0 = " << array.get(0) << endl;
  cout << "Index 1 = " << array.get(1) << endl;
  cout << "Index 2 = " << array.get(2) << endl;
  array.set(4, 3);
  array.set(-1, 2);
}


texts:
This challenge took me forever.  I spent a lot of time messing with regular expressions, but couldn't get it to work.  I ended up coming up with this abomination.  If anybody wants to take the time I'm interested in simpler ways to accomplish this task. (I'm a brand new pythoner)

def is_stressful(subj):
    """
        recognise a stressful email subject
        we are looking for any of: all uppercase, or ending in 3 !!!, or
        containing 'help', 'asap', or 'urgent' despite have extraneous spellings
    """

    import string

    flagged_words = ['help', 'asap', 'urgent']

    if subj[-3:] == '!!!':  # check for ending in at least 3 !!!
        return True
    if subj.isupper():   # check for uppercase
        return True

    stripped = "".join(c for c in subj if c not in string.punctuation) # get rid of confusing characters
    wordlist = stripped.lower().split(' ') # make the list to check

    for word in wordlist:  # first easy check, everything is spelled correctly
        if word in flagged_words:
            return True
    for word in wordlist:  # start the annoying check, getting rid of extra letters in flagged words
        r = 0  # our word list counter
        getgood = []
        badletters = []
        while r < len(flagged_words):  # start the loop
            for i, l in enumerate(word):  # going through each character
                if l in flagged_words[r]:  # checking for good letters
                    if l not in getgood:
                        getgood.append(l)  # no repeats except for 'a' in asap (don't know a good way for this)
                    elif l == 'a' and getgood.count('a') < 2:
                        getgood.append(l)
                else:
                    badletters.append(False)  # make sure we don't spell flagged words accidentally
            r += 1  # go to the next word in list
            i = 0  # reset letter counter
            if ''.join(getgood) in flagged_words and all(badletters):  # our final check
                return True
            getgood = []  # reset the loop
            badletters = []  # reset the loop
    return False

My tests:

print(is_stressful("H!E!L!P! its urGent asAP"))
print(is_stressful("asaaap"))
print(is_stressful("Headlamp, wastepaper bin and supermagnificently"))
print(is_stressful("I neeed advice!!!!"))

Thanks for any tips!


texts: Convert a dictionary of iterables into an iterator of dictionaries

texts:
I have a user-editable dictionary of content used to fill in a string.Template and I wanted to allow the user to fill the same template with several values at once.

Using only values, itertools.product would be enough for my needs but I needed dictionaries to fill in a template. I also wanted users to be able to enter a single string or numerical value as values for the dictionary without having anything blowing up and requiring them to encapsulate their single value in a 1-length tuple.

I used itertools.product(*map(pair_iter_safe, <the_dict>.items())) to generate iterables of key-value pairs suitable for the dict() constructor or the dict.update() method. With pair_iter_safe being:

def pair_iter_safe(kv_pair):
    key, value = kv_pair
    if isinstance(value, str):
        value = (value,)
    else:
        try:
            value = iter(value)
        except TypeError:
            value = (value,)

    for val in value:
        yield key, val

For a broader picture here is a simplified example of calling code:

import sys
import string
import itertools

PARAMETERS = {
    'name': 'John Doe',
    'age': range(40,45),
    'activity': ('foo', 'bar', 'baz'),
}

SCENARIO = """\
[@campaign] @name:
    Hi! I'm @age and I like to @activity.
"""

class AtTemplate(string.Template):
    delimiter = '@'

def run_scenario(parameters, stdout):
    scenario = AtTemplate(SCENARIO).substitute(parameters)
    print(scenario, file=stdout)

def run_campaign(campaign_name='test', stdout=sys.stdout):
    parameters = {'campaign': campaign_name}
    for setup in itertools.product(*map(pair_iter_safe, PARAMETERS.items())):
        parameters.update(setup)
        run_scenario(parameters, stdout)

def pair_iter_safe(kv_pair):
    key, value = kv_pair
    if isinstance(value, str):
        value = (value,)
    else:
        try:
            value = iter(value)
        except TypeError:
            value = (value,)

    for val in value:
        yield key, val

if __name__ == '__main__':
    run_campaign()

Is there anything wrong with the approach or the pair_iter_safe function altogether?


texts:
I’m learning python and have built a very simple program that just renames files. It makes all letters lowercase and replaces spaces and %20-instances with underscores and then copies them into a ‘Finished’ folder. I’m looking for better methods and approaches of writing and structuring my code.
Can anybody find any obvious imperfections or methods of improvement? If anyone has any advice then that would be great.
My code can be found below:

import os
from shutil import copyfile

files_to_improve_dir = 'Files to Improve'
finished_files_dir = 'Finished'

print('isdir', os.path.isdir(files_to_improve_dir))

# 1 - copy files into 'finished' folder
for f in os.listdir(files_to_improve_dir):
    copyfile(os.path.join(files_to_improve_dir, f),
             os.path.join(finished_files_dir, f))

for f in os.listdir(finished_files_dir):
    new_filename = f.replace(' ', '_').replace('%20', '_').lower()
    print('f', f, 'new_filename', new_filename)
    if (f != new_filename):
        os.rename(os.path.join(finished_files_dir, f),
                  os.path.join(finished_files_dir, new_filename))


texts: Why is my Python web scraper taking so long?

texts:
I am trying to create a program to download a long list of websites using Python 3.7. By using multiprocessing for each request, my code runs much faster than when it's run synchronously.

I've added a timer to my script so I can know the execution time for the script. The one I wrote below takes on average approximately 3.5 seconds to run. However, when I use this script for my long list of URL's, it takes approximately 8 minutes to execute.

I am wondering: is it taking this long because my internet is slow? Or is my script just bad?

My internet speed is pretty low (3 mb/s download, 1 mb/s upload). If anyone has faster internet, could you post your execution time for this script along with your internet speed? This way, I can see if the bottleneck is internet speed or not.

If the bottleneck isn't internet speed, but simply that my script is bad, can anyone offer any suggestions for improving the script so that the execution time is better? Thanks coders!

from urllib.request import Request, urlopen
from multiprocessing.dummy import Pool as ThreadPool
import datetime
import time
import requests

start_time = time.time()

urls = [
  'https://en.wikipedia.org/wiki/Python_(programming_language)',
  'https://www.python.org/',
  'https://stackoverflow.com/questions/tagged/python',
  'https://github.com/python',
  'https://realpython.com/python-beginner-tips/',
  'https://pythonprogramming.net/introduction-to-python-programming/',

  ]

mylist = []

def my_function(url_to_parse):
  req = Request(url_to_parse, headers={'User-Agent': 'Mozilla/5.0'})
  resp = urlopen(req).read()
  mylist.append(resp)

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

pool = ThreadPool(8)
results = pool.map(my_function, urls)
pool.close()
pool.join()

print("--- %s seconds --- REQUESTS" % (time.time() - start_time))
```