texts: Check for idle status in meteor by using 'setInterval'

texts:
I'm trying to check in my meteor app for a defined timeout (idle user) to show a modal. But the way I did it seems a bit too complicated to me.

I'm doing a setInterval for 1 minute. Then a counter - which is stored in a Session var (maybe a local reactive var would be smarter?) - will be incremented by one. If there is any event (mousemove, keypress and so on), the counter will be reset.

Template.example.onRendered(function() {
    Session.set('idleTime', 0);
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000);

    function timerIncrement() {
        idleTime = Session.get('idleTime');
        idleTime = idleTime + 1;
        Session.set('idleTime', Session.get('idleTime'));

        if (idleTime > 14) {
            // show modal after 15 minutes
        }
    }
});

Template.example.events({
    'mousemove, mousedown, touchstart, keypress': function() {
        Session.set('idleTime', 0);
    }
});


texts: Creating every possible combination until a code word is found

texts:
I understand my main limitation is my computer's ability to compare millions of combinations but I wondered if there is any way to improve the speed at which the comparisons take place.

My code is as follows:

code = open("C:\\Users\\User\\Desktop\\code.txt").read()
dictionary = open("C:\\Users\\User\\Desktop\\dictionary.txt").read()
precomputed = open("C:\\Users\\User\\Desktop\\precompute.txt").read()
code_found = False
from timeit import default_timer as timer
import itertools
printable = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' #"!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

This sets out the file locations including the file where the 'password' is (named code).

Precomputed is a list of all combinations Printable can make saved to a .txt file:

def bruteforce_by_precomputed():
    code_found = False
    start=timer()
    for attempt in precompute.splitlines():
        if attempt == code:
            print("the word is", attempt)
            code_found = True
            break
        #if attempt != code:
            #print(attempt, "not word")
    if code_found != True:
        print("word not in dictionary")
    end = timer()
    taken = (end-start)
    print("time taken =  :", taken)

This section is comparing each precomputed value within the .txt file to check if it matches the code:

def dictionary_attack():
    for attempt in dictionary.splitlines():
        if attempt == code:
            print("the word is", attempt)
            code_found = True
            break
        #if attempt != code:
            #print(attempt, "not word")
    if code_found != True:
        print("word not in dictionary")

This section uses a .txt file with every English word for a match:

def infinately_increasing_brute():
    import itertools
    lengthoforce = 0
    while attempt != code:
        lengthoforce += 1
        for brute_attempt in itertools.product(printable, repeat = lengthoforce):
            attempt = ''.join(brute_attempt)
            if attempt == code:
                print("succesful brute, your word is: ", attempt)
                break

This section uses .product from itertools to find every combination of Printable and if not found increase the length of combination by 1:

def custom_brute():
    lengthoforce = int(input("what length to force?"))
    start = timer()
    for brute_attempt in itertools.product(printable, repeat = lengthoforce):
        attempt = ''.join(brute_attempt)
        if attempt == code:
            print("")
            print("succesful brute, your word is: ", attempt)
            print("")
            end = timer()
            print(end-start, "seconds were taken to find", attempt)
            print("")
            break

This section simply allows the user to enter the length of the combinations to compare.

I have another section of code which creates all possible combinations and saves them to a .txt file. Instead of generating possibilities, it just reads and compares, but I would like to avoid this and generate combinations and compare.


texts:
I'm looking for some JavaScript code improvement and optimization. Is it possible to optimize this block of code (for example, remove double array loop)?

replace: function(ex, str) {
    var arr = str.match(/{add_([A-Z]+)}/gi);
    if (arr && arr.length) {
       arr.each(function(e){
          var id = e.replace('{add_','').replace('}',''),
          o = Core.get_data_by_id(ex.extensions, id);

          if (o && o.status =="1") {
            str = str.replace('{add_'+id+'}', o.html);
          }
       });
    }

    var arr2 = str.match(/{banner_([0-9]+)}/gi);
    if (arr2 && arr2.length) {
       arr2.each(function(e){
         var id = e.replace('{banner_','').replace('}',''),
         b = Core.get_data_by_id(ex.banners, id);

         if (b && b.status =="1" && b.code && b.code.length) {
            var content = '

' +
            b.code.each(function(s){
               content += '
'+s.code+'
';
            });
            content += '

';
            str = str.replace('{banner_'+id+'}', content);
         }
       });
    }

    return str;
}


texts: Abstract classes and interfaces in a game inventory system

texts:
After reading a lot about interfaces, which I'm new to, I've tried implementing it in my inventory system for a game I'm working on. I have managed to create something proof of concept which seems to work as intended, but I wanted to check with more experienced C# programmers if this is the correct/best approach?

The player has an inventory, an inventory has several slots, and each slots can have several items. The player can use any of the different items (or, more precisely, item types), but how they are used differs; food items can be eaten, weapon items can be equipped etc.

So I have started with this:

public interface IUser<Item> {
    void Use ( Item usableItem );
}

public class Player : IUser<Item> {
    public float Energy { get; set; }

    public Player () {
        Energy = 0.0f;
    }

    public void Use ( Item usableItem ) {
        usableItem.Use ( this );
    }
}

public interface IUsable<Player> {
    void Use ( Player player );
}

public abstract class Item : IUsable<Player> {
    public string Name { get; set; }

    public Item () {
        Name = "ITEM WITH NO NAME";
    }

    public virtual void Use ( Player player ) {
        // Nothing here?
    }
}

public abstract class Food : Item {
    public float Energy { get; set; }

    public Food () {
        Name = "FOOD WITH NO NAME";
        Energy = 1.0f;
    }

    public override void Use ( Player player ) {
        player.Energy += Energy;
    }
}

public class Meat : Food {
    public Meat () {
        Name = "Meat";
        Energy = 10.0f;
    }
}

Does this at all make sense?


texts: Generating a table of contents with collapsible subsections, PhP or JQuery?

texts:
The code below generates tables of contents with collapsible subsections from HTML headers. I have done it for a WordPress website, so I can use either PHP or JQuery/JavaScript. I have used PHP to generate the HTML of the ToC and JQuery to collapse/un-collapse the sections.

The code works fine, but I was wondering if it could be simpler/more robust.

PHP fiddle is here: https://paiza.io/projects/fyq6rNEs5H6AO77DkDRRXQ . It outputs HTML code that goes in JSFiddle: https://jsfiddle.net/yu51a5/jasngvfz/37/

PHP code:

    $content="  {yu_TOC}
A1
a1
A2
a2
B1
b1
B2
b2
C1
c1
C2
c2
D1
d1
E1
e1
F1
f1";

    $start_text = strpos($content, '}') + 1;

    $toc_title = 'Table Of Contents';
    $id_title = /*sanitize_title*/($toc_title);

    $index = 1;
    $tableOfContents = "";
    $old_level = 0;
    $maybe_button = "";
    // Insert the IDs and create the TOC.
    $content = preg_replace_callback('#<(h[1-9])(.*?)>(.*?)</\1>#si', function ($matches) use (&$index, &$tableOfContents, &$old_level, &$id_title, &$toc_title, &$maybe_button) {
        $tag = $matches[1];
        $toc_entry_title = strip_tags($matches[3]);
        $hasId = preg_match('#id=("|”)(.*?)\1[\s>]#si', $matches[2], $matchedIds);
        $id = $hasId ? $matchedIds[2] : ($id_title . '-' . $index++ . '-' . /*sanitize_title*/($toc_entry_title));

        $new_level = intval($tag[1]);

        //
 is not closed, because we might want to add a button
        $tableOfContents_entry = "
$toc_entry_title";
        if ($new_level > $old_level) { // $new_level = $old_level + 1
            // adding a button + other html from the previous iteration
            $tableOfContents .= $maybe_button . $tableOfContents_entry;
        } else {
            // close the
's
            for ($x = $new_level; $x < $old_level; $x++) {
                $tableOfContents_entry = "
" . $tableOfContents_entry;
            }
            $tableOfContents .= "
" . $tableOfContents_entry;
        }

        // creating html in case it is needed at the next iteration
        $maybe_button = '<input class="toc_button" id="button_toc_' . $id . '"  type="button" value="+" />

';

        $old_level = $new_level;

        return "<$tag $matches[2] id='$id'>$matches[3]</$tag>↑ Back To $toc_title ↑";
     }, $content);

    // make sure all divs are closed
    $nb_opening_divs = preg_match_all('/
/i', $tableOfContents, $matches);
    $nb_closing_divs = preg_match_all('/<\/div>/i', $tableOfContents, $matches);
    for ($x = $nb_closing_divs; $x < $nb_opening_divs; $x++) {
        $tableOfContents .= "
";
    }

    $result = "
$toc_title
" . '
' . $tableOfContents . '
' . trim(substr($content, $start_text));
    echo $result;

JQuery code:

$('.toc_button').click(function() {
  if ($(this).val() === "-") {
    $(this).val("+");
  } else {
    $(this).val("-");
  }
  $('#div_' + this.id).toggle();
});


texts:
I implemented an implicit treap and tested it a little. It works fine but I'd like to know if there are ways to improve/simplify things and/or if some parts are incorrect. Later, I'll augment code to allow for more operations (interval reversal, shifts, etc..).

Treap node.

struct Node
{   int v, p, c; /* value, priority, subtree size */
    Node *l, *r; /* left and right subtrees */

    Node(int val, int priority = rand())
    {   v = val;
        p = priority;
        l = r = 0;
    }
};

Size of subtree rooted at node x.

int count(Node *x)
{   return x ? x->c : 0;
}

Merge.

void join(Node **x, Node *left, Node *right)
{   if(left == 0 || right == 0)
        *x = left ? left : right;
    else
    {   if(left->p > right->p)
        {   join(&left->r, left->r, right);
            *x = left;
        }
        else
        {   join(&right->l, left, right->l);
            *x = right;
        }
        (*x)->c = count((*x)->l) + count((*x)->r) + 1;
    }
}

Split.

void split(Node *x, int k, Node ** left, Node **right)
{   Node *tmp;
    if(x == 0) *left = *right = 0;
    else
    {   int c = count(x) - count(x->r);
        if(k < c)
        {   split(x->l, k, left, &tmp);
            *right = x, (*right)->l = tmp;
        }
        else
        {   split(x->r, k - c, &tmp, right);
            *left = x, (*left)->r = tmp;
        }
        x->c = count(x->l) + count(x->r) + 1;
    }
}

Insert element.

void insert(Node **t, int k, int v)
{   Node *n = new Node(v);
    Node *left, *right;
    split(*t, k, &left, &right);
    join(t, left, n);
    join(t, *t, right);
}

Remove element.

void remove(Node **t, int k)
{   Node *left, *mid, *tmp, *right;
    split(*t, k, &left, &mid);
    split(mid, k + 1, &tmp, &right);
    join(t, left, right);
}


texts: Reading multiple csv files in a single dataframe

texts:
I have a lot of compressed csv files in a directory. I want to read all those files in a single dataframe. This is what I have done till now:

df = pd.DataFrame(columns=col_names)
for filename in os.listdir(path):
    with gzip.open(path+"/"+filename, 'rb') as f:
        temp = pd.read_csv(f, names=col_names)
    df = df.append(temp)

I have noticed that the above code runs quite fast initially, but it keeps on getting slower and slower as it reads more and more files. How can I improve this?


texts:
I have a method that generates a 10 digit random number where each digit occurs only once.

eg:

0123456789
3645720918

Is there any way this method could be optimized/improved?

    private static String randomize(){
        Random r = new Random();
        List<Integer> digits=  new ArrayList<Integer>();
        String number = "";
        for (int i = 0; i < 10; i++) {
            digits.add(i);
        }
        for (int i = 10; i > 0; i--) {
            int randomDigit = r.nextInt(i);
            number+=digits.get(randomDigit);
            digits.remove(randomDigit);
        }
        return number;
    }


texts:
I've just started to play around with Python and I've decided to create a little script that post tweets every hour (cronjob on Ubuntu) telling what time it is.

I'm not sure if I follow best practices or if I can make the code even shorter/cleaner/nicer? I'm a C# developer so I miss a few things in Python, like string.Empty and list.First().  Do these features exist in Python?

from twitter import *
from datetime import datetime
import pytz

TOKEN = "SECRET_STUFF"
TOKEN_KEY = "SECRET_STUFF"
API_KEY = "SECRET_STUFF"
API_SECRET = "SECRET_STUFF"

def init(timestamp = datetime.now(pytz.timezone('Europe/Stockholm')).time()):
    number_of_rings = get_number_of_times_to_display_alarm(timestamp)
    send_tweet(compose_tweet(number_of_rings, timestamp))

def get_number_of_times_to_display_alarm(timestamp):
    # Convert our timestamp to 12h format, split it, select first element(hours)
    # and cast to int to remove leading 0 (e.g. 09.00 will give us 9)
    return int(timestamp.strftime("%I:%M %p").split(':')[0])

def compose_tweet(number_of_rings, timestamp):
    # Creates a tweet, e.g. "BONG...BONG...BONG #03:00
    ALERT_SOUND = "BONG"
    tweet = ""
    for i in range(number_of_rings):
        tweet += "%s%s" %(ALERT_SOUND, "..." if i < (number_of_rings - 1) else "")

    tweet += " #%s:%s" %(str(timestamp.hour).zfill(2), str(timestamp.minute).zfill(2))
    return tweet

def send_tweet(tweet):
    auth = OAuth(TOKEN, TOKEN_KEY, API_KEY, API_SECRET)
    t = Twitter(auth=auth)
    t.statuses.update(status=tweet)

init()

UPDATE
Based on the great feedback I got from @LiavK I've now updated my code as follows:

from twitter import OAuth, Twitter
from datetime import datetime
import pytz

TOKEN = "SECRET_STUFF"
TOKEN_KEY = "SECRET_STUFF"
API_KEY = "SECRET_STUFF"
API_SECRET = "SECRET_STUFF"

MY_TZ = pytz.timezone('Europe/Stockholm')
now = datetime.now(MY_TZ).time()

def get_current_hour(timestamp):
    return timestamp.hour % 12

def compose_tweet(number_of_rings, timestamp):
    # Creates a tweet, e.g. "BONG...BONG...BONG #03:00
    ALERT_SOUND = "BONG..."
    tweet = (ALERT_SOUND * number_of_rings)[:-3] # Removes last ...
    tweet += " #%s:%s" %(str(timestamp.hour).zfill(2), str(timestamp.minute).zfill(2))
    return tweet

def send_tweet(tweet):
    auth = OAuth(TOKEN, TOKEN_KEY, API_KEY, API_SECRET)
    t = Twitter(auth=auth)
    t.statuses.update(status=tweet)

def main(timestamp = now):
    number_of_rings = get_current_hour(timestamp)
    send_tweet(compose_tweet(number_of_rings, timestamp))

if __name__ == "__main__":
    main()


texts: Choose a color with probability proportionate to its weight in a group of colors

texts:
Input: An array of colors with weights. e.g [['red', 10], ['blue', 20], ['green', 30]]

Output: A random color from the array, based on it's proportion to the other colors. So for the example above, red should show up 1/6 of the time, blue 2/6, green 3/6.

I was asked this during an interview. After talking to that interviewer I went from an O(n2) solution to this, which runs in O(n). I feel like there should be a better way?

def random_color(colors_with_weights)
  probabilities = {}
  count = 0
  colors_with_weights.each do |color_weight|
    probabilities[count..count+color_weight[1]] = color_weight[0]
    count = count + color_weight[1]
  end
  random_number = rand(count)
  random_range = probabilities.keys.find { |k| k.include?(random_number) }
  probabilities[random_range]
end

colors_with_weights = [['red', 10], ['blue', 20], ['green', 30]]
puts random_color(colors_with_weights)


texts:
I've implemented a working version of Array#uniq in Ruby to answer the question here: http://www.rubeque.com/problems/like-a-snowflake, but I'd like to see if there's ways to clean up my code or some better practices I should follow?  This is my version:

class Array
  def uniq(&block)
    objs = []
    yield_vals = []
    self.each do |obj|
      yield_val = yield obj
      unless yield_vals.include?(yield_val)
        yield_vals.push(yield_val)
        objs.push(obj)
      end
    end
    objs
  end
end


texts:
So I needed a a star rating feature to appear in my app - it doesn't need to be interactive.

I have my app connected to a database I've set up in Parse, and I've made a column for OurRatingof type Number, and I just set a number between 0.5 and 5.

In my custom cell, I have 5 images which will display my star images. The code I've done is as follows:

//I define my images at the top

var fullStarImage: UIImage = UIImage(named: "starFull.png")!
var halfStarImage: UIImage = UIImage(named: "starHalf.png")!
var emptyStar: UIImage = UIImage(named: "starEmpty.png")!

Then further down in my table method, I have:

//Star Rating System
    if let ourRating = object?["OurRating"] as? Double {

    if ourRating == 0.5 {
        cell?.star1.image = halfStarImage
    }
    if ourRating == 1 {
        cell?.star1.image = fullStarImage
    }
    if ourRating == 1.5 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = halfStarImage
    }
    if ourRating == 2 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
    }
    if ourRating == 2.5 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = halfStarImage
    }
    if ourRating == 3 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = fullStarImage
    }
    if ourRating == 3.5 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = fullStarImage
        cell?.star4.image = halfStarImage
    }
    if ourRating == 4 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = fullStarImage
        cell?.star4.image = fullStarImage
    }
    if ourRating == 4.5 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = fullStarImage
        cell?.star4.image = fullStarImage
        cell?.star5.image = halfStarImage
    }
    if ourRating == 5 {
        cell?.star1.image = fullStarImage
        cell?.star2.image = fullStarImage
        cell?.star3.image = fullStarImage
        cell?.star4.image = fullStarImage
        cell?.star5.image = fullStarImage
    }

}

This code WORKS! Nothing wrong with what it produces, I'm using wondering if there was a better way I could have written this? Maybe to reduce the amount of code?

Any advice is appreciated.


texts: I have a query like this that seems complicated and I want to do it by using Java Stream Api

texts:
I have method that fetches sorted and filtered data from Mysql Database, Firstly I had done It by using Java. Now I did it by Mysql but I don't like the way the code looks
I have entity that named Order and It looks like this
public class Order implements Serializable {
    private int orderId;
    private int userId;
    private int carId;
    private String userAddress;
    private String userDestination;
    private double orderCost;
    @JsonSerialize(using = CustomLocalDateTimeJsonSerializer.class)
    private LocalDateTime orderDate;
//getters, setters
}

Method that performs all work
@Override
    public List<Order> findFilSortOrders(Map<String, String> filters, String sortedColumn, boolean descending, int startRow, int rowsPerPage) {
    StringBuilder query = new StringBuilder("SELECT*FROM (SELECT*FROM user_order ");
    ResultSet resultSet = null;
    LinkedHashMap<String,String> filterToQuery;
    List<String> values = new ArrayList<>();
    List<String> keys = new ArrayList<>();
        List<Order> orders = new ArrayList<>();
        if(filters!=null){
            query.append("WHERE ");
            filterToQuery = new LinkedHashMap<>(filters);
            values = new ArrayList<>(filterToQuery.values());
            keys = new ArrayList<>(filterToQuery.keySet());
            keys.forEach(key->
        {
            if(key.equals("orderDate")){
                query.append("date_format(").append(key).append(",'%Y-%m-%d %H:%i') = ? AND ");
            }else{
                query.append(key).append(" = ? AND ");
            }
        });
            query.setLength(query.length()-4);
    }
        query.append(" LIMIT ?, ?) a").append(" ORDER BY ").append(sortedColumn).append(" ").append(descending?"DESC":"ASC;");
    try(Connection connection = MySQLDAOFactory.getConnection();
    PreparedStatement statement = connection.prepareStatement(query.toString())){
       for (int i=0;i<values.size();i++){
           switch (keys.get(i)){
               case "orderId":
               case "userId":
               case "carId":{
                   statement.setInt(i+1, Integer.parseInt(values.get(i)));
                   break;
               }
               case "orderDate":
               case "userAddress":
               case "userDestination":{
                  statement.setString(i+1,values.get(i));
                   break;
               }
               case "orderCost":{
                   statement.setDouble(i+1,Double.parseDouble(values.get(i)));
                   break;
               }
           }
       }
       statement.setInt(values.size()+1,startRow);
       statement.setInt(values.size()+2,rowsPerPage);
        resultSet = statement.executeQuery();
        while(resultSet.next()){
            Order order = new Order();
            order.setCarId(resultSet.getInt("carId"));
            order.setOrderId(resultSet.getInt("orderId"));
            order.setUserId(resultSet.getInt("userId"));
            order.setUserAddress(resultSet.getString("userAddress"));
            order.setUserDestination(resultSet.getString("userDestination"));
            order.setOrderCost(resultSet.getDouble("orderCost"));
            order.setOrderDate(resultSet.getTimestamp("orderDate").toLocalDateTime());
            orders.add(order);
        }
    }catch (SQLException e){
        LOGGER.error(e);
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            LOGGER.error(throwables);
        }
    }
     return orders;
    }

This code works but I dont like it looks If you could help me improve the code, I would be very grateful. Thanks for answering.


texts:
I am retrieving data from Postgres (jsonb type) and I need to return an OrderedDict that has a predictable order for human and machine consumption.  There are some common(ish) keys that should be used to direct precedence of values of common types (based on a predefined order and if sort_order is defined).  Otherwise, sort order should fall back to key based lexicographic ordering.

The general intent is to have a predictable, 'sane', represenation of composite dicts.

The basic algorithm is:

Dicts come before lists
Values that are NOT iterables or mapping take precedence over objects that are.
Values of the same type whose keys are not in sort_order are considered equal and should be sorted lexicographically.
Obj A takes precedence over Obj B if type(A[0]) == type(B)  and [0] in sort_order not B[0] in sort_order
if all([type(A[1]) == type(B[1]), A[0] in sort_order, B[0] in sort_order]) then the index position of the object key is the precedence determinant.

I have attempted several implementations, but I have not been able to come up with anything that I would consider pythonic/elegant.

Here is the latest incarnation:

# -*- coding: utf-8 -*-

import json
from collections import OrderedDict

def dict_sort(obj, sort_order=None):
    def seq(s, o=None, v=None):
        return str(s) + str(o) + str(v) if o is not None else str(s)

    order_seq = None
    if sort_order is not None and obj[0] in sort_order:
        order_seq = [i for i, v in enumerate(sort_order) if v == obj[0]][0]

    if isinstance(obj[1], dict):
        return seq(2, order_seq, obj[0]) if order_seq else seq(3)
    elif isinstance(obj[1], list):
        return seq(4, order_seq, obj[0]) if order_seq else seq(5)
    else:
        return seq(0, order_seq, obj[0]) if order_seq else seq(1)

def comp_sort(obj, sort_order=None):
    data = OrderedDict()
    if isinstance(obj, dict):
        for key, value in sorted(obj.items(), key=lambda d: dict_sort(d, sort_order)):
            if isinstance(value, dict) or isinstance(value, list):
                data[key] = comp_sort(value, sort_order)
            else:
                data[key] = value
    elif isinstance(obj, list):
        try:
            return sorted(obj)
        except:
            items = []
            for value in obj:
                if isinstance(value, dict) or isinstance(value, list):
                    items.append(comp_sort(value, sort_order))
                else:
                    items.append(value)
            return items
    return data

# thx herk

Here is a sample data set.


texts:
I'm trying to write a Poker hand evaluator using NumPy, because I find pure Python is pretty slow.

def eval_(*args):

    if len(args) == 5:
        hand = np.asarray([*args], dtype=np.int8)
    else:
        hand = np.asarray(args[0], dtype=np.int8)

    ranks = np.bincount(hand // 4, minlength = 13)
    count = np.array([np.where(ranks == count)[0] for count in range(5)])

    if len(count[4]):
        return 8, count[4][0], count[1][0]
    if len(count[3]) and len(count[2]):
        return 7, count[3][0], count[2][0]
    if len(count[3]):
        return 4, count[3][0], count[1][1], count[1][0]
    if len(count[2]) == 2:
        return 3, count[2][1], count[2][0], count[1][0]
    if len(count[2]):
        return 2, count[2][0], count[1][2], count[1][1], count[1][0]

    is_straight = count[1][0] + 4 == count[1][4]
    is_acestraight = count[1][4] - 9 == count[1][3]
    is_flush = 5 in np.bincount(hand % 4)
    if is_straight: return 5 + 4 * is_flush, count[1][4]
    if is_acestraight: return 5 + 4 * is_flush, 3

    return 1 + 5 * is_flush, count[1][4], count[1][3], count[1][2], count[1][1], count[1][0]

I'm not satisfied with my code. I don't like all kinds of count[1][2] calls, I should be able to just attach the whole count[1] array to my return value but I don't know how to do it. And I have trouble with np.where(). I don't think I should use list comprehension for different count values on this:

count = np.array([np.where(ranks == count)[0] for count in range(5)])

but I have no idea.


texts:
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.

  To determine the next value of the i-th bit, look at the current
  value of the bits at positions i−1 and i+1 (if they exist; otherwise
  assume them to be 0). If you see exactly one 1, then the next value of
  the i-th bit is 1, otherwise it is 0. All the bits change at once, so
  the new values in the next state depend only on the values in the
  previous state. We consider the universe dead if it contains only
  zeros.

My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.

import sys

def get_bit(bits, i):
    if 0 <= i < len(bits):
        return int(bits[i])
    else:
        return 0

def get_new_state(old_state):
    new_state = []
    for index in range(len(old_state)):
        if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
            new_state.append(0)
        elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
            new_state.append(1)
    return new_state

def is_dead(state):
    if set(state).pop() == "1":
        return False
    elif set(state).pop() == 1:
        return False
    elif len(set(state)) == 1:
        return True
    else:
        return False

def foresee_fate(state):
    seen = []
    while True:
        if is_dead(state):
            return False
        if state in seen:
            return True
        seen.append(state)
        state = get_new_state(state)

num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
    cur_state = []
    case = sys.stdin.readline().strip()
    for char in case:
        cur_state.append(char)
    print("LIVES" if foresee_fate(cur_state) else "DIES")

What are some ways to improve the performance of my code?


texts: Batch file to copy specific folders and to delete the folder which is not copied

texts:
This is the batch file I have created which copy the specific folders which I want. I use the specific server folder name of which I want to copy. This batch file will also delete the folder which you don't want to copy. My batch file will ask for the user input for the source path as well the destination path and to name the folder. If the user does not provides the source and destination path and folder name it will take the default value. I have also added a command which will start the specific service which is stopped. The concept of starting the service is totally related to server where we use to down the server. I also wanted my code to ask whether to delete those logs.

Please help me regarding this script and please suggest any improvements.

@echo off
:: variables
echo This script takes the backup of file SwiftALM Important folders
set /P SOURCEPATHPATH=Enter SOURCEPATH example:D:\backup\test\swift (default SOURCEPATH path=D:\backup\test\swift):
 if "%SOURCEPATH%"=="" (
set SOURCEPATH=D:\backup\test\swift
) else (
 set SOURCEPATH=%SOURCEPATH%
)
set /P DESTPATH=Enter DESTPATH (default DESTPATH path=D:\backup4):
if "%DESTPATH%"=="" (
set DESTPATH=D:\backup4
) else (
 set DESTPATH=%DESTPATH%
)
set /P folder=Enter folder name:
echo default folder name=%Date:~-7,2%-%Date:~-10,2%-%Date:~-4,4%
if "%folder%"=="" (
set folder=%Date:~-7,2%-%Date:~-10,2%-%Date:~-4,4%
) else (
 set folder=%folder%
)
echo folder=%folder%
mkdir %DESTPATH%\%folder%
set xcopy=xcopy /E/V/Q/F/H/I
echo echo conf folder will be copied
%xcopy% %SOURCEPATH%\conf %DESTPATH%\%folder%\conf
echo conf folder is copied
echo lib folder will be copied
%xcopy% %SOURCEPATH%\lib %DESTPATH%\%folder%\lib
echo lib folder is copied
echo deploy folder will be copied
%xcopy% %SOURCEPATH%\deploy %DESTPATH%\%folder%\deploy
echo deploy folder is copied
echo deployers folder will be copied
%xcopy% %SOURCEPATH%\deployers %DESTPATH%\%folder%\deployers
echo deplyers folder is copied
echo files will be copy press enter to proceed
pause
echo Deleting folders after copy
rmdir /s %SOURCEPATH%\tmp
rmdir /s %SOURCEPATH%\data
rmdir /s %SOURCEPATH%\work
echo folders have been removed
pause
echo To Start the task scheduler
sc start "Schedule"
pause


texts:
I'm working on HackerRank to try to improve my Haskell skills along side with reading Haskell Programming from first principles. I wrote a program that works, but it seems to time out on large input sets. The purpose of the program is

Given a list of n integers a = [a1, a2, ..., an], you have to find those integers which are repeated at least k times. In case no such element exists you have to print -1.
If there are multiple elements in a which are repeated at least k times, then print these elements ordered by their first occurrence in the list.

So I wrote a few different functions to help with this.
count which counts the number of occurrences of an element in a list
count :: Eq a => Integral b => a -> [a] -> b
count e [] = 0
count e (a:xs) = (count e xs +) $ if a == e then 1 else 0

uniq which removes duplicates from a list
uniq :: Eq a => [a] -> [a] -> [a]
uniq x [] = x
uniq [] (a:xs) = uniq [a] xs
uniq x (a:xs) = if a `elem` x then uniq x xs else uniq (a:x) xs

filt which filters through a list and removes elements that don't occur at least k times.
filt :: Show a => Num a => Read a => Eq a => Integral b => [a] -> b -> [a]
filt a b = reverse $ uniq [] [i | i <- a, count i a >= b]

printList which prints a list as a space separated list or prints -1 if the list is empty.
printList :: Show a => [a] -> IO ()
printList [] = putStrLn "-1"
printList a = putStrLn $ unwords [show i | i <- a]

readNumbers which takes a space separated string and returns a Num list from that string.
readNumbers :: Show a => Eq a => Num a => Read a => String -> [a]
readNumbers = map read . words

run which throws all of this together and runs this n times.
run :: (Show a, Eq a, Num a, Read a) => a -> IO ()
run 0 = putStr ""
run n = do
  a <- getLine
  b <- getLine
  printList $ filt (readNumbers b) (readNumbers a !! 1)
  run $ n - 1

main the main function. It gets a number n and then calls run n.
main :: IO ()
main = do
  a <- getLine
  run $ read a

This code works, for example, with the input
3
9 2
4 5 2 5 4 3 1 3 4
9 4
4 5 2 5 4 3 1 3 4
10 2
5 4 3 2 1 1 2 3 4 5

and gives the desired output of
4 5 3
-1
5 4 3 2 1

However, with larger datasets this code is incredibly slow. I'm guessing it's because the recursion is less than optimal, but I can't really pinpoint what is taking so long. My best guess is that uniq or count is the limiting factor, but I can't figure out how to optimize them.


texts: Calculate Work Week Hours by Shift (stored as dict)

texts:
I am crazy about needing to calculate my work shifts for my part-time job while attending University.  This is because I cannot work more than 20 hours a week.

  Yes, this code is crap, I wrote it in 20 minutes... my brain operates kinda like a pachinko machine, and whatever it writes for stupidly annoying scripts like this it just writes, screw quality.  Don't ding me for that, please, I just haven't had enough coffee or sleep lately to write better code.

So, I wrote a Python script that lets me do one of two things:

Process my 'normal' work schedule, which is hardcoded as the 'default' schedule
Process the first argument (which should be a dict containing the name of the day of the week, and contain a list of lists which contain the start and end time for each shift, using 24hr time format), passed into the program at runtime as an argument.

Regardless of these cases, it will always return something like:

Total Weekly Hours: 15.0

(as an example, using the 'default' hardcoded schedule).

When executing as a shell command, or with the python executable, you have to put the "schedule" dict in quotes.  This is an example of execution of the file and passing in a schedule where I have to take on additional hours (on the command line, so this would be executed verbatim):

./workhours.py "{'Monday': [['09:00', '13:00']], 'Tuesday': [['09:00', '10:30'], ['17:00', '19:00']], 'Wednesday': [['09:00', '11:00']], 'Thursday': [['13:00', '15:00']], 'Friday': [['10:00', '17:00']]}"

As long as the first argument is an entire dict, as a string so it's parsed right by the application, it seems to work fine, and gives me correct values (for example, the last example would return a value of 18.5 hours which is accurate).

While this works, I'd like suggestions for how I could improve this.  It's a quickly-thrown-together script that does what I want, but suggestions for improvement are definitely accepted.

This is the code:

workhours.py:

#!/usr/bin/python
import sys
import os
from ast import literal_eval
from datetime import datetime, timedelta

_TIME_FORMAT = '%H:%M'

def set_timeformat(self, formatstr=_TIME_FORMAT):
    self._TIME_FORMAT = formatstr

_DEFAULT_SCHEDULE = {
    'Sunday': None,
    'Monday': [['09:00', '13:00']],
    'Tuesday': None,
    'Wednesday': [['09:00', '11:00']],
    'Thursday': [['13:00', '15:00']],
    'Friday': [['10:00', '17:00']],
    'Saturday': None
}

def _calc_shift_hours(shift):
    tdelta = datetime.strptime(shift[1], _TIME_FORMAT) - datetime.strptime(shift[0], _TIME_FORMAT)

    if tdelta.days < 0:
        tdelta = timedelta(days=0, seconds=tdelta.seconds, microseconds=tdelta.microseconds)

    return tdelta.seconds / 3600.0

def _calc_workhours(sched=_DEFAULT_SCHEDULE):
    hours = {
        'Sunday': 0,
        'Monday': 0,
        'Tuesday': 0,
        'Wednesday': 0,
        'Thursday': 0,
        'Friday': 0,
        'Saturday': 0
    }

    totalhours = 0

    for day in sched.iterkeys():
        if sched[day] is None:
            pass
        else:
            # noinspection PyTypeChecker
            for shift in sched[day]:
                hours[day] += _calc_shift_hours(shift)
            totalhours += hours[day]

    os.system('clear')
    print "Total Weekly Hours: %s" % totalhours

if __name__ == '__main__':
    try:
        dictarg = literal_eval(sys.argv[1])
        if isinstance(dictarg, dict):
            schedule = dictarg
        else:
            schedule = _DEFAULT_SCHEDULE
    except IndexError:
        schedule = _DEFAULT_SCHEDULE

    _calc_workhours(schedule)


texts: HackerRank: Left Array Rotation in Python

texts:
Here is the problem on HackerRank. I want to know how I can improve this code. I am mainly trying to improve the following skills: Documentation, functional programming (top-down approach), accurately estimating Big O Complexity, Space Complexity, doc-testing, and readable code.

Sometimes I feel that my code is simply too clustered with documentation, so I am not sure how much or how little to add. Should I write param in my documentation how I have it written? Can I improve my space/time complexity for this algorithm? I tried to focus on changing the list in place so as not to increase the space complexity. Is my estimate of O(2N) correct for my main array_left_rotation() function?

If I want to write about the worst case complexity, is how I wrote it the correct way to write it and is that where I am supposed to write it?

The mysterious no return functions and other funky stuff under the main function are the courtesy of HackerRank. Just in case you want to view it on Github

I wish to improve code style, space/time complexity analysis, and readability.

"""
Author: Rafeh Qazi
Program: Array Left Rotation (Hackerrank Challenge)
Modified: October 2016
Submit this code at: https://www.hackerrank.com/challenges/ctci-array-left-rotation
"""

def array_left_rotation(int_list, shift):
    """
    Given an array of n integers and a number, d, perform d left rotations on the array.
    Then print the updated array as a single line of space-separated integers.
    :param int_list: list
    :param shift: int

    Worst Case Time Complexity: O(2N)

    Worse Case Space Complexity: O(N)

    >>> array_left_rotation([1, 2, 3, 4, 5], 1)
    2 3 4 5 1

    >>> array_left_rotation([2, 3, 4, 5, 1], 3)
    5 1 2 3 4
    """
    pairs = new_index_value_pairs(int_list, shift)
    replace_int_list(int_list, pairs)
    print(*int_list, sep=' ')

def new_index_value_pairs(int_list, shift):
    """
    Create a list of shifted index and value tuples.
    :param int_list: list
    :param shift: int
    :return: list

    Worst Case Complexity: O(N)

    >>> new_index_value_pairs([10, 20, 30], 1)
    [(2, 10), (0, 20), (1, 30)]
    """
    return [((index - shift) % len(int_list), value) for index, value in enumerate(int_list)]

def replace_int_list(int_list, pairs):
    """
    Map the the shifted index value pairs onto the original int_list.
    :param int_list: list
    :param pairs: list

    Worst Case Complexity: O(N)

    >>> int_list = [10, 20, 30]
    >>> replace_int_list(int_list, [(0, 20), (1, 30), (2, 10)])
    >>> int_list
    [20, 30, 10]
    """
    for index, value in pairs:
        int_list[index] = value

if __name__ == '__main__':
    import doctest

    doctest.testmod()
    _, shift = map(int, input().strip().split())
    int_list = list(map(int, input().strip().split()))
    array_left_rotation(int_list, shift)

Update:  I am aware of the deque data structure from collections module in Python. However, I wanted to challenge myself.


texts: Assign Specific Value If BitField Is True

texts:
My colleague created this SQL to handle certain user selections which are based on an on/off bit flag. The goal is to identify those individual bit flags with a specific integer which will be used in a later SQL to group specific types which the flags relate to.

What would be a more elegant way of doing this on SQL-Server 2012 which would remove the proceeding if statements?

DECLARE @ct1 int;
DECLARE @ct2 int;
DECLARE @ct3 int;
DECLARE @ct4 int;

SELECT  @ct1 = ISNULL(TypeDaily, 0) ,
        @ct2 = ISNULL(TypeTerm, 0) ,
        @ct3 = ISNULL(TypePerformance, 0) ,
        @ct4 = ISNULL(TypeWeather, 0)
FROM    ReportTable
WHERE   ReportSelectionId = @ReportSelectionId;

if (@ct2 > 0)
   select @ct2 = 2

if (@ct3 > 0)
   select @ct3 = 3

if (@ct4 > 0)
   select @ct4 = 4

The Type.... fields above are valid bit columns on the ReportTable table.


texts:
All,
I barely have a week of angular behind me and I am still struggling with some of the concepts. Below is a piece of code I came up with. The idea is to let the user add/delete entries in a model (in practice, the model is read from a json and is more complex than what is presented). While this code seems to work, I'm wondering whether it's "proper" angular:

Is it OK to leave the add_item function in the controller ? I understand that any DOM manipulation should be put in a directive, but it's only manipulating the model, right?
Shouldn't the del_item be in the controller too, then?
Using the index to control which item to delete look a bit dangerous, what would be a better alternative?

Thanks for any input.

   {{items}}

     <button type="button" ng-click="add_item()">
       New item
     </button>

       <display-item idx={{$index}}></display-item>


texts: Prepared statements from security viewpoint

texts:
I've decided to go with OOP style and prepared statements, and so far I like it a lot more than the procedural style.  It's much more understandable in my opinion.

For this code review, I've just included my PHP code that interacts with my MySQL database. Everything is working how it should, but I'd like to know if you see anything that could be improved upon. Also, I'd like a security analysis/review of the code. Is my code safe from SQL injection since I'm using prepared statements? Is there anything else I should be doing?

I have this function in a folder/file above public_html, and just require it on the pages that need it.

function connectToDatabase() {
    $connect = new mysqli('localhost', 'myUserName123', 'myPassword123', 'myDatabaseName');
    if ($connect->connect_error) {
        exit;
    }
    return $connect;
}

This is the function I use to pull the question text, and answer integers from the database to display on the website.

function getQuestionsAndAnswers($connect) {
    $questionArray = array();
    $answersArray = array();
    $getStuff = $connect->prepare('SELECT `question`, `answer` FROM `Quizzes` WHERE `questionNumber`<? ORDER BY `questionNumber` ASC');
    $getStuff->bind_param('i', $questnum);
    $questnum = 21;
    $getStuff->execute();
    $getStuff->bind_result($singleQuestion, $singleAnswer);
    while ($getStuff->fetch()) {
       array_push($questionArray, $singleQuestion);
       array_push($answersArray, $singleAnswer);
    }
    $getStuff->close();
    $connect->close();
    return array($questionArray, $answersArray);
}

This is the code that gets run after the user takes the math quiz, submits his answers, and I validate that the answers are all integers, etc.

$connect = connectToDatabase(); // open database connection here

$stmt1 = $connect->prepare("SELECT MAX(`id`) FROM QuizAdministration");
$stmt1->execute();
$stmt1->bind_result($maxId);
$stmt1->fetch();
$stmt1->close();

$stmt2 = $connect->prepare("INSERT INTO PlayerAnswers (`QuizAdministrationId`, `questionNumber`, `playerAnswer`) VALUES (?, ?, ?)");
    for ($yty = 1; $yty < 21; $yty += 1) {
        $stmt2->bind_param('iii', $QuizAdministrationid, $questnum, $questansw);
        $QuizAdministrationid = $maxId + 1;
        $questnum = $yty;
        $questansw = $_POST['qora'.$yty];
        $stmt2->execute();
    }
    $stmt2->close();

$stmt3 = $connect->prepare("INSERT INTO QuizAdministration (`quizNumber`, `cookie`, `ip`, `score`) VALUES (?, ?, ?, ?)");
$stmt3->bind_param('issi', $quizNumber, $playerCookie, $playerIP, $playersPercent);
$quizNumber = 1;
$playerCookie = session_id();
$playerIP = getUserIp();
$playersPercent = 90;
$stmt3->execute();
$stmt3->close();

$connect->close(); // close database connection here
header('Location: http://www.myWebsite.com/quizResults.php');
exit;


texts:
I have two arrays:

first one is ip addresses from billing for blocking
second is ip addresses from firewall - already blocked

My task is, compare it, and if ip address new in billing list - block it (run a command) if ip address not in billing list  unblock it.

Current solutions is:

#billing->router
foreach $ip (@ipfw_ip) {
    if ( grep $_ eq $ip, @bill_ip ) {
    } else {
        `/sbin/ipfw table 11 add $ip`;
        print "$ip blocked\n";
    }
}

#router->billing
foreach $ip (@bill_ip) {
    if ( grep $_ eq $ip, @ipfw_ip ) {
    } else {
        `/sbin/ipfw table 11 delete $ip`;
        print "$ip unblocked\n";
    }
}

I hate 'grep' in the loops, and looking for better solution. Any advice?

UPD:
difference function from Set::Functional helps me.

for(difference (\@ipfw_ip, \@bill_ip)) {
     ..._;
}
sub difference(@) {
    my $first = shift;

    return unless $first && @$first;

    my %set;

    undef @set{@$first};

    do { delete @set{@$_} if @$_ } for @_;

    return keys %set;
}


texts: Indenting and dedenting ASP Classic code with Python

texts:
I've created a Python script that tries to properly indent and dedent ASP code. Similar to http://www.aspindent.com/

Since I've began using it I've noticed some edge cases that I hadn't anticipated. The reason these edge-cases appear is because of the fact that I'm not parsing straight ASP code. There are instances of HTML and Javascript in the file, thus, some of this is causing indentations to occur sporadically throughout the final output. I realize that part of the problem stems from my regex use. I'm here to see if there is a cleaner way to go about this.

import re, sys

class Indenter:
    def __init__(self, string):
        self.space = 0
        self.count = 0
        self.string = string

    def print_ln(self, string):
        sys.stdout.write(" " * self.space + str(string))
        sys.stdout.flush()

    def indent(self):
        self.print_ln(self.string[self.count])
        self.space += 4

    def dedent(self):
        self.space -= 4
        self.print_ln(self.string[self.count])

    def dedent_indent(self):
        self.space -= 4
        self.print_ln(self.string[self.count])
        self.space += 4

    def main(self):
        while self.count < len(self.string):
            if re.search("^\s*if.*then", str(self.string[self.count]), re.IGNORECASE):
                self.indent()
            elif re.search("^\s*for", str(self.string[self.count]), re.IGNORECASE):
                self.indent()
            elif re.search("^\s*with", str(self.string[self.count]), re.IGNORECASE):
                self.indent()
            elif re.search("^\s*do until", str(self.string[self.count]), re.IGNORECASE):
                self.indent()
            elif re.search("^\s*do$", str(self.string[self.count]), re.IGNORECASE):
                self.indent()
            elif re.search("^\s*Select Case", str(self.string[self.count]), re.IGNORECASE):
                self.indent()

            elif re.search("^\s*End Select", str(self.string[self.count]), re.IGNORECASE):
                self.dedent()
            elif re.search("^\s*loop", str(self.string[self.count]), re.IGNORECASE):
                self.dedent()
            elif re.search("^\s*end with", str(self.string[self.count]), re.IGNORECASE):
                self.dedent()
            elif re.search("^\s*end if", str(self.string[self.count]), re.IGNORECASE):
                self.dedent()
            elif re.search("^\s*next", str(self.string[self.count]), re.IGNORECASE):
                self.dedent()

            elif re.search("^\s*Case", str(self.string[self.count]), re.IGNORECASE):
                self.dedent_indent()
            elif re.search("^\s*else", str(self.string[self.count]), re.IGNORECASE):
                self.dedent_indent()
            elif re.search("^\s*elseif.*then", str(self.string[self.count]), re.IGNORECASE):
                self.dedent_indent()

            else:
                self.print_ln(self.string[self.count])
            self.count += 1

with open("scratch.html") as s:
    ind = Indenter(s.readlines())
    ind.main()


texts:
I've just started learning Rust (coming from Haskell) and decided to test a toy expression interpreter.

Code:

use std::rc::Rc;

pub type RAST<T> = Rc<AST<T>>;

#[derive(Debug)]
pub enum AST<T> {
    ConstInt(isize, Rc<T>),
    Add(RAST<T>, RAST<T>, Rc<T>),
}

pub fn eval<T>(x: &RAST<T>) -> RAST<T> {
    match &**x {
        AST::Add::<T>(l, r, t) => {
            let el = eval(&l);
            let er = eval(&r);
            match (&*el, &*er) {
                (AST::ConstInt::<T>(li,_q),
                 AST::ConstInt::<T>(ri,_r)) =>
                    Rc::new(AST::ConstInt::<T>(li+ri, Rc::clone(t))),
                _ => mk_add(&el, &er, &t),
            }
        },
        _ => Rc::clone(x),
    }
}

pub fn mk_int<T>(i: isize, t: &Rc<T>) -> RAST<T> {
    Rc::new(AST::ConstInt::<T>(i, Rc::clone(t)))
}

pub fn mk_add<T>(l: &RAST<T>, r: &RAST<T>, t: &Rc<T>) -> RAST<T> {
    Rc::new(AST::Add::<T>(Rc::clone(l), Rc::clone(r), Rc::clone(t)))
}

pub fn main() {
    let a = Rc::new(());

    let x = mk_int(3, &a);
    let y = mk_int(6, &a);
    let z = mk_add(&x, &y, &a);
    let c = mk_add(&x, &z, &a);

    let r = eval(&c);
    println!("Raw: {:?}", c);
    println!("Evaluated: {:?}", r);
}

With this output:

Raw: Add(ConstInt(3, ()), Add(ConstInt(3, ()), ConstInt(6, ()), ()), ())
Evaluated: ConstInt(12, ())

I'd really appreciate any feedback on:

Am I using the "right" type for the Add subnodes (i.e. Rc)?
Is it possible to create eval as an AST method instead of a function? I kept fighting the borrow checking if x in eval was self : &AST<T> (within the impl block, of course)
Is there any way to make this program more concise/cleaner? I think I understand why all the additional wrapping and sprinkling of Rc::clone/new and lots of reference taking is needed, but was wondering if I was perhaps missing something that might make this code cleaner to read.
Any other feedback/helpful pointers would also be appreciated. Thank you!


texts:
Both of the following code give the same result.  But I'm not sure where should I put the raise statement.

def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
  for __ in range(max_iteration):
    half = start + (stop - start)/2
    if abs(f(half)) < eps or half - start < eps:
      return half
    if f(half) * f(start) > 0:
      start = half
    else:
      stop = half
  else:
    raise ValueError('Cannot find root in the given range')

Or

def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
  for __ in range(max_iteration):
    half = start + (stop - start)/2
    if abs(f(half)) < eps or half - start < eps:
      return half
    if f(half) * f(start) > 0:
      start = half
    else:
      stop = half

  raise ValueError('Cannot find root in the given range')

P.S.  I asked this question Stack Overflow and someone there suggested to ask it here.


texts:
I have written this Sudoku Generator. How good/bad is this? How can I improve this?

import java.util.Random;

public class SudokuUtility {

    static final int max = 8;
    static final int min = 0;

    static final int digitMax = 9;
    static final int digitMin = 1;

    static final int easyMin = 36;
    static final int easyMax = 49;

    static final int mediumMin = 32;
    static final int mediumMax = 35;

    static final int hardMin = 22;
    static final int hardMax = 27;

    public static void main(String[] args) {

        int[][] grid = new int[9][9];

        String option = "hard";

        Random random = new Random();

        int row = 0;
        int col = 0;

        int randomNumber = 0;
        int noOfCellsToBeGenerated = 0;

        if ("easy".equals(option)) {
            noOfCellsToBeGenerated = random.nextInt((easyMax - easyMin) + 1) + easyMin;
        } else if ("medium".equals(option)) {
            noOfCellsToBeGenerated = random.nextInt((mediumMax - mediumMin) + 1) + mediumMin;
        } else {
            noOfCellsToBeGenerated = random.nextInt((hardMax - hardMin) + 1) + hardMin;
        }

        for (int i = 1; i <= noOfCellsToBeGenerated; i++) {
            row = random.nextInt((max - min) + 1) + min;
            col = random.nextInt((max - min) + 1) + min;
            randomNumber = random.nextInt((digitMax - digitMin) + 1) + digitMin;

            if (grid[row][col] == 0 && noConflict(grid, row, col, randomNumber)) {
                grid[row][col] = randomNumber;
            } else {
                i--;
            }

        }

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                System.out.print(grid[i][j] + "  ");
            }
            System.out.println();
        }

    }

    public static boolean noConflict(int[][] array, int row, int col, int num) {

        for (int i = 0; i < 9; i++) {
            if (array[row][i] == num) {
                return false;
            }
            if (array[i][col] == num) {
                return false;
            }
        }

        int gridRow = row - (row % 3);
        int gridColumn = col - (col % 3);
        for (int p = gridRow; p < gridRow + 3; p++) {
            for (int q = gridColumn; q < gridColumn + 3; q++) {
                if (array[p][q] == num) {
                    return false;
                }
            }
        }
        return true;
    }
}


texts:
After reading Ulrich Drepper's "Futexes are Tricky", I have written the following "dumbest mutex" in C++14 using the Linux futex primitives. This mutex is simpler than Drepper's; I believe it to be correct. The reason it gets to be so simple is the same as the reason I'm calling it the "dumbest mutex": it makes a system call on every unlock, even if the mutex is not being contended and nobody's waiting for the lock.

Therefore this is not a good mutex if you care about performance.

My question is: Leaving aside the performance issue, is this a correct mutex?  Or does it, like most hand-written concurrency code, have some subtle bug?
 Stylistic comments are also welcome.

#include <atomic>
#include <linux/futex.h>
#include <syscall.h>
#include <unistd.h>

inline int futex_wait(void *addr, int block_if_value_is) {
    return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);
}

inline int futex_wake_one(void *addr) {
    return syscall(SYS_futex, addr, FUTEX_WAKE, 1, nullptr, nullptr, 0);
}

class mutex {
    std::atomic<int> m_state;
    static constexpr int UNLOCKED = 0;
    static constexpr int LOCKED = 1;
public:
    constexpr mutex() noexcept : m_state(UNLOCKED) {}

    bool try_lock() {
        return m_state.exchange(LOCKED) == UNLOCKED;
    }

    void lock() {
        while (m_state.exchange(LOCKED) != UNLOCKED) {
            futex_wait(&m_state, LOCKED);
        }
    }

    void unlock() {
        m_state = UNLOCKED;
        futex_wake_one(&m_state);
    }
};


texts:
I use Project Euler to teach me programming and not to submit any results. As such I look up the expected return values to double check my solutions.

To organise my files I use the following folder structure:

main.py
\euler # The problem files
     __init__.py # empty
     e001.py
     e002.py
     ...
\input # Additional input files
     8.dat
     11.dat
     ...

My main.py file is the common entry point. It can either run all the solved examples so far or a specific one. This second option is added that I don't need to add an if __name__ == '__main__' guard in every file. The file looks as follows:

TOP_LEVEL = "euler"

def run_module(num):
    """Run specific Problem"""
    mod = importlib.import_module('%s.e%0.3i' % (TOP_LEVEL, num))

    start = time.time()
    ist = mod.run()
    print("  %5i | %6.3f |  %s  | %i" % \
(num, time.time() - start, "ox"[ist == mod.SOLL], ist))

if __name__ == '__main__':
    N_MAX = 67

    # Pre Header
    print('Problem |  Time  | x/o | Solution')
    print("--------+--------+-----+---------")

    global_time = time.time()

    # Run over all problems
    if len(sys.argv) == 2:
        run_module(int(sys.argv[1]))
    else:
        for num in range(1, N_MAX + 1):
            run_module(num)

    # End Header
    print("--------+--------+-----+---------")
    print("Total: %.3f s" % (time.time() - global_time))

I'll show now two example files to show the source files and how old code can be reused. e018.py:

"""By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below"""

SOLL = 1074

def run(file = "input/18.dat"):
    # Parse File
    with open(file) as fid:
        tri = [[int(num) for num in line.split(' ')] for line in fid.read().split('\n')]

    # From bottom's up find the maximal value
    for row in range(len(tri) - 2, -1, -1):
        for col in range(row + 1):
            tri[row][col] += max(tri[row + 1][col], tri[row + 1][col + 1])

    return tri[0][0]

and e067.py

"""By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below"""

import e018

SOLL = 7273

def run(file = "input/67.dat"):
    # problem has been solved in set 18
    return e018.run(file = file)

Since this is the first time I tried to structure such a project, I'm quite sure there is plenty of room for optimization. I'm happy for any feedback I can get.


texts: Effieciently validate multiple DataRows with return early option

texts:
I'm looking for an efficient way to validate multiple rows originating from multiple .csv files. Below is the current code to accomplish that.
The validation logic is in the function ValidateRow(DataRow row) (not presented here).

I could think of an alternative with using Linq and performing batch.All( row => ValidateRow(row)) and adding the row to the InvalidRow property in ValidateRow. But I don't know if that is more efficient or not.

public bool ValidateBatch( IEnumerable<DataRow> batch, bool exitOnFirstError = false )
    {
      //return early if we find no datarows
      if( batch == null || batch?.Count() == 0 ) { logger.Error( MSG_NO_DATAROWS ); return false; }
      bool result = true;

      foreach( DataRow row in batch )
      {
        if( !ValidateRow( row )  )
        {
          result = false;
          // track invalid rows on a property (List<DataRow>)
          InvalidRows.Add( row );
          if( exitOnFirstError )
          {
            return result;
          }
        }
      }
      return result;
    }


texts: Forming a dictionary where all values are only conditionally set

texts:
I have lots of dictionary keys with conditional values, ternary in this case:

# cover page
data_coverPage.append({'reportCalendarOrQuarter': coverPage.reportcalendarorquarter.string if coverPage.reportcalendarorquarter else "N/A",
            'filingManager_name': coverPage.filingmanager.find_all('name')[0].text if coverPage.filingmanager.find_all('name') else "N/A",
            'filingManager_street1': coverPage.find('com:street1').string if coverPage.find('com:street1') else "N/A",
            'filingManager_city': coverPage.filingmanager.find('com:city').text if coverPage.filingmanager.find('com:city') else "N/A",
            'filingManager_stateOrCountry': coverPage.filingmanager.find('com:stateorcountry').text if coverPage.filingmanager.find('com:stateorcountry') else "N/A",
            'filingManager_zipCode': coverPage.filingmanager.find('com:zipcode').text if coverPage.filingmanager.find('com:zipcode') else "N/A",
            'reportType': coverPage.reporttype.string if coverPage.reporttype else "N/A",
            'form13FFileNumber': coverPage.form13ffilenumber.string if coverPage.form13ffilenumber else "N/A",
            'provideInfoForInstruction5': coverPage.provideinfoforinstruction5.text if coverPage.provideinfoforinstruction5 else "N/A"
            })

data.append(data_coverPage)
# print data

# info tables
for it in bf.find_all('infotable'):
    # print it.nameofissuer.text
    data_infoTable.append({'nameOfIssuer': it.nameofissuer.text if it.nameofissuer else "N/A",
                 'titleOfClass': it.titleofclass.text if it.titleofclass else "N/A",
                 'cusip': it.cusip.text if it.cusip else "N/A",
                 'value': it.value.text if it.value else "N/A",
                 'sshPrnamt': it.shrsorprnamt.sshprnamt.text if it.shrsorprnamt else "N/A",
                 'sshPrnamtType': it.shrsorprnamt.sshprnamttype.text if it.shrsorprnamt.sshprnamttype else "N/A",
                 'investmentDiscretion': it.investmentdiscretion.text if it.investmentdiscretion else "N/A",
                 'putCall': it.putCall.string if it.putCall else "N/A",
                 'otherManager': it.otherManager.string if it.otherManager else "N/A",
                 'sole': it.votingauthority.sole.text if it.votingauthority.sole else "N/A",
                 'shared': it.votingauthority.shared.text if it.votingauthority.shared else "N/A",
                 'none': it.votingauthority.none.text if it.votingauthority.none else "N/A"})

Is there a much shorter way to represent so many conditional values? I'm repeating "else 'N/A'" throughout that block of code. I could store "N/A" with a variable and refer to that variable instead of the raw string. Other than that, how would I keep things essentially DRY in this situation?


texts: Speeding up Excel distance calculation using Bing API calls

texts:
I am writing VBA in Excel to calculate the distance between an employee's home address and work address using Bing Maps API calls. The process follows this general flow:

1) Convert the employee's address to Lat-Long values using the GetLatLong function

2) Convert the employee's work address to Lat-Long values using the GetLatLong function

3) Calculate the distance between these two points using the GetDistance function

4) Calculate the drive time between these two points using the GetTime function

The spreadsheet looks like this:

The process is working, but it is excruciatingly slow. The employee population is approximately 2300, and it takes almost an hour to execute.

I am not a coder, but I can functionally modify found code to my purposes. This is an amalgamation of multiple different processes found through Google searches. The code pieces in use are:

Public Function GetDistance(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins="
    secondVal = "&destinations="
    lastVal = "&travelMode=driving&o=xml&key=<My Key>&distanceUnit=mi"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Url = firstVal & start & secondVal & dest & lastVal
    objHTTP.Open "GET", Url, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    GetDistance = Round(WorksheetFunction.FilterXML(objHTTP.responseText, "//TravelDistance"), 0) & " miles"
End Function

Public Function GetTime(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins="
    secondVal = "&destinations="
    lastVal = "&travelMode=driving&o=xml&key=<My Key>&distanceUnit=mi"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Url = firstVal & start & secondVal & dest & lastVal
    objHTTP.Open "GET", Url, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    GetTime = Round(WorksheetFunction.FilterXML(objHTTP.responseText, "//TravelDuration"), 0) & " minutes"
End Function

Public Function GetLatLong(address As String, city As String, state As String, zip As String)
    Dim firstVal As String, secondVal As String, thirdVal As String, fourthVal As String, lastVal As String
    firstVal = "https://dev.virtualearth.net/REST/v1/Locations?countryRegion=United States of America&adminDistrict="
    secondVal = "&locality="
    thirdVal = "&postalCode="
    fourthVal = "&addressLine="
    lastVal = "&maxResults=1&o=xml&key=<My Key>"
    Url = firstVal & state & secondVal & city & thirdVal & zip & fourthVal & address & lastVal
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    objHTTP.Open "GET", Url, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    GetLatLong = WorksheetFunction.FilterXML(objHTTP.responseText, "//Point//Latitude") & "," & WorksheetFunction.FilterXML(objHTTP.responseText, "//Point//Longitude")
End Function

To be clear, the process works well, just extremely slowly. Any thoughts on speeding this up?


texts: Text representation for numbers with python

texts:
Simple function which returns a text representation for numbers in range [1...1000].

N100 = 'hundred'
N1000 = 'one thousand'
N1_9 = [
    'one', 'two', 'three',
    'four', 'five', 'six',
    'seven', 'eight', 'nine',
]
N10_19 = [
    'ten', 'eleven', 'twelve',
    'thirteen', 'fourteen', 'fifteen',
    'sixteen', 'seventeen', 'eighteen',
    'nineteen',
]
Nx10 = [
    'twenty', 'thirty', 'forty',
    'fifty', 'sixty', 'seventy',
    'eighty', 'ninety',
]

def make_word(num):
    assert 0 < num <= 1000
    if num == 1000:
        return N1000
    lst = [0] * 3
    for i in xrange(3):
        div = 10 ** (2 - i)
        lst[i] = num / div
        num %= div
    res = []
    if lst[0] != 0:
        res.append(
            '{} {}'.format(N1_9[lst[0]-1], N100)
        )
    if lst[1] or lst[2]:
        if lst[1] == 0:
            res.append(
                N1_9[lst[2] - 1]
            )
        elif lst[1] == 1:
            res.append(
                N10_19[lst[2]]
            )
        else:
            if lst[2] == 0:
                res.append(
                    Nx10[lst[1] - 2]
                )
            else:
                res.append(
                    '{}-{}'.format(Nx10[lst[1] - 2], N1_9[lst[2] - 1])
                )
    return ' and '.join(res)

for x in xrange(1, 1000 + 1):
     print x, make_word(x)

Is it possible to rewrite the function a little bit cleaner? Maybe decrease a number of branches somehow


texts: Checking if a number is a perfect square (without Math)

texts:
I typed this up quickly as an intuitive solution for determining if a given number is a perfect square.

How could I improve this? I already know that it doesn't handle the case where the number is 1. I'm wondering if I could generalize the calculation so it rounds up. What can I look into to develop a mindset for tackling these sorts of problems?

int number = 1000000;
int half = (number + 2 - 1)/2;
int square = 0;
boolean isSquare = false;

for( int i = half; i > 0 ; i-- ){

    square = i*i;

    if( square > number )
        continue;

    if( square == number ){
        System.out.println( "This number is a perfect square" );
        isSquare = true;
        break;
    }

}

if( !isSquare ){
    System.out.println( "This number is not a perfect square" );
}


texts:
I'm having performance issues with this query. If I remove the status column, it runs very fast; but adding the subquery in the column section delays the query way too much  (1.02 min execution). How can I modify this query so it runs faster while still getting the desired data?

The reason I put that subquery there is because I needed the status for the latest activity; some activities have null status so I have to ignore them.

Establishments: 6.5k rows -
EstablishmentActivities: 70k rows -
Status: 2 (Active, Inactive)

SELECT DISTINCT
    est.id,
    est.trackingNumber,
    est.NAME AS 'establishment',
    actTypes.NAME AS 'activity',
    (
        SELECT stat3.NAME
        FROM SACPAN_EstablishmentActivities eact3
        INNER JOIN SACPAN_ActivityTypes at3
            ON eact3.activityType_FK = at3.code
        INNER JOIN SACPAN_Status stat3
            ON stat3.id = at3.status_FK
        WHERE eact3.establishment_FK = est.id
          AND eact3.rowCreatedDT = (
            SELECT MAX(est4.rowCreatedDT)
            FROM SACPAN_EstablishmentActivities est4
            INNER JOIN SACPAN_ActivityTypes at4
                ON est4.establishment_fk = est.id
                AND est4.activityType_FK = at4.code
            WHERE est4.establishment_fk = est.id
              AND at4.status_FK IS NOT NULL
          )
          AND at3.status_FK IS NOT NULL
    ) AS 'status',
    est.authorizationNumber,
    reg.NAME AS 'region',
    mun.NAME AS 'municipality',
    ISNULL(usr.NAME,  '') + ISNULL(+ ' ' + usr.lastName,  '')
        AS 'created',
    ISNULL(usr2.NAME, '') + ISNULL(+ ' ' + usr2.lastName, '')
        AS 'updated',
    est.rowCreatedDT,
    est.rowUpdatedDT,
    CASE WHEN est.rowUpdatedDT >= est.rowCreatedDT
         THEN est.rowUpdatedDT
         ELSE est.rowCreatedDT
    END AS 'LatestCreatedOrModified'
FROM SACPAN_Establishments est
INNER JOIN SACPAN_EstablishmentActivities eact
    ON est.id = eact.establishment_FK
INNER JOIN SACPAN_ActivityTypes actTypes
    ON eact.activityType_FK = actTypes.code
INNER JOIN SACPAN_Regions reg
    ON est.region_FK = reg.code --
INNER JOIN SACPAN_Municipalities mun
    ON est.municipality_FK = mun.code
INNER JOIN SACPAN_ContactEstablishments ce
    ON ce.establishment_FK = est.id
INNER JOIN SACPAN_Contacts con
    ON ce.contact_FK = con.id
--JOIN SACPAN_Status stat ON stat.id = actTypes.status_FK
INNER JOIN SACPAN_Users usr
    ON usr.id = est.rowCreatedBy_FK
LEFT JOIN SACPAN_Users usr2
    ON usr2.id = est.rowUpdatedBy_FK
WHERE (con.ssn = @ssn OR @ssn = '*')
  AND eact.rowCreatedDT = (
    SELECT MAX(eact2.rowCreatedDT)
    FROM SACPAN_EstablishmentActivities eact2
    WHERE eact2.establishment_FK = est.id
)
--AND est.id = 6266
ORDER BY 'LatestCreatedOrModified' DESC

I can't upload the execution plan because of rep points, but there's a 21% on one of the establishment activity tables.


texts: Getting the program's first argument as a number

texts:
I want to get the first argument as a number, if there is any. This does not feel quite right, but I don't know yet what the Rust way would be.

I'm not searching for a args-framework or something, I just want to get a grip on doing stuff with Rust.

fn limit_from_args(args: env::Args) -> i32 {
    let args: Vec<String> = args.collect();
    if args.len() > 1 {
        match args[1].parse::<i32>() {
            Ok(i) => i + 1,
            Err(_) => 101,
        }
    } else {
        101
    }
}


texts: Class that holds calculation results and has to be immutable

texts:
I'm roughly trying to follow the guidelines in "Effective Java", "Item 15: Minimize mutability", hence the class is not "final" on purpose.

Information is gathered from a number of temperature meters.
Some may fail to report, so the size of the map is not known.

The serializing bothers me. Is there a simpler way to make this class immutable ?

public class Result<T extends Number> {
    private final Map<String, T> result;

    private Result(final Map<String, T> result) {
        this.result = result;
    }

    public static final Result<Number> of() {
        return new Result<>(new LinkedHashMap<>());
    }

    /** Add or replace value. */
    public Result<T> put(final String key, final T value) {
        final Map<String, T> copy = new LinkedHashMap<>(result);
        copy.put(key, value);
        return new Result<>(copy);
    }

    @SuppressWarnings("unchecked")
    public T get(final String key) throws Exception {
        return ((T) convertFromBytes(convertToBytes(result.get(key))));
    }

    @Override
    public String toString() {
        return result.toString();
    }

    private byte[] convertToBytes(Object object) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(object);
            return bos.toByteArray();
        }
    }

    private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            return in.readObject();
        }
    }
}


texts: Avoiding a call to CommandBarControl.Picture

texts:
Earlier today, I encountered an Access Violation error when opening the VBE for SolidWorks 2006, while Rubberduck VBA was initializing.

I traced the Access Violation back to an attempt to set the Picture property of a CommandBarButton, and then posted on SO

Initially, I suspected that SolidWorks might have implemented the VBE in some wacky out-of-process way, as the Picture property uses StdOle's IPictureDisp which will throw an AccessViolation on crossing a process boundary.

But upon skipping the Picture assignments, Rubberduck was able to fully load, and I discovered that SolidWorks 2006's VBE has CommandBarControl's that don't have Picture or Mask properties.

A little more digging, and it became clear that Office first introduced Picture and Mask in Office XP, but evidently SolidWorks hadn't updated the CommandBars within their VBE implementation (they possibly used an older version of the VBA SDK?).

Rubberduck is using the embedded types of the Office Interop Assembly that contains the CommandBar types, and that is from after Office XP.

So it seems that accessing the non-existent Picture and Mask properties would ordinarily cause a catchable exception, but because they involve StdOle, .NET sees a process boundary has been crossed and throws an AccessViolation.

I had to find a way of safely setting the picture, so I've elected to cast the button to a dynamic and then try reading the property. I could have just cast to dynamic and set the Picture, but it seemed to deserve its own helper function, HasPictureProperty...

    public static void SetButtonImage(CommandBarButton button, Image image, Image mask)
    {
        button.FaceId = 0;
        if (image == null || mask == null)
        {
            return;
        }

        if (!HasPictureProperty(button))
        {
            return;
        }

        try
        {
            button.Picture = AxHostConverter.ImageToPictureDisp(image);
            button.Mask = AxHostConverter.ImageToPictureDisp(mask);
        }
        catch (COMException exception)
        {
            Logger.Debug("Button image could not be set for button [" + button.Caption + "]\n" + exception);
        }
    }

    private static bool HasPictureProperty(CommandBarButton button)
    {
        try
        {
            dynamic control = button;
            object picture = control.Picture;
            return true;
        }

        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException exception)
        {
            Logger.Debug("Button image cannot be set for button [" + button.Caption + "], because Host VBE CommandBars are too old.\n" + exception);
        }

        return false;
    }

Am I abusing dynamic in this instance? Should I have perhaps have opted for reflection over catching what might be many RuntimeBinderException's?

BTW - The upside of this fix will mean that Rubberduck VBA should now support Office 2000 and earlier, albeit the Rubberduck toolbar buttons won't have images.


texts:
Trying to create something really lightweight. Sources are on GitHub.

To create a proxy we need to define an interface first, e.g.:

// Fake Online REST API for Testing and Prototyping
[Site("https://jsonplaceholder.typicode.com")]
public interface ITypicode
{
    [Get("posts")]
    Task<BlogPost[]> GetAsync();

    [Get("posts/{0}")]
    Task<BlogPost> GetAsync(int id);

    [Post("posts")]
    Task<BlogPost> PostAsync([Body] BlogPost data);

    [Put("posts/{0}")]
    Task<BlogPost> PutAsync(int id, [Body] BlogPost data);

    [Delete("posts/{0}")]
    Task<BlogPost> DeleteAsync(int id);
}

public class BlogPost
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

At this moment we actually know enough to generate a proxy:

ITypicode typicode = RestClient.Create<ITypicode>();
BlogPost blogPost = await typicode.PutAsync(1, new BlogPost { Body = "Wow!" });
Console.WriteLine(blogPost.Body);

We can inject HttpMessageHandler:

ITypicode typicode = RestClient.Create<ITypicode>(handler);

We can also emit the proxy class for dependency injection:

Type typicodeType = RestClient.Emit<ITypicode>();

About error handling – this exception is thrown for unsuccessful HTTP status codes:

public class RestException : Exception
{
    public RestException(HttpResponseMessage response)
    {
        Response = response;
    }

    public HttpResponseMessage Response { get; }
    public override string ToString() =>
        Response.Content.ReadAsStringAsync().Result;
}

We could specify extra type parameter for the SiteAttribute:

[Site("https://jsonplaceholder.typicode.com", Error = typeof(TypicodeError))]
public interface ITypicode
{
    // …
}

to have generic exception be thrown instead:

public class RestException<TError> : RestException
{
    public RestException(HttpResponseMessage response)
        : base(response)
    {
    }

    public T Error => JsonConvert.DeserializeObject<TError>(ToString());
}

So error response body will be kindly deserialized for us.

It is possible to implement API interface on a server side ASP.NET Web API Controller also to insure compatibility.

What do you think about this design?

To be continued with implementation details.

UPDATE: Adding support for HTTP headers – something like this:

[Site("https://jsonplaceholder.typicode.com")]
public interface ITypicode
{
    [Get("posts/{0}")]
    [Header("X-API-KEY: {1}")]   // req - in
    [Header("Content-Type: {2}; charset={3}")]  // res - out
    Task<BlogPost> GetAsync(
        int id, string apiKey, out string contentType, out string charset);
}

Does it look good? Anything else that might be useful?


texts:
I am new to assembly and have made a simple addition program to sum two integers read from the keyboard. The program outputs correctly, but I want to know if there is a way to streamline my code. It seems a bit cumbersome for such a simple program and I may have instructions that are unnecessary.

# Author: Evan Bechtol
# Description: This program prompts the user to enter 2 integers and computes their sum.
#---------------------------------------------------------------------------------------#
        .data
A:          .word       # Store the number 4 as an integer in var1  # $t0 is used
B:          .word       # Store the number 2 as an integer in var2  # $t1 is used
S:          .word       # Store the sum of A and B          # $t2 is used
Prompt1:    .asciiz "Please enter first number: "
Prompt2:    .asciiz "Please enter second number: "
Result:     .asciiz "The sum of A and B is: "
        .text
main:
    #--------------------------------------------------------#
    #Display first prompt
    li  $v0, 4      # Load instruction "print string"
    la  $a0, Prompt1    # Load prompt into $a0
    syscall

    #Read first integer
    li  $v0, 5      # Read 1st integer
    la  $t0, A      # $t0 = A
    syscall

    #Store first integer into memory
    move    $t0, $v0    # Move contents in $v0 to $t0
    sw  $t0, A      # A = value at $t0
    #--------------------------------------------------------#

    #Display second prompt
    li  $v0, 4      # Load instruction "print string"
    la  $a0, Prompt2    # Load prompt into $a0
    syscall

    #Read second integer
    li  $v0, 5      # Read 1st integer
    la  $t1, B      # $t0 = A
    syscall

    #Store second integer into memory
    move    $t1, $v0    # Move contents in $v0 to $t0
    sw  $t1, B      # A = value at $t0
    #--------------------------------------------------------#

    #Add the two variables
    la  $t2, S      # $t2 = S
    add     $t2, $t0, $t1   # $t2 = $t0 + $t1
    sw  $t2, S      # S = value at $t2

    #Display the Result prompt
    la  $a0, Result # Loads Output label to be printed
    li  $v0, 4      # Sysycall to print string
    syscall

    #Display the sum
    lw  $a0, S      # $a0 = value at S
    li  $v0, 1      # Syscall to print integer
    syscall

    #Exit the program
    li  $v0, 10     # Load exit code to $v0
    syscall


texts:
I sometimes need to merge some big PDF files. Looking around I decided to use PyPDF2. All files are in the same directory as the script. The code works as intended and was tested with 5 small PDF files.
I found many variations and decided to write this one myself:
import glob
from PyPDF2 import PdfFileMerger

files = sorted(glob.glob('./*.pdf'))
merger = PdfFileMerger()
filename = input("Enter merged file name: ")

for file in files:
    merger.append(file)
    print(f"Processed file {file}")

merger.write(f'{filename}.pdf')
merger.close()

All files have titles such as 1.pdf 2.pdf.
The writing to file bit seems sloppy to me but I don't know how to or even if to improve it. Did I insure that the files list will always be in alphabetical order? Are there best practice things I missed? Any other feedback is welcome as well.
The code only needs to run on windows. Cross-platform is not a concern for me. I don't anticipate memory constraints as the system it runs on has a lot of RAM. This will only run client side using Python 3.8.


texts:
I've been writing a frequency shifter in C++ for an Audio Unit plugin. The best way for me to do this while keeping a large amount of other algorithms working in the same plugin was by writing a separate header file with a full class definition that could handle all things related to the frequency shift. After a few problems with my code were cleared up in this question, I decided to go look for some optimizations and better functionality. I didn't get very far, so here we are. For any people answering my question, I ask that you address the following:

Please keep the arguments to the processBlock function as they are. I am not good enough to in any way revise how audio is supplied to the processing function.
If you've got a better FFT algorithm (you probably do), please implement it! I used an elementary function from Rosetta Code that didn't even utilize all the fancy bitshifting/reversing that it could be. I also know that Apple offers various vDSP functions for FFT, but I am even more clueless on how to implement those.
Of course, optimizations would be nice since the function is called several times a second.
I always appreciate a great lecture on code conventions, especially in C++.

Thanks in advance for any answers. The following is from FrequencyShifter.h:

#include <complex>
#include <valarray>

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

class FrequencyShifter {
float sampleRate;
public:
    FrequencyShifter() {

    }
    void setSampleRate(float inSampleRate) {
        sampleRate = inSampleRate;
    }
    void fft(CArray& x)
    {
        const size_t N = x.size();
        if (N <= 1) return;

        // divide
        CArray even = x[std::slice(0, N/2, 2)];
        CArray  odd = x[std::slice(1, N/2, 2)];

        // conquer
        fft(even);
        fft(odd);

        // combine
        for (size_t k = 0; k < N/2; ++k)
        {
            Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
            x[k    ] = even[k] + t;
            x[k+N/2] = even[k] - t;
        }
    }
    void processBlock(float *inBlock, const int inFramesToProcess, float scale) {
        //inFramesToProcess is the amount of samples in inBlock
        Complex *copy = new Complex[inFramesToProcess];
        for (int frame = 0; frame<inFramesToProcess; frame++) {
            copy[frame] = Complex((double)inBlock[frame], 0.0);
        }
        CArray data(copy, inFramesToProcess);
        fft(data);
        const float freqoffsets = 2.0 * PI/ inFramesToProcess;
        const float normfactor  = 2.0 / inFramesToProcess;
        for (int frame = 0; frame<inFramesToProcess; frame++) {
            inBlock[frame] = 0.5 * data[0].real();
            for (int x = 1; x < data.size() / 2; x++) {
                float arg = freqoffsets * x *f rame*scale;
                inBlock[frame] += data[x].real()*cos(arg) - data[x].imag()*sin(arg);
            }
            inBlock[frame] *= normfactor;
        }
    }
};


texts: Window-size-dependent content toggler for an HTML form

texts:
I had to build a responsive component which allows the user to display specific content in a page. I called it the contentToggler.

Here is my component in action

HTML Structure of togglers & contents :
On small screens : <select> with <option>
On big screens :
 containing <buttons>

<select id="paymentMethodSelector">
    <option class="js-card-selector-option" value="Carte bancaire">Carte bancaire</option>
    <option class="js-money-transfer-selector-option" value="Virement">Virement</option>
    <option class="js-check-selector-option" value="Chèque">Chèque</option>
</select>

        <input type="radio" class="js-card-selector-radio" id="radio-checkout-selector-1" checked>
        Carte bancaire

        <input type="radio" class="js-money-transfer-selector-radio" id="radio-checkout-selector-2">
        Virement

        <input type="radio" class="js-check-selector-radio" id="radio-checkout-selector-3">
        Chèque

content1

content2

content3

Associated JS which works however it makes my eyes bleed by its horrifying redundance.

var paymentMethod = {
  selectorOptionWrapper: $('#paymentMethodSelector'),
  card: {
    selectorOption: $('.js-card-selector-option'),
    selectorRadio: $('.js-card-selector-radio'),
    content: $('#paymentCardContent')
  },
  moneyTransfer: {
    selectorOption: $('.js-money-transfer-selector-option'),
    selectorRadio: $('.js-money-transfer-selector-radio'),
    content: $('#paymentMoneyTransferContent')
  },
  check: {
    selectorOption: $('.js-check-selector-option'),
    selectorRadio: $('.js-check-selector-radio'),
    content: $('#paymentCheckContent')
  }
}

function updateCheckoutContent() {
  paymentMethod.selectorOptionWrapper.on('change', function() {
    if(paymentMethod.card.selectorOption.is(':selected')) {
      paymentMethod.card.content.siblings().addClass('u-hide')
      paymentMethod.card.content.removeClass('u-hide');
    }
  });
  paymentMethod.card.selectorRadio.on('change', function() {
    if($(this).is(':checked')) {
      paymentMethod.card.content.siblings().addClass('u-hide')
      paymentMethod.card.content.removeClass('u-hide');
    }
  });

  paymentMethod.selectorOptionWrapper.on('change', function() {
    if(paymentMethod.moneyTransfer.selectorOption.is(':selected')) {
      paymentMethod.moneyTransfer.content.siblings().addClass('u-hide')
      paymentMethod.moneyTransfer.content.removeClass('u-hide');
    }
  });
  paymentMethod.moneyTransfer.selectorRadio.on('change', function() {
    if($(this).is(':checked')) {
      paymentMethod.moneyTransfer.content.siblings().addClass('u-hide')
      paymentMethod.moneyTransfer.content.removeClass('u-hide');
    }
  });

  paymentMethod.selectorOptionWrapper.on('change', function() {
    if(paymentMethod.check.selectorOption.is(':selected')) {
      paymentMethod.check.content.siblings().addClass('u-hide')
      paymentMethod.check.content.removeClass('u-hide');
    }
  });
  paymentMethod.check.selectorRadio.on('change', function() {
    if($(this).is(':checked')) {
      paymentMethod.check.content.siblings().addClass('u-hide')
      paymentMethod.check.content.removeClass('u-hide');
    }
  });
}

updateCheckoutContent(paymentMethod);


texts: Sudoku solver using backtracking, in Ruby

texts:
I wrote the below Sudoku solver, using Backtracking. Would love to hear your comments on the approach, and how I can improve readability/performance:

BLANK = '.'

def sudoku(board)
  # find first '.'
  for i in 0...board.length
    for j in 0...board[i].length
      next unless board[i][j] == BLANK

      options = get_options(board, i, j)
      return nil if options.empty? # validity check failed, kill branch

      # put options on board individually, and recurse
      proposed = board.dup
      options.each do |v|
        proposed[i][j] = v
        return proposed if sudoku(proposed)
        proposed[i][j] = BLANK
      end

      # none of the options worked
      return nil
    end
  end

  # base case: the whole board has numbers
  board
end

def get_options(board, row, col)
  # returns the list of potential options for a particular cell based
  # on the game rules:
  # - no repeated numbers in each row
  # - no repeated numbers in a column
  # - no repeated numbers in a block

  options = [*"1".."9"] # all options
  len = board.length

  # remove the options that exist in the same row
  options -= board[row].chars.uniq

  # remove the options that exist in the same column
  column = len.times.collect {|row| board[row][col]}
  options -= column.uniq

  # remove the options that exist in the same block
  block = get_block(board, row, col)
  options -= block.uniq

  # remove blanks and return
  options -= [BLANK]
end

def get_block(board, row, col)
  # returns the entire block that the row/col falls in
  row_start = 3 * (row / 3)
  col_start = 3 * (col / 3)
  block = []

  for i in 0..2
    for j in 0..2
      block << board[row_start + i][col_start + j]
    end
  end
  block
end

board =
   ["53..7....",
    "6..195...",
    ".98....6.",
    "8...6...3",
    "4..8.3..1",
    "7...2...6",
    ".6....28.",
    "...419..5",
    "....8..79"]

puts sudoku(board).inspect


texts: Function to lock a file using memcache, Version 1

texts:
I have a web application where I list files in the UI to many users at the same time. There are many people who monitor the files and process them. However, I don't want multiple users processing the same file.

I am using simple memcache dictionary as data structure to interpret if it is locked. If the key "filename" is present then it is considered as locked, otherwise the key "filename" is added (maybe with username as value) so that another user cant access it and access is granted for that user. The files "locked" by a user is processed at a later point by that user itself and no other. "Process" here means to move it to some another folder.

I was recommended to use Ghetto Central Locking by the development team but I still feel that it doesn't cover my scenario of locking and delayed action. The  problem there is that the "locking" and "action" both are combined operation but in my case can be delayed. Also the user should have the ability to unlock and not specify a time-out value as mentioned there.

So I came up with an API that covers my scenarios:

def addToCart(filename):
    ableToLock = memcache.add(filename, username)
    fileExists = os.file.ispath(filename)
    if ableToLock:
        if fileExists:
            return "Added To Cart"
        else:
            memcache.delete(filename)
            return "Processed by another user."
    else:
        if fileExists:
            return "Processed by another user."
        else:
            user = memcache.get(filename)
            return "%s is Processing" % user

def process(source):
    shutil.move(source, destination)

process happens any point of time later.

Does anyone see logical flaws or race-conditions if this code is run concurrently?

I consider it as flawed if a request comes from a user to process one of his locked file and one of the ever gets a file not found error. Scenarios like DOM manipulation etc are not considered valid because it interferes with the logic.

PS: Memcache has some drawbacks if we use as a locking mechanism like for example remote server disconnection and data eviction, but we don't consider that as an issue.


texts:
I was doing following question on leetcode: String to Integer (atoi)

Question:

  Implement atoi which converts a string to an integer.

  The function first discards as many whitespace characters as necessary
  until the first non-whitespace character is found. Then, starting from
  this character, takes an optional initial plus or minus sign followed
  by as many numerical digits as possible, and interprets them as a
  numerical value.

  The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.

  If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.

  If no valid conversion could be performed, a zero value is returned.

  Note:

  Only the space character ' ' is considered as whitespace character.
  Assume we are dealing with an environment which could only store
  integers within the 32-bit signed integer range: [−231,  231 − 1]. If
  the numerical value is out of the range of representable values,
  INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Question link: https://leetcode.com/problems/string-to-integer-atoi/

For the above question, I wrote the following code

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    let i = 0
    let output = ''
    const intMax = 2**31 - 1
    const intMin = -intMax - 1
    while (i<str.length) {
       const char = str[i]
       if (!char == " ") {
           if (char.toLowerCase() === char.toUpperCase()) {
               output = output + char
           } else if (output) {
               break
           }
           if (!output) return 0
       }
        i++
    }
    output = parseInt(output)
    if (output !== null && !isNaN(output)) {
        if (output > intMax) return  intMax
        if (output < intMin) return intMin
        return output
    }
    return 0
}

Can someone improve upon the same and give me suggestions on how I can improve my code?


texts:
What would be the best way to get the first two numbers of a string?

I can do it like this:

public static String getFirstTwoNumbersOfString(String s){
        if(s == null)
            return "";

        String numbers = "0123456789";

        String result = "";

        for(int i=0; i<s.length() && result.length()<2; i++){
            String c = String.valueOf(s.charAt(i));
            if(numbers.contains(c)){
                result += c;
            }
        }

        return result;
    }

But I think there must be a better way, more concise and with better performance.