texts:
I've been using Ruby for about a year now, mostly for small scripts with uses ranging from data munging to DevOps tasks. However, I am not intimately familiar with OOP (I appreciate the functional programming approach I'm often able to take with Ruby) and so I think my code is harder to read and debug than it could be.

I do not think my code is idiomatically Ruby, and I think I'm using a procedural style. I've included a recently-written Ruby script as an example, but at what point should one refactor into a OOP style? Is it always helpful to begin with a OOP structure? And I mean helpful in two senses: the sense that it will be easier for other team members to read the code; and also in the sense that it will make the program more robust and easier to debug.

The script below was intended as a small auditing tool. It takes a CSV (in two possible formats) and compares it to a database, but it has to do a lot of munging and matching because the results are not easily directly comparable.

#!/usr/bin/env ruby

require 'csv'
require 'date'
require 'json'
require 'mysql2'
require 'pp'

# Command line argument handling
if ARGV.length < 2
  puts "Usage: <CSV path or filename> <User's screenname>"
  puts "Outputs JSON of results we do not have in our database"
  exit
end

ARGV.each do |arg|
  # If the arg is a file that exists...
  File.file?(arg) ? @file = arg : @user = arg
end

def redacted?(filename)
  /redacted/.match(filename)
end

def make_redacted(csv)
  header = csv.slice!(0).map {|x| x.split.join.downcase.gsub(/\(\$\)/, '').to_sym}
  fd_csv = csv.map {|row| Hash[header.zip(row)]}
  fd_csv.map do |row|
    row[:name] = row[:title]
    row[:hashtag] = row[:sport]
    row[:opponent_score] = row[:oppscore]
    row[:place_finished] = row[:position].to_i
    row[:prize] = row[:winnings].to_f
    row[:date] = Date.parse(row[:date]).strftime('%Y-%m-%d')
    #row[:opponent_name] = row[:opponent]
    row[:score] = row[:score].to_f
    row[:entrants] = row[:entries].to_i
    row[:buy_in] = row[:entry].to_f
    row.delete_if { |k,v| [:title, :entries, :sport, :oppscore, :position,
     :opponent].include? k }
   end
 end

 def make_other_redacted(csv)
  ## Same sort of deal, except mapping other fields
  return dd_csv
end

# Read the database into memory too
def our_results
  # Set site ID to magic int
  site_id = redacted?(@file) ? 2 : 20
  db_hash = []
  client = Mysql2::Client.new(:host     => "hostname",
    :username => "etc",
    :password => "etc",
    :port     => etc,
    :database => "etc"
    )
  sql = "long sql query with some #{string_interpolation}"

  # Had to turn off casting due to some issues in the DB results
  db_results = client.query(sql, :symbolize_keys => true, :cast => false).each do |row|
    # Here I'm mapping hash names again
    row[:score] = row[:score].to_f
    # etc...
    db_hash << row
  end
  db_hash
end

# Takes a single object and an array
def match_redacted?(source, target)
  target.detect{|x| source[:prize] == x[:prize] &&
    # Match based on a list of hash values matching
  }
end

def match_other_redacted?(source, target)
  target.detect{|x| source[:prize] == x[:prize] &&
    # Same thing, different matching criteria
  }
end

def get_remainder(source, target)
  if redacted?(@file)
    source.delete_if {|s| match_redacted?(s, target)}
  else
    source.delete_if {|s| match_other?(s, target)}
  end
end

db_results = our_results()
# Read the csv into memory, fix it up
csv = CSV.read(@file)
source = fanduel?(@file) ? make_redacted(csv) : make_other_redacted(csv)
# Delete the results from the source that we match in the DB
remainder = get_remainder(source, db_results)
unless remainder.empty?
  puts JSON.generate(remainder)
end


texts:
I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL.

If a match is found, I find a li with a class (.index, .grid or .type) and add the active class. This is just for my main nav in an attempt to make it somewhat dynamic.

However, I feel like there is a more efficient way to code this:

$(document).ready(function() {
  var myLocation = window.location.href;
  var index = /index/i;
  var grid = /grid/i;
  var type = /type/i;
  var urlIndex = convertURL.match(index);
  var urlGrid = convertURL.match(grid);
  var urlType = convertURL.match(type);

  if (urlIndex) {
    $('.index').addClass('active');
  } else if (urlGrid) {
    $('.grid').addClass('active');
  } else if (urlType) {
    $('.type').addClass('active');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


texts: Sortings stocks into quantiles based on their signal

texts:
This function sorts stocks into quantiles.
To do so I used this function that accepts sig_df (dataframe with the timeseries of stocks signal) and number of quantiles as imput:

qs = ['Q' + str(i) for i in range(1, len(perc)+1)]
q_labels= list(itertools.chain.from_iterable(
itertools.repeat(x, int(sig_df.shape[1]/q_num)) for x in qs))

rank_labels = ['rank_{}'.format(i) for i in range(sig_df.shape[1])]

bucketed_names = pd.DataFrame(
        sig_df.columns.values[np.argsort(-sig_df.values, axis=1)],
        columns=[q_labels, rank_labels]
        )

The second function computes portfolio returns, based on the names bucketed in the function above. It accepts two input a ret_df containing stocks return and the output from the function above. To do so I used:

bucketed_returns = dict()
for i in range(1, int(ret_df.shape[1]/bucketed_names.Q1.shape[1])):
    Q = []
    for row in bucketed_names['Q' + str(i)].itertuples():
        temp = ret_df.loc[list(row[:1]) ,list(row[1:])]
        Q.append(float(np.dot(temp, weights)))
        bucketed_returns['Q' + str(i)] = Q
bucketed_returns = pd.DataFrame(bucketed_returns)

To optimize this code I thought about multiprocessing — but as a beginner I don't know how — or maybe there could be a better way remaining in pandas/numpy environment.


texts: Return most recent non null field values for multiple unknown fields

texts:
I am attempting to create a stored procedure that looks at one table and imports changes in that table to another.

This stored procedure is going to be preformed on multiple source tables and will dump out into multiple log tables.  The way the data in the log table is stored looks like this:

ID | Source_PK_field | field_1 | field_2 | field_3 | Update_Type | Updated
01 |        001      |  value  |  value  |  value  |      C      | 2015-02-04
02 |        001      |   null  |  change |   null  |      U      | 2015-02-05
03 |        001      |  change |   null  |  change |      U      | 2015-02-06

The idea being that if a record changes the log table would indicate all the fields that changed with their new values but leave fields that didn't change for the record null.

In order for this to work I need to grab a copy of what the record looked like in the most recent log version vs the current source version (the problem being that some of the values in the most recent log will be null)

In order to accomplish that I am using the current query inside my stored procedure:

DECLARE @latest_sql VARCHAR(MAX) = 'SELECT [ID], [' + @relationKey + '] '

SELECT @latest_sql = @latest_sql + ', (SELECT TOP 1 [' + COLUMN_NAME + '] FROM (SELECT * FROM ' + @changelog + ' x WHERE x.[' + @relationKey + '] = CT.[' + @relationKey +'] AND [' + COLUMN_NAME + '] IS NOT NULL) q ORDER BY UPDATED DESC) AS [' + COLUMN_NAME +'] '
FROM #COLUMN_NAMES
WHERE COLUMN_NAME != @relationKey

SET @latest_sql = @latest_sql + ' INTO ##LATEST_UPDATES FROM ' + @changelog + ' CT'

EXEC(@latest_sql)

The stored procedure requires you to pass it @changelog the log table, @source the source table and @relationKey the primary key that ties the two tables together (usually the source PK). And #COLUMN_NAMES is a temp table created before this is executed in the stored procedure that simply stores column names that match between the source table and the log table (not all fields from the source are being logged).

Now this code behaves as intended, the problem is the query takes about 10-20min to complete (just this part of the stored procedure).  The heaviest query this is used on is looking at 48 fields in a table that only stores 300K records.  There has got to be a way I can make this query faster.


texts: Dealing with multiple types in an excel sheet

texts:
I need to parse an excel sheet in order to produce an statistic, and some of the columns in the sheet can have different value types within the same column. For example:

A        B
String  String
String  String
Date    String

I cannot force the columns to have a consistent type because the input sheet belongs to one of our clients (the ones with the money), so I'm stuck with possible multiple types of values in the same column. To address this issue I made this class:

public final class MultiTypeValue {

private Map<Class<?>, Optional<?>> values;

public static MultiTypeValue newInstance(Class<?>... classes) {
    return new MultiTypeValue(classes);
}

private MultiTypeValue(Class<?>... classes) {
    if (classes == null || classes.length == 0) {
        throw new IllegalArgumentException("The classes cannot be empty");
    }

    values = new ConcurrentHashMap<>();
    for (Class<?> clazz : classes) {
        values.put(clazz, Optional.empty());
    }
}

public void put(Class<?> clazz, Object value) {
    values.put(clazz, Optional.ofNullable(value));
}

@SuppressWarnings("unchecked")
public <T> T value(Class<T> clazz) {
    return (T) values.get(clazz);
}

}

The idea was that for each type a column can have, to have an Optional associated to that type which may or may not have a value.

In terms of performance I imagine this is pretty bad, but I couldn't think another solution. Does anyone know a framework or a design pattern better than this solution?


texts: Dragging and dropping a spot using TypeScript

texts:
Currently my code is based around mouse events so that it is easier to test but I will be swapping these to touch events once I have had the code reviewed. The idea of the UX is that you need to mousedown for 500ms until you can move the spot (similar to that of iOS when re-arranging apps on the homescreen). Then the spot shows you it's in a movable state then you can drop it.

The code works exactly as I want it to but I can't help but think that I have over-engineered it. This is why I have posted for review.

Codepen Link

const spotState = {
  moveable: false
}

const spotEL = document.getElementById('spot');
const statusEL = document.getElementById('status');

spotEL.onmouseenter = function() {
  statusEL.innerHTML = "Enter";
  clearTimeout(spotState.mouseDownTimer);
  spotState.mouseDownTimer = null;
  spotState.moveable = false;
  spotState.moving = false;
  spotEL.classList.remove('moving');
  spotState.clear && spotState.clear();
}

spotEL.onmouseleave = function() {
  statusEL.innerHTML = "Leave";
  clearTimeout(spotState.mouseDownTimer);
  spotState.mouseDownTimer = null;
  spotState.moveable = false;
  spotState.moving = false;
  spotEL.classList.remove('moving');
  spotState.clear && spotState.clear();
}

spotEL.onmousedown = function(event) {
  spotState.mouseDownTimer = setTimeout(function(){
    statusEL.innerHTML = "Down";
    spotEL.classList.add('moving');
    spotState.moveable = true
    spotState.mouseDownTimer = null
    let shiftX = event.clientX - spot.getBoundingClientRect().left;
    let shiftY = event.clientY - spot.getBoundingClientRect().top;

    moveAt(event.pageX, event.pageY);

    function moveAt(pageX, pageY) {
      if (spotState.moveable || spotState.moving) {
        spotState.moving = true;
        spotEL.style.left = pageX - shiftX + 'px';
        spotEL.style.top = pageY - shiftY + 'px';
      }
    };

    function onMouseMove(event) {
      statusEL.innerHTML = "Move";
      moveAt(event.pageX, event.pageY);
    };

    document.addEventListener('mousemove', onMouseMove);
    spotState.clear = function() {
      document.removeEventListener('mousemove', onMouseMove);
    }
  }, 350);

  spotEL.onmouseup = function() {
    statusEL.innerHTML = "Up";
    clearTimeout(spotState.mouseDownTimer);
    spotEL.classList.remove('moving');
    spotEL.onmouseup = null;
    spotState.moving = false;
    spotState.moveable = false;
    spotState.mouseDownTimer = null;
    spotEL.onmousemove = null;
    spotState.clear && spotState.clear();
  };
};

spotEL.ondragstart = function() {
  return false;
};


texts: Using an Edit box in a table views header section to insert the values into the table using swift

texts:
Allow me to provide some context. I have a UITableViewCell that contains an EditText and a Button. This cell is then inserted into the self.tableView.tableHeaderView property of the table to achieve the following result:

Below is my implementation for the view controller:

class ViewController: UITableViewController {

     var data = ["Apple", "Apricot"] as NSMutableArray

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Testing"
        createHeader()
    }

    func createHeader(){

        let headerViewCell = NSBundle.mainBundle().loadNibNamed("InputToListCell", owner: nil, options: nil)[0] as! InputToListCell
        headerViewCell.setTableViewWithData(self,data: data)
        self.tableView.tableHeaderView = headerViewCell

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

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

        let cell = tableView.dequeueReusableCellWithIdentifier("rowCell", forIndexPath: indexPath)
        cell.textLabel?.text = data[indexPath.row] as? String
        return cell
    }
}

Here is my implementation for the UITableViewCell that is inserted into the table:

class InputToListCell: UITableViewCell {

    @IBOutlet weak var inputEditText: UITextField!
    var tableViewController: ViewController!
    var arrayForTable: NSMutableArray!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func setTableViewWithData(inputTableViewController:ViewController, data:NSMutableArray){
        tableViewController = inputTableViewController
        arrayForTable = data
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

    @IBAction func addValueToArray(sender: AnyObject) {
        let inputFromEditText = inputEditText.text!
        arrayForTable.addObject(inputFromEditText)
        tableViewController.data = arrayForTable
        tableViewController.tableView.reloadData()
        tableViewController.createHeader()
    }
}

I have just started with iOS development and I dont have access to a senior developer to review my code to see if things could be improved or done in a better/best practices sort of way. Any help or suggestions would be great.


texts: Semicircle Navigationmenu with html, css and js

texts:
i am trying to create a semicircle menu with animations and texts.
Currently i try to position the texts in the semicircle which is only working with a specific window-width and browser.

This is my current approach: https://codepen.io/Jxner/pen/xxGBKYJ

.menu {
  padding: 0;
  list-style: none;
  position: relative;
  margin: 150px auto;
  width: 70%;
  height: 0;
  padding-top: 70%;
}

@media all and (max-width: 320px) {
  .menu {
    width: 230px;
    height: 230px;
    padding: 0;
  }
}

@media all and (min-width: 700px) {
  .menu {
    width: 1080px;
    height: 1080px;
    padding: 0;
  }
}

.menu li {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  clip-path: url(#sector);

<meta name="viewport" content="width=device-width, initial-scale=1.0">

        One

        Two

        Three

<svg height="0" width="0">
  <defs>
    <clipPath clipPathUnits="objectBoundingBox" id="sector">
      <path fill="none" stroke="#111" stroke-width="1" class="sector" d="M0.5,0.5 l0.5,0 A0.5,0.5 0 0,0 0.75,.066987298 z"></path>
    </clipPath>
  </defs>
</svg>

I am fairly new to css, so this seems like a really laborious way just to create a semicircle with 3 segments and an edge for each one.

How can i improve my code to better scale and run it in different browsers and how can i fix my text to the "pie-segments" so it doesn't disappear with different window sizes?


texts: Stop repeating myself: Similar pattern used on multiple event handlers

texts:
My code listens for a number of events, and calls the Google Analytics event tracking function when they fire.

Each event uses a similar pattern. Can I achieve the same functionality without repeating myself?

/*jslint debug:true, browser:true, devel:true nomen:true */
/*global _gaq:true, jquery:true, $:true */

function trackEvent(c, a, l) {

    'use strict'; // JSLint

    //console.log(c, a, l); // Dev only

    _gaq.push(['_trackEvent', c, a, l]);

}

$(function () {

    'use strict'; // JSLint

    var alert, carousel, collapse, modal, tab, tooltip, download, external, mailto;

    // Alerts event handler

    alert = function () {

        var alertButton = $(this),
            category = 'Alerts',
            action = alertButton.next().text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('click.alert.data-api', '[data-dismiss="alert"]', alert);

    // Carousel event handler

    carousel = function () {

        var carouselButton = $(this),
            category = 'Carousels',
            action = carouselButton.attr('data-slide'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click.carousel.data-api', '[data-slide]', carousel);

    // Collapse event handler

    collapse = function () {

        var category = 'Collapses',
            action = $(this).text(),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click.collapse.data-api', '[data-toggle=collapse]', collapse);

    // Modal event handler

    modal = function () {

        var category = 'Modals', action, label, activeModal;

        activeModal = $(this).attr('href');
        action = $(activeModal).find('h3').text();

        trackEvent(category, action, label);
    };

    $('body').on('click.modal.data-api', '[data-toggle="modal"]', modal);

    // Tab event handler

    tab = function () {

        var category = "Tabs",
            action = $(this).text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', tab);

    // Tooltip event handler

    tooltip = function () {

        var category = "Tooltips",
            action = $(this).text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('mouseenter', '[rel="tooltip"], [rel="popover"]', tooltip);

    // Download link event handler

    download = function () {

        var category = "Downloads",
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a[href$="pdf"], a[href$="doc"], a[href$="docx"], a[href$="rtf"], a[href$="ppt"], a[href$="zip"]', download);

    // Mailto event handler

    mailto = function () {
        var category = 'Mailto',
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a[href^="mailto"]', mailto);

    // External link event handler

    $.expr[':'].external = function (a) {
        var PATTERN_FOR_EXTERNAL_URLS = /^\w+:\/\//,
            href = $(a).attr('href');
        return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
    };

    external = function () {

        var category = 'External links',
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a:external', external);

});


texts:
I'm writing a small ETL, which loads data from CSVs, cleans each table a bit, and then loads everything into a PostgreSQL database. I was planning to use pandas for its built-in capabilities, but am wondering whether to subclass DataFrame or whether to just do everything functionally.

The subclassed DataFrame code is pasted below. For maintainability by non-developers, I have a small YAML file with information about each table and column type.

import pandas
import numpy
import yaml
from os import path

CFG = yaml.load(open('config.yaml', 'r'))

class ETLDataTable(pandas.DataFrame):
    _metadata = ['table_name', 'file_name', 'columns', 'notes']

    @property
    def _constructor(self):
        return ETLDataTable

    def __init__(self, table_name):
        # Name of the database table
        self.table_name = CFG[table_name]['table']
        # Name of the CSV file
        self.file_name = CFG[table_name]['file']
        # Whether file has note fields
        self.notes = CFG[table_name]['notes']

        #Data Types to feed into read_csv
        try:
            self.columns = CFG[table_name]['columns']
        except:
            pass

        _ = path.join(path.abspath(path.pardir), self.file_name)
        super().__init__(pandas.read_csv(_))

    def load_df(self, root_path, **kwargs):
    """Read the csv associated with the table name,
    then import as a pandas DataFrame
    """
        _ = path.join(path.abspath(path.pardir), self.file_name)
        pandas.read_csv(csv_path,
                        na_values = ['00000000', ' ', ''],
                        encoding="latin1",
                        dtype="object",
                        **kwargs)

Going forward I was planning to add in some methods that are needed by every table: fixing bad dates, stripping empty strings, etc. Is this approach going to be more trouble than it's worth?


texts: Automated Java fighting and battling simulation

texts:
This is my second post since I've started coding/joined this site so be ready for some bad code and beginner questions!

I am just playing around with Java right now, as I believe this is a fun way to learn the language, so I decided to make a simple fight simulator. The simulator is meant to have each player start with a set amount of health (hitPoints) and they take turns hitting each other. Their damage dealt determined by a random number roll.

I just started trying to use multiple classes to make my code easier to ready and more. Correct I guess.

I have a question but also hope someone can give me pointers on how to improve my code in some ways. My questions is. I want to make it so when a player hits 0 health the program goes to the outCome() method but it currently allows 1 more hit after a player loses. So if the person who attacks first dies, they get 1 more hit in before the program ends but this is wrong and I'm not sure how to fix this. Here is my code.

This is my main class that runs everything.

package com.company;
import java.util.Scanner;

public class Battle {

    public static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Please enter your username.");
        Players.userName = scan.nextLine();

        System.out.println(Players.userName + ", get ready for battle..");
        System.out.println("Press enter when ready.");
        scan.nextLine();

        while(Players.pHP > 0 && Players.oHP > 0) {
            Game.fight();
        }

        Game.outCome();
    }

}

This is my Player class which I believe is very unnecessary right now and would like some feedback on how to make it more useful than it is. This class feels entirely wrong to me.

package com.company;

public class Players {

    static String userName;
    static int hitPoints = 99;
    static int oHP = opponentHP();
    static int pHP = playerHP();

    public static int playerHP() {
        return pHP = hitPoints;
    }

    public static int opponentHP() {
        return oHP = hitPoints;
    }

}

And finally my Game class which kind of has the game code in it. This class looks messy to me and I believe I will improve on my organization with practice.

package com.company;

import java.util.Random;

public class Game {

    public static Random r = new Random();
    private static boolean isTurn = true;

    public static void fight() {
        int damage = r.nextInt(20);

        try {
            Thread.sleep(1000);
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
            System.out.println("INTERUPTED DELAY");
        }

        if(isTurn) {
            Players.oHP -= damage;
            if(Players.oHP < 0) {
                Players.oHP = 0;
            }
            System.out.println("You hit a(n) " + damage + " and now your
    opponent has " + Players.oHP + " HitPoints.");
            isTurn = false;
        } else {
            Players.pHP -= damage;
            if(Players.pHP < 0) {
                Players.pHP = 0;
            }
            System.out.println("Your opponent hit a(n) " + damage + " and now
    you have " + Players.pHP + " HitPoints.");
            isTurn = true;
        }
    }

    public static void outCome() {

        if (Players.oHP == 0 || Players.oHP < 0) {
            victory();
        } else {
            defeat();
        }
    }

    private static void victory() {
        System.out.println("You are the ultimate warrior.");
        System.out.println("Thanks for fighting..........");
    }

    private static void defeat() {
        System.out.println("You have been slain.");
        System.out.println("Thanks for fighting..........");
    }

}


texts: Program to compress a string of characters

texts:
I was given this small task in an interview recently. I'm usually terrible at coding questions in interviews, because with the time constraint and the lack of google I usually overthink and rush stuff and just end up with a mess of a program.

The task was to write a program that would compress the length of string, and compare the length of the compressed string to the input string and return whichever one is smaller. Example would be: input string "aaabcccc" would be compressed to "a3b1c4".

I essentially split the string into a charArray and then counted each occurrence of a character and stored them into a hashmap, and looped through the map to build the new string. Just from a learning perspective, was there a better way to do this? I was given ~10 minutes to write it as well, it more to assess how I would solve the problem as opposed to the code itself. But regardless, I'd like a review of it:

import java.util.HashMap;
import java.util.Map.Entry;

public class Compressor {

    public static void main(String args []) {

        String randomString = "aaabccccc";

        HashMap<Character, Integer> map = countCharacters(randomString);
        String compressedString = createCompressedString(map);

        if(randomString.toCharArray().length < compressedString.toCharArray().length) {
            System.out.println(randomString);
        }
        else {
            System.out.println(compressedString);
        }
    }

    /**
     * Create hasmap to store character and count of occurrence
     * @param s
     * @return
     */
    private static HashMap<Character, Integer> countCharacters(String s) {

        HashMap<Character, Integer> characterCount = new HashMap<Character, Integer>();
        char[] characterArray = s.toCharArray();

        for(Character c : characterArray) {
            int newCount;
            Integer count = characterCount.get(c);
            if(count == null) {
                newCount = 1;
            }
            else {
                newCount = count + 1;
            }
            characterCount.put(c, newCount);
        }

        return characterCount;
    }

    /**
     * Convert hashmap into a string
     * @param map
     * @return
     */
    private static String createCompressedString(HashMap<Character, Integer> map) {

        String newString = "";
        for (Entry<Character, Integer> entry : map.entrySet()) {
            Character key = entry.getKey();
            Integer value = entry.getValue();

            newString += "" + key + "" + value;
        }

        return newString
    }
}


texts: RecyclerView with different ViewHolder using generic

texts:
I have different ViewHolder for different Feed implementations. But I can't use the best practice of having each ViewHolder corresponds to different layout id because i am reusing layout for 2 different ViewHolder (aka. FeedWithImageHolder and FeedWithoutImageHolder)

class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.BaseFeedHolder>{

    @NonNull
    @Override
    public BaseFeedHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = null;
        switch (viewType){
            case FeedType.FEED_WITH_IMAGE :
                v = LayoutInflater.from(context).inflate(R.layout.feed_status,parent,false);
                //notice that i use the same R.layout.feed_status for two different ViewHolder

                return new FeedWithImageHolder(v);
            case FeedType.FEED_WITHOUT_IMAGE:
                v = LayoutInflater.from(context).inflate(R.layout.feed_status,parent,false);
                return new FeedWithoutImageHolder(v);
            case FeedType.ADS:
                v = LayoutInflater.from(context).inflate(R.layout.ads,parent,false);
                return new AdsHolder(v);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseFeedHolder holder, int position) {
        //noinspection unchecked
        holder.bindFeed(feeds.get(position));
    }

    abstract class BaseFeedHolder<T extends Feed> extends RecyclerView.ViewHolder {
        BaseFeedHolder(@NonNull View itemView) {
            super(itemView);
        }

        abstract void bindFeed(T feed);
    }

    class FeedWithImageHolder extends BaseFeedHolder<FeedStatus>{

        FeedWithImageHolder(@NonNull View itemView) {
            super(itemView);
        }

        @Override
        void bindFeed(FeedStatus feed) {
            doSomethingWithFeed(feed);
            bindImage(feed.getPostImage());
        }

        protected void bindImage(String image){
            clipImageToImageView(image);
        }
    }

    class FeedWithoutImageHolder extends FeedWithImageHolder{

        FeedWithoutImageHolder(@NonNull View itemView) {
            super(itemView);
            removeImageViewFromCoinstraintLayout(itemView);
        }

        @Override
        protected void bindImage(String image) {
            //void
        }
    }

    class AdsHolder extends BaseFeedHolder<Ads>{
        AdsHolder(@NonNull View itemView) {
            super(itemView);
        }

        @Override
        void bindFeed(Ads ads) {
        }
    }

}

Instead what I do is making Feed have a method .getType() so every implementation can have different type corresponding to it.

For example:

class FeedStatus implements Feed {

    private String image;

    @Override
    public int getType() {
        return (this.image == null) ? FeedType.FEED_WITHOUT_IMAGE : FeedType.FEED_WITH_IMAGE;
    }

}

There is tingling worry here because I think there is code smell in there but I am not sure which one and I hope you can help me with it. Thanks


texts:
This is the dashboard controller code in PHP Symfony 2. It collects some aggregate data and points for charts, but i don't like it very much. Do you think that this code belongs to what a controller should do in a MVC patter? How can i refactor it?

public function dashboardAction()
{
    $bag = array();

    // Helpers from service container
    $messaging = $this->get('messaging.helper');
    $charting  = $this->get('charting.helper');

    // Current logged user, subscription and message inhibitor
    $loggedUser   = $this->getSecurityContext()->getToken()->getUser();
    $subscription = $messaging->createSubscriptionFromUser($loggedUser);
    $usage        = $messaging->createUsageFromSubscription($subscription);

    $bag['subscription'] = $subscription;
    $bag['usage']        = $usage;
    $bag['inhibitor']    = $messaging->createInhibitor($usage, $subscription);

    // Get charts from usage raw data
    $rawData = $usage->getRawData();
    $start   = $usage->getStartDate();
    $end     = $usage->getEndDate();

    $bag['line_chart'] = $charting->createMessagesLineChart($rawData, $start, $end);
    $bag['pie_chart']  = $charting->createMessagesPieChart($rawData);

    // Customers and latest 5 added
    $customers = $loggedUser->getCustomers();

    $bag['customers_count']  = $customers->count();
    $bag['latest_customers'] = $customers->slice(0, 5);

    // Tags/keywords counts and latest 5 meta
    $metas       = $loggedUser->getMeta();
    $getTags     = function($m) { return $m instanceof Tag; };
    $getKeywords = function($m) { return $m instanceof Keyword; };

    $bag['tags_count']     = $metas->filter($getTags)->count();
    $bag['keywords_count'] = $metas->filter($getKeywords)->count();
    $bag['latest_meta']    = $metas->slice(0, 5);

    // SMS and newsletter counts
    $outgoingMessages = $loggedUser->getOutgoingMessages();
    $getSms           = function($m) { return $m instanceof SmallTextMessage; };
    $getNewsletters   = function($m) { return $m instanceof Newsletter; };

    $bag['sms_count']        = $outgoingMessages->filter($getSms)->count();
    $bag['newsletter_count'] = $outgoingMessages->filter($getNewsletters)->count();

    return $bag;
}


texts:
Last time I made a website using PHP, I didn't know of PDO, so someone dropped all my tables. I think I've made an improvement now. I'm sorry if there's a lot to go through, but I want to make sure its safe (most importantly) and also using the best practices.

Here are some snippets:

1)

$form = $_POST;     $name = $form[ 'name' ];    $desc = $form[ 'desc' ]; $link = $form[ 'link' ];   $tag = $form[ 'tag' ];  $category = $form[ 'category' ];

$sql = "INSERT INTO items ( `name`, `desc`, `link`, `tag`, `category` ) VALUES ( :name, :desc, :link, :tag, :category )";

$query = $db->prepare( $sql );  $query->execute( array( ':name'=>$name, ':desc'=>$desc, ':link'=>$link, ':tag'=>$tag, ':category'=>$category ) );

2)

$db = new PDO('mysql:host=mywebsite.com;dbname=thisdb;charset=utf8','root', '');

3)

if (isset($_GET['search'])) {
   $searchStmt = $db->prepare('SELECT * FROM items WHERE tag LIKE    :usersearch'); $searchStmt->execute(['usersearch' =>    "%".$_GET['search']."%"]);

   foreach ($searchStmt as $row) { ?> <?php    include('includes/results-layout.php'); ?> <?php }} else {    header('Location: http://localhost/photo'); }
   if ($_GET['search'] == "") {     header('Location:    http://mywebsite.com/photo');  }
   if ($searchStmt->rowCount() === 0) {     echo "Sorry, your search for    \"".$_GET['search']."\" was not found...";   }

4)

$page1Stmt = $db->query("SELECT * FROM items WHERE category = 1 ORDER BY id DESC");

5)

$downloadStmt = $db->prepare('SELECT * FROM items WHERE id = :downloadID'); $downloadStmt->execute(['downloadID' => $_GET['id']]); ?> $tags = explode(" ",$row['tag']);
foreach($tags as $tag) {echo "".$tag."";} $relatedStmt = $db->prepare("SELECT * FROM items WHERE tag = (select tag from items where id = :downloadID)");
$relatedStmt->execute(['downloadID' => $_GET['id']]); ?>

6)

$pageStmt = $db->query("SELECT * FROM items ORDER BY id DESC");
foreach ($pageStmt as $row) { ?>
<?php include('includes/results-layout.php'); ?>
<?php } ?>


texts: VBA Macro to generate a report of mean values for each date

texts:
My Macro that I wrote is running really slowly and I'm not sure why. The Macro deletes the area, then reproduces one column of locations as a row, deleting any duplicates, then copy's across a column of dates, then puts the corresponding Mean value for each date under the correct functional location.

Sub Macro1()
'
' Macro1 Macro

' Delete Previous Data
Range("J1:AQ1000").Clear

' Functional Location

Dim toAdd As Boolean, uniqueTag As Integer, i As Integer, j As Integer
Cells(1, 11).Value = Cells(2, 2).Value
uniqueTag = 11
toAdd = True
For i = 3 To 1000
For j = 11 To uniqueTag
If Cells(i, 2).Value = Cells(1, j).Value Then
toAdd = False
End If
Next j
If toAdd = True Then
Cells(1, uniqueTag + 1).Value = Cells(i, 2).Value
uniqueTag = uniqueTag + 1
End If
toAdd = True
Next i

' Date

Dim k As Integer
For k = 2 To 1000
Cells(k, 10).Value = Cells(k, 6).Value
Next k

' Mean Value
Dim l As Integer, m As Integer
For l = 2 To 1000
For m = 11 To 100
If Cells(l, 2).Value = Cells(1, m).Value Then
Cells(l, m).Value = Cells(l, 5).Value
End If
Next m
Next l

End Sub

Are there any optimizations that would make it run faster, or something I haven't included?
The first parts all work pretty speedily, its only the copying of the mean values which appears to take time.


texts:
Description: The web server retrieves data from file database (pdf, doc, 3d file, zip and rar) and financial program such as inventory, price, indexes, order status and so on.

I'm doing REST API PHP for the first time,  I've never used this API with PHP, I am an absolute beginner to REST.

Code returns data to cooperate with a www site.

First, I will test for a product that exists.

Output code 200:get_id2.php?id=39

id  "39"
caption "product01"
filename    "http://localhost/photo_gallery/public/files/images/image01.jpg"
description "testing Api"

Next, I will test for a product that does not exist.

Output code 404:get_id2.php?id=99999

message "No product."

I need your opinions.

Are there any code smells (can it be done better)?
Better to use prepared statement or not?
Use htmlspecialchars and urlencode for output?
What is good practice for REST API (PHP)?

Thank you in advance for your opinion.

File: get_id2.php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");

    include_once('config_setup.php');

    //$id = $_GET['id'];
    $id = isset($_GET['id']) ? $_GET['id'] : die();

    $sql = "SELECT * ";
    $sql .= "FROM photographs ";
    $sql .= "WHERE id='" . db_escape($db, $id) . "'";

    $result = mysqli_query($db, $sql);
    confirm_db_connect($result);

    $url = 'http://localhost/photo_gallery/public/files/images/';

    $allowed_tags = '

';

    $photo = mysqli_fetch_assoc($result);

            $id             = $photo['id'];
            $caption        = $photo['caption'];
            $filename       = $photo['filename'];
            $description2   = $photo['description2'];

    if ($photo['caption'] != null) {

        // create array
        $product_arr = array(
            "id"            => u(h($id)),
            "caption"       => h($caption),
            "filename"      => $url . h($filename),
            "description2"  => strip_tags($description2, $allowed_tags)
        );

        // set response code - 200 OK
        http_response_code(200);
        echo json_encode( $product_arr );

    } else {
        // set response code - 404 Not found
        http_response_code(404);
        // tell the user product does not exist
        echo json_encode(array("message" => "No product."));
    }

    mysqli_free_result($result);

    db_disconnect($db);

Functions

function h($string="") {
  return htmlspecialchars($string);
}
function u($string="") {
  return urlencode($string);
}
function confirm_result_set($result_set) {
    if (!$result_set) {
        exit("Database query failed.");
    }
  }
function db_escape($connection, $string) {
    return mysqli_real_escape_string($connection, $string);
  }
function db_disconnect($connection) {
    if(isset($connection)) {
      mysqli_close($connection);
    }
  }


texts: Get exactly `n` unique randomly sampled rows per category in a Dataframe

texts:
I want to get exactly n unique randomly sampled rows per category in a Dataframe. This proved to be involve more steps than the description would lead you to believe.
n = 4
df = pd.DataFrame({'category': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 1],
                   'value' : range(12)})

category_counts = df['category'].value_counts()
categories_with_count_above_threshold = category_counts[category_counts >= n].index

# rows with infrequent categories are filtered out
df = df[df['category'].isin(categories_with_count_above_threshold)]

# sample exactly x rows per category
df = df.groupby('category').sample(n)

This goes through the whole DataFrame quite a few times. With a bigger DataFrame this can become quite time consuming. Is there a way to simplify this expression?
PS: requires pandas >= 1.1 for the DataFrameGroupBy.sample


texts:
I wrote a queue class in C++ using arrays of fixed width. Could anyone review my code ? I would appreciate any comment and recommendations. It works like a circular queue, so I handled back and front pointers in that manner.

#include <stdlib.h>
#include <iostream>

template <class T>
class Queue {
    public:
        Queue(void);
        Queue(Queue<T>& copyQueue);
        bool empty(void) const;
        std::size_t size(void) const;
        void clear(void);
        T front(void) const;
        void pop(void);
        void push(T& item);
        void print(std::ostream& os);
    private:
        static const std::size_t MAX_SIZE = 50;
        T list[MAX_SIZE];
        T* frontPtr;
        T* backPtr;
        std::size_t sizeQ;
};

template <class T>
Queue<T>::Queue(void) {
    frontPtr = nullptr;
    backPtr = nullptr;
    sizeQ = 0;
}

template <class T>
Queue<T>::Queue(Queue<T>& copyQueue) {
    frontPtr = nullptr;
    backPtr = nullptr;
    sizeQ = 0;
    if(copyQueue.backPtr >= copyQueue.frontPtr){
        for(T* i = copyQueue.frontPtr; i <= copyQueue.backPtr; i++){
            push(*i);
        }
    }
    else {
        for(T* i = copyQueue.frontPtr; i <= (copyQueue.list + MAX_SIZE -1); i++){
            push(*i);

        }
        for(T* i = copyQueue.list; i <= copyQueue.backPtr; i++) {
            push(*i);
        }
    }
}

template <class T>
bool Queue<T>::empty(void) const {
    return (sizeQ == 0);
}

template <class T>
std::size_t Queue<T>::size(void) const {
    return sizeQ;
}

template <class T>
void Queue<T>::clear(void) {
    frontPtr = nullptr;
    backPtr = nullptr;
    sizeQ = 0;
}

template <class T>
T Queue<T>::front(void) const {
    if(frontPtr == nullptr) {
        std::cerr << "Queue is empty. No front value" << '\n';
    }
    else {
        return *frontPtr;
    }
}

template <class T>
void Queue<T>::pop(void) {
    if(sizeQ == 0) {
        std::cerr << "Queue is empty. Can't pop." << '\n';
    }
    else{
        frontPtr = list + ((frontPtr - list + 1) % MAX_SIZE);
        sizeQ -= 1;
    }
}

template <class T>
void Queue<T>::push(T& item) {
    if(sizeQ == MAX_SIZE) {
        std::cerr << "Queue is full. Can't push" << '\n';
    }
    else{
        if(sizeQ == 0) {
            frontPtr = backPtr = list;
        }
        else {
            backPtr = list + ((backPtr - list + 1) % MAX_SIZE);
        }
        *backPtr = item;
        sizeQ += 1;
    }
}

template <class T>
void Queue<T>::print(std::ostream& os) {
    if(backPtr >=frontPtr){
        for(T* i = frontPtr; i <= backPtr; i++){
                os << *i << '\n';
        }
    }
    else {
        for(T* i = frontPtr; i <= (list + MAX_SIZE -1); i++){
            os << *i << '\n';
        }
        for(T* i = list; i <= backPtr; i++) {
            os << *i << '\n';
        }
    }
}

Edit: Not using googletest, but a simple main function to test the Queue.h can be found below:

#include "Queue.h"
int main() {
    Queue<int> newQueue;
    for(int i=1; i<110; i = i+2)
        newQueue.push(i);
    newQueue.pop();
    newQueue.pop();
    newQueue.pop();
    newQueue.pop();
    int i = 999;
    newQueue.push(++i);
    newQueue.push(++i);
    newQueue.push(++i);
    newQueue.push(++i);
    newQueue.print(std::cout);
    Queue<int> copiedQueue(newQueue);
    std::cout << copiedQueue.size() << '\n';
    copiedQueue.print(std::cout);
    for(int i=1; i<11; i = i+2)
        copiedQueue.pop();
    newQueue.print(std::cout);
    std::cout << copiedQueue.empty();
    std::cout << newQueue.empty();
    copiedQueue.print(std::cout);
    return 0;
}


texts:
I wrote a build file for a mini Android game. I use this buildfile whereupon travis reports success. But I'm not always sure of what I'm doing.

language: android
jdk: oraclejdk8

#sudo: false

android:
  components:
    # Uncomment the lines below if you want to
    # use the latest revision of Android SDK Tools
    - tools
    - platform-tools
    - tools

    # The BuildTools version used by your project
    - build-tools-26.0.1

    # The SDK version used to compile your project
    - android-26

    # Additional components
    - extra-google-google_play_services
    - extra-google-m2repository
    - extra-android-m2repository
    # - addon-google_apis-google-19

    # Specify at least one system image,
    # if you need to run emulator(s) during your tests
    - sys-img-armeabi-v7a-android-22
    - sys-img-armeabi-v7a-android-17

#before_script:
#  - echo no | android create avd --force -n test -t android-21 --abi armeabi-v7a
#  - emulator -avd test -no-skin -no-audio -no-window &
#  - android-wait-for-emulator
#  - adb shell input keyevent 82 &

install: skip

# env:
#   global:
#     - CACHE_DIR=$([ $TRAVIS_OS_NAME = 'linux' ] && echo "FOO" || echo "BAR")

# cache:
#   directories:
#     - $CACHE_DIR

# env:
#   global:
#     - PATH=/usr/local/android-sdk/tools/bin:$PATH

script: skip
# android:
#   components:
#     - tools
#     - platform-tools
#     - tools

#     - android-25

#     - build-tools-25.0.2
#     - extra
#     - extra-google-m2repository
#     - extra-android-m2repository
#     - extra-android-support

# jdk: oraclejdk8

matrix:
  include:
    - sudo: false
      dist: precise
      env: DIST=precise STACK=EC2
    # - sudo: required
    #   dist: precise
    #   env: DIST=precise STACK=GCE
    # - sudo: false
    #   dist: trusty
    #   env: DIST=trusty STACK=EC2
    # - sudo: required
    #   dist: trusty
    #   env: DIST=trusty STACK=GCE
    # - sudo: false
    #   dist: trusty
    #   group: edge
    #   env: DIST=trusty STACK=EC2 GROUP=edge
    # - sudo: required
    #   dist: trusty
    #   group: edge
    #   env: DIST=trusty STACK=GCE GROUP=edge
#     - os: osx

notifications:
  email: false

  #  slack:
  #  rooms:
  #    - secure: "KZTfjxhkOdDDZYD2ThBILt2ShYtdEee3PudFZlQBfpxG9N470GfxnKVfOl7Odu4lN6cIupwC4S4BnehubEywSR99l60VmfhePUCTqDLYy+iR9+guTvaECdXdaau3jTKhFdu5u60ITsiw5Yb+hwAaGFO0HmQhqR9XVr/U8IGQlok="
  #  template:
  #    - "Build <%{build_url}|#%{build_number}> (<%{compare_url}|%{commit}>) of %{repository}@%{branch} by %{author} %{result} in %{duration} (elapsed time: %{elapsed_time}) subject: %{commit_subject} message: %{commit_message} foobar"
  #  on_success: always


texts:
Is it good way of asking for a number? Should that function return 0 if there is an error?

private int getNumberDialog(String message) {
            try {
                String resultInString = JOptionPane.showInputDialog(message);
                int result = Integer.parseInt(resultInString);
                return result;
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "You didn't gave a number");
            }
            return 0;
        }


texts: Time optimization of counting shifts in insertion sort

texts:
Is there any way of counting how many shifts would it take to count shifts while doing insertion sort?  This is a Hackerrank problem. Here's my solution, but it takes more than 16 seconds.

counts = []
for _ in range(int(input())):
    size = int(input())
    ar = list(map(int, input().split()))
    count = 0
    for i in range(1, len(ar)):
        j = i
        while j >= 1 and ar[j] < ar[j-1]:
            ar[j], ar[j-1] = ar[j-1], ar[j]
            j -= 1
            count+=1
    counts.append(count)
for c in counts: print(c)

  Insertion Sort is a simple sorting technique which was covered in
  previous challenges. Sometimes, arrays may be too large for us to wait
  around for insertion sort to finish. Is there some other way we can
  calculate the number of times Insertion Sort shifts each elements when
  sorting an array?

  If ki is the number of elements over which ith element of the array
  has to shift then total number of shift will be k1 + k2 + … + kN.

  Input: The first line contains the number of test cases T. T test
  cases follow. The first line for each case contains N, the number of
  elements to be sorted. The next line contains N integers
  a[1],a[2]…,a[N].

  Output: Output T lines, containing the required answer for each test
  case.

That's the problem. Is there any way I could optimize my solution?


texts: Finding sum of divisors of numbers between the range (1 to 1e16)

texts:
The exact link to the question : https://www.spoj.com/problems/DIVSUM2/

Input: An integer stating the number of test cases (equal to 500), and that  many lines follow, each containing one integer between \$1\$
and \$10^{16}\$ inclusive.
Output: Print one integer, the sum of the proper divisors of the number.

An easier version of this question exists in which the constraints are relaxed.
My code works for the easier version , but exceeds the time limit for the harder one.
Example of approach: \$36=2^2 \times 3^2\$. So sum of proper factors = $$(2^0+2^1+2^2)\times(3^0+3^1+3^2)-36=55$$
My code:
#include<iostream>
long long sum_proper_divisors(long long n)
{
    long long sum=1,x=n;
    for(long long i=2;i*i<=n;i++)
      {
          long long current_sum=1,current_term=1;
           while(n%i==0)
           {
              n/=i;
              current_term*=i;
              current_sum+=current_term;
            }
         sum*=current_sum;
      }
   if(n>=2){
    sum*=(n+1);
    }
  return (sum-x);
}
int main()
{
   long long q;
   std::cin>>q;
    while(q--)
    {
      long long n;
      std::cin>>n;
      std::cout<<sum_proper_divisors(n)<<std::endl;
    }
 }


texts: Write log file in nodeJS with setInterval

texts:
I wrote this code to write the log file every 5 seconds to avoid excessive disk I/O (which can cause HDD temperature to increase or SSD to wear off):

var fs = require('fs');
var logText = '';
function log(){
    fs.appendFile('c:/log.txt', logText, (err) => {
        if (err) throw err;
        logText = '';
    });
}
setInterval(log, 5000);

Is this the correct approach? I mean this is async right? Will setInterval interfere with the performance?


texts: Fast ray/triangle intersection code in C

texts:
I wonder if someone is familiar with ray/triangle intersection algorithms and can help me optimize them?

Here are my implementations of two ray/triangle intersection algorithms in C. The first is the well-known Möller-Trombore algorithm:

inline bool
isect_mt_b(vec3 o, vec3 d,
           vec3 v0, vec3 v1, vec3 v2,
           float *t, vec2  *uv) {

    vec3 e1 = v3_sub(v1, v0);
    vec3 e2 = v3_sub(v2, v0);
    vec3 pvec = v3_cross(d, e2);
    vec3 tvec = v3_sub(o, v0);
    vec3 qvec;
    uv->x = v3_dot(tvec, pvec);
    float det = v3_dot(e1, pvec);
    if (det > 0) {
        if (uv->x < 0 || uv->x > det)
            return false;
        qvec = v3_cross(tvec, e1);
        uv->y = v3_dot(d, qvec);
        if (uv->y < 0 || uv->x + uv->y > det)
            return false;
    } else if (det < 0) {
        if (uv->x > 0 || uv->x < det)
            return false;
        qvec = v3_cross(tvec, e1);
        uv->y = v3_dot(d, qvec);
        if (uv->y > 0 || uv->x + uv->y < det)
            return false;
    } else {
        return false;
    }
    float inv_det = 1 / det;
    *t = v3_dot(e2, qvec) * inv_det;
    uv->x *= inv_det;
    uv->y *= inv_det;
    return *t >= ISECT_NEAR && *t <= ISECT_FAR;
}

I'm not pasting the source for v3_cross, v3_dot and friends. They are all declared using the inline keyword for maximum performance. It should be obvious what they do if you know that they operate on a vec3 struct containing three float fields; x, y and z. The second less known one is Segura-Feita algorithm:

inline float
v3_sign_3d(vec3 p, vec3 q, vec3 r) {
    return v3_dot(p, v3_cross(q, r));
}
inline bool
isect_sf01(vec3 o, vec3 d,
           vec3 v0, vec3 v1, vec3 v2,
           float *t, vec2  *uv) {
    vec3 v0o = v3_sub(v0, o);
    vec3 v1o = v3_sub(v1, o);
    vec3 v2o = v3_sub(v2, o);
    float w2 = v3_sign_3d(d, v1o, v0o);
    float w0 = v3_sign_3d(d, v2o, v1o);
    bool s2 = w2 >= 0.0f;
    bool s0 = w0 >= 0.0f;
    if (s2 != s0)
        return false;
    float w1 = v3_sign_3d(d, v0o, v2o);
    bool s1 = w1 >= 0.0f;
    if (s2 != s1)
        return false;
    uv->x = w1 / (w0 + w1 + w2);
    uv->y = w2 / (w0 + w1 + w2);
    vec3 v0v1 = v3_sub(v1, v0);
    vec3 v0v2 = v3_sub(v2, v0);
    vec3 n = v3_cross(v0v1, v0v2);
    *t = v3_dot(n, v0o) / v3_dot(n, d);
    return *t >= ISECT_NEAR && *t <= ISECT_FAR;
}

It is described in this paper and my sample code comes from this webpage.

Any performance tips are greatly appreciated. :)


texts:
I have always suffered with too many conditionals in some of my methods. The following is a pseudocode/skeleton of one of my method like that:

private List<ReturnType> DoSth(string name = null)
{
    List<ReturnType> names = new List<ReturnType>();

    for (int i = 0; i < somearray.Length; i++)
    {
        if (somecondition)
        {
            if (name == null)
            {
                //'Add' to list
            }
            else
            {
                if (someothercondition)
                {
                    //'Add' to list
                }
            }
        }
    }

    return names;
}

Actual Code which returns an object filled with Controller and corresponding Action names:

private List<AppController> GetControllerActions(string ControllerName = null)
{
    Type[] typelist = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "Project.Web.Controllers", StringComparison.Ordinal)).ToArray();

    List<AppController> names = new List<AppController>();

    for (int i = 0; i < typelist.Length; i++)
    {
        if (typelist[i].BaseType.Name == "Controller")
        {
            if (ControllerName == null)
            {
                names.Add(new AppController
                {
                    ControllerName = typelist[i].Name,
                    ActionName = typelist[i].GetMethods()
                    .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
                    .Select(s => s.Name).ToList()
                });
            }
            else
            {
                if (typelist[i].Name == ControllerName)
                {
                    names.Add(new AppController
                    {
                        ControllerName = typelist[i].Name,
                        ActionName = typelist[i].GetMethods()
                        .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
                        .Select(s => s.Name).ToList()
                    });
                }
            }
        }
    }

    return names;
}

As you can see the same Add code is being repeated twice and the 'Add' code is not an external method and I would prefer not making it one also. I can also provide the actual code if required.

Is there any scope of making this code more concise and compact like you can do with ternary operators for example?


texts:
Working on identifying duplicate vendor payments using SQL in MS Access. The business logic uses four column; Vendor #, Invoice #, Invoice Date and Invoice Amount. There are 5 core reviews, if all are the Exact matches (EEEE) or if at least one field is different (DEEE,EDEE,EEDE,EEED). I have it working for all 5, however its slow and I would like to improve on the code itself. I put an example of EEEE and DEEE below. Thoughts on a better way to write it?

Table SCHEMA:

ID - AutoNumber
VendorCol - Short Text
VendorNameCol - Short Text
InvoiceNoCol - Short Text
InvAmountCol - Number
InvoiceDateCol - Date/Time

EEEE:

SELECT *
  FROM [Payment History] AS PH1
  WHERE Exists
 (Select *
 From [Payment History] AS PH2
 Where PH2.[ID] <>PH1.[ID]
 AND PH2.[VendorCol] = PH1.[VendorCol]
 AND PH2.[InvoiceNoCol] = PH1.[InvoiceNoCol]
 AND PH2.[InvoiceDateCol] = PH1.[InvoiceDateCol]
 AND PH2.[InvAmountCol] = PH1.[InvAmountCol])
 ORDER BY [InvAmountCol] DESC , [InvoiceDateCol] DESC;

Example of desired result:
EEEE Example

DEEE: Different vendor # but all else equal

SELECT *
FROM [Payment History] AS PH1
 WHERE Exists
 (Select *
 From [Payment History] AS PH2
 Where PH2.[ID] <>PH1.[ID]
 AND PH2.[VendorCol] <> PH1.[VendorCol]
 AND PH2.[InvoiceNoCol] = PH1.[InvoiceNoCol]
 AND PH2.[InvoiceDateCol] = PH1.[InvoiceDateCol]
 AND PH2.[InvAmountCol] = PH1.[InvAmountCol])
 ORDER BY [InvAmountCol] DESC , [InvoiceDateCol] DESC;

Example of desired result:
DEEE Example

I can post the other ones, but figured this would get most there.


texts:
I just came through a GitHub repo, which has an amazing animation for Button in Android.

So, I thought why not make that for web buttons too.

And I started designed that.

Here is my repo for the same.

Here is my code:

let icons = $('.magic')

for (let i = 0; i < icons.length; ++i) {
    icons[i].onclick = function (element) {
        icons[i].classList.toggle('enabled');
    }
}
.magic {
    display: inline-block;
    margin: 50px;
    position: relative;
  }

  .magic i {
    color: orange;
    filter: grayscale(100%);
    position: relative;
    animation: disable 0.5s forwards;
  }

  .enabled i {
    animation: enable 1s forwards;
  }

  .magic::before {
    content: "";
    top:calc(50% - 45px);
    left:calc(50% - 45px);
    width: 90px;
    height: 90px;
    position: absolute;
    border-color: orange;
    border-style: solid;
    border-width: 45px;
    border-radius: 50%;
    transform: scale(0);
    box-sizing: border-box;
  }

  .enabled::before {
    transition:
      transform 0.5s,
      border-width 0.5s 0.2s;
    transform: scale(1);
    border-width: 0px;
  }

  .magic::after,
  .magic i::after {
    content: "";
    position: absolute;
    top: calc(50% - 80px);
    left: calc(50% - 80px);
    height: 160px;
    width: 160px;
    background:
      radial-gradient(circle, red 50%, transparent 60%),
      radial-gradient(circle, red 50%, transparent 60%),
      radial-gradient(circle, red 50%, transparent 60%),
      radial-gradient(circle, red 50%, transparent 60%),
      radial-gradient(circle, orange 50%, transparent 60%),
      radial-gradient(circle, orange 50%, transparent 60%),
      radial-gradient(circle, orange 50%, transparent 60%),
      radial-gradient(circle, orange 50%, transparent 60%);

    background-position:
      calc(50% - 50px) calc(50% - 50px),
      calc(50% - 50px) calc(50% + 50px),
      calc(50% + 50px) calc(50% - 50px),
      calc(50% + 50px) calc(50% + 50px),
      calc(50% - 0px) calc(50% - 70px),
      calc(50% - 70px) calc(50% - 0px),
      calc(50% - 0px) calc(50% + 70px),
      calc(50% + 70px) calc(50% - 0px);
    background-size: 16px 16px;
    background-repeat: no-repeat;
    border-radius:50%;
    transform: scale(0);
  }

  .magic i:after {
    background-size: 10px 10px;
    transform: rotate(10deg) scale(0);
  }

  .enabled::after {
    transition:
      transform 0.5s 0.5s,
      opacity 0.4s 1s,
      background-size 0.4s 1s;

    transform: scale(1);
    opacity: 0;
    background-size: 0 0;
  }

  .enabled i:after {
    transition:
      transform 0.5s 0.5s,
      opacity 0.4s 0.8s,
      background-size 0.4s 0.8s;

    transform: rotate(10deg) scale(1);
    opacity: 0;
    background-size: 0 0;
  }

  @keyframes enable {
    50% {
      filter: grayscale(100%);
      transform: scale(0);
    }
    51% {
      filter: grayscale(0%)
    }
    90% {
        transform: scale(1.3)
    }
    100% {
      filter: grayscale(0%);
      transform: scale(1);
    }
  }

  @keyframes disable {
      50% {
          filter: grayscale(0%);
          transform: scale(1.3);
      }
      100% {
          transform: scale(1);
      }

  }

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">

What do you reckon? Is there anything I can improve either in the animation or in the code?


texts: Function to return a string legal for a range name

texts:
I wrote an Excel VBA function that will take a string argument and return a string that is legal for naming a range.  Upon looking through this, if you're wondering what I've been smoking, I should add a disclaimer that I'm new to VBA and I have not yet come across a less restrictive way to obtain this functionality.  And, of course, please feel welcome to modify and use it for your own purposes.

Function Namify(inputName As String) As String
'Takes a string argument and returns a modified string suitable for use as a name

    'Create a string to be modified and returned
    Dim workingName As String
    workingName = inputName

    'Create a string array containing all the valid characters in an Excel name
    Dim validchars() As Variant
    validchars = Array("_", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", _
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", _
        "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", _
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", _
        "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")

    'Iterate through each character of the string argument and replace that character
    'with an underscore if it's an illegal character.
    Dim i As Long
    For i = 1 To Len(inputName)

        'Is the character illegal? If so replace it in workingName
        If IsError(Application.Match(Mid(inputName, i, 1), validchars, 0)) Then
            workingName = Replace(workingName, Mid(inputName, i, 1), "_")
        End If

    Next i

    'Detect whether the first character in workingName is a number.
    Dim numbers() As Variant
    numbers = Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")

    If Not IsError(Application.Match(Mid(workingName, 1, 1), numbers, 0)) Then
        workingName = "_" & workingName
    End If

    'return the string that is now legal to use as a name.
    Namify = workingName

End Function

How I use it:

I have a macro that gets a text name from the user, instantiates a new object, and displays the user-input name in a cell followed by the object's property values in cells to the right. Then the sub calls Namify (user-selected name) to create a prefix for assigning a unique name to all these cells so their values can be updated with changes to the object's properties. The prefix itself is stored as a property of the object for later retrieval.

Some potential problems for this function (feel free to add to this list by editing or asking me to add in a comment):

It could return a name that is also a valid cell address.
It would return the same string from arguments with different illegal characters in the same position. (Example arguments: "User;Name", "User=Name")
It does not return all possible arrangements of valid characters.
It would return any of the one-character strings "C", "c", "R", "r"
There is no limit on the length of the returned string

What I'd like to know:

Is this a reasonable approach for allowing the user to create whatever name they like and then using a version of that name to name objects and ranges?
What ideas do you have to make this function more rigorous or more useful?

Disclaimer: I accepted Mat's Mug's answer because it worked well for me. AlexR's answer does appear to be the ideal way to handle this, however VB regular expressions aren't natively supported on my version of Excel (for Mac 2011). Please have a look at his answer if you're interested in optimizing something like my function for yourself.

Follow Up: With some great answers on the board, I revised this function and posted it in a follow up question.  Please have a look at it before posting additional answers here.


texts: Release the acquired lock after specific timeout

texts:
I'm trying to release a lock after some timeout. The lock is acquired to do any database changes so that multiple requests will not update the database simultaneously.

Below is the code

public static readonly _lockObject = new Object();

public bool UpdateData(ModifiedData modifiedData)
{
    var success = false;
    lock(_lockObject)
    {
        var thread = new Thread(()=>
        {
            try
            {
                SessionManager.Instance.OpenConversation(true); // Starts a session using nHibernate
                //Modifications

                success = true;
                SessionManager.Instance.EndConversation(true);

            }
            catch(ThreadAbortException ex)
            {
                //Do I need to handle any condition here
            }
        });
        thread.Start();
        if (!thread.Join(TimeSpan.FromMilliseconds(1000)))  // Timeout
        {
           if (!success)
              thread.Abort();
           else
           {
             thread.Join();
           }
        }
        else
        {
            if (!success)
             {
                    throw new Exception("Should Not occur");
             }
        }
    }
}

are there any better approaches available?? I tried with Action.BeginInvoke but in that not able to kill or stop action execution after some timeout.


texts:
The Skyline problem from UVa Online Judge is as follows:

  You are to design a program to assist an architect in drawing the skyline of a city given the locations of the buildings in the city. A building is specified by an ordered triple \$ (L_i,H_i,R_i) \$ where \$ L_i \$ and \$ R_i \$ are left and right coordinates, respectively, of building \$ i \$ and \$ H_i \$ is the height of the building.

  The input is a sequence of building triples. All coordinates of buildings are integers less than 10,000 and there will be at least one and at most 5,000 buildings in the input file. Each building triple is on a line by itself in the input file. All integers in a triple are separated by one or more spaces. The triples will be sorted by \$ L_i \$, the left x-coordinate of the building, so the building with the smallest left x-coordinate is first in the input file.

  The output should consist of the skyline vector \$ (v_1, v_2, v_3, \ldots, v_{n−2}, v_{n−1}, v_n)\$, the \$ v_i \$ such that \$ i \$ is an even number represent a horizontal line (height). The \$ v_i \$ such that \$ i \$ is an odd number represent a vertical line (x-coordinate). The skyline vector should represent the “path” taken, for example, by a bug starting at the minimum x-coordinate and traveling horizontally and vertically over all the lines that define the skyline. Thus the last entry in all skyline vectors will be a 0.

This is my solution:

# [SortedDict](http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html)
from sortedcontainers import SortedDict # pip3 install sortedcontainers
from collections import deque
import heapq

def skyline(buildings_by_L): # a deque.
    buildings_by_H = SortedDict() # a self-balancing binary tree.
    buildings_by_R = [] # a priority queue.
    skyline = []
    def add_point(x):
        h = buildings_by_H.iloc[-1] if buildings_by_H else 0
        if not skyline:
            skyline.append((x, h))
        else:
            x0, h0 = skyline[-1]
            if h != h0:
                if x == x0:
                    skyline[-1] = (x, max(h, h0))
                else:
                    skyline.append((x, h))
    def insert(b, sets=[set()]):
        heapq.heappush(buildings_by_R, (b[2], b))
        s = buildings_by_H.setdefault(b[1], sets[0])
        s.add(b)
        if s == sets[0]:
            sets[0] = set()
        add_point(b[0])
    def delete(b):
        buildings_by_H[b[1]].remove(b)
        if not buildings_by_H[b[1]]:
            del buildings_by_H[b[1]]
        add_point(b[2])
    while buildings_by_L or buildings_by_R: # another sweep line algorithm
        if (not buildings_by_R
            or buildings_by_L
               and buildings_by_L[0][0] <= buildings_by_R[0][0]):
            insert(buildings_by_L.popleft())
        else:
            delete(heapq.heappop(buildings_by_R)[1])
    return skyline

Test Cases:

buildings = (
    (1,9,3), (1,11,5), (2,6,7), (3,13,9), (12,7,16),
    (14,3,25), (19,18,22), (23,13,29), (24,4,28))
assert ([(1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), (22, 3), (23, 13), (29, 0)]
    == skyline(deque(buildings)))

Can you please suggest more elegant and eloquent ways for this problem? (Perhaps better ways to represent a graph with vertices and edges?)


texts:
I have a class that I use to manage a list to/from an API in Swift. Using a clean code approach, I'm wondering if, how, and why I should change it when I have a class that uses it for just one or two functions.

Here's the class:

import Foundation

protocol ApiWishListManagerDelegate
{
    func didFailWishList(failError: NSError?)
    func didGetWishList()
    func didAddToWishList()
    func didUpdate()
    func didDelete()
}

class ApiMyAccountWishListManager: ApiController
{
    // MARK: - Vars
    var delegateWishList: ApiWishListManagerDelegate?

    // MARK: - Inits

    override init()
    {
        super.init()
    }

    init(delegateWishList: ApiWishListManagerDelegate)
    {
        super.init()
        self.delegateWishList = delegateWishList
    }

    // MARK: - Functions

    func addToWishList(productId: Int)
    {
        var dataToPost = NSDictionary(objects: [productId], forKeys: ["pid"])
        post(MakeURL.addToWishList(), postData: dataToPost, callBack: parseAddToWishList)
    }

    func parseAddToWishList(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            self.delegateWishList!.didAddToWishList()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func readItems()
    {
        get(MakeURL.getWishList(), queryString: "", https: true, callBack: parseReadItems)
    }

    func parseReadItems(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            MyAccountDataCache.sharedInstance.saveWishList(jsonResultDictionary)
            self.delegateWishList!.didGetWishList()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func updateItemQuantity(productId: Int, quantity: Int, folderId: Int)
    {
        var dataToPost = NSDictionary(objects: [productId, quantity, folderId], forKeys: ["pid", "prodQty", "srcFolderID"])
        post(MakeURL.chageQuantity(), postData: dataToPost, callBack: parseUpdateItemQuantity)
    }

    func parseUpdateItemQuantity(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if wasCallSuccessfulAPI(response) && data?.length == 0
        {
            self.delegateWishList!.didUpdate()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func deleteItemFromFolder(productId: Int, folderId: Int = 0)
    {
        var dataToPost = NSDictionary(objects: [productId, folderId], forKeys: ["pid", "srcFolderID"])
        put(MakeURL.removeProduct(), postData: dataToPost, queryString: "", callBack: parseDeleteItemFromFolder)
    }

    func parseDeleteItemFromFolder(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            self.delegateWishList!.didDelete()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }
}

The main question is when a class is using this manager, for something like just getting the wishlist, we have a set of empty delegates like this:

    // MARK: - ApiWishListManager

    func didFailWishList(failError: NSError?)
    {
        hideSpinner()
    }

    func didGetWishList()
    {
        mainTableView.reloadData()
        hideSpinner()
    }

    func didAddToWishList()
    {
    }

    func didUpdate()
    {
    }

    func didDelete()
    {
    }

The add, update and delete are just sitting there never to be used.  I know about making them optional, using @objc, but I don't really want to add all the extra code that goes with checking if the delegate is setup before calling each one.  I've tried adding delegates within the same class, but I think that just starts looking too ugly and makes extra code for the classes that need all of the functions of this one manager.


texts: Multi-threaded code to handle messages from a provider

texts:
Having a look at my code, is there a way to be losing elements?

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class Main {
  private final static Map<String, Set<String>> data = Maps.newConcurrentMap();

  public static void main(String[] args) throws InterruptedException {
    new Main().init("X");
  }

  public void init(String code) throws InterruptedException {
    data.put(code, Sets.newConcurrentHashSet());

    subscribeToDataFrom(code);

    Set<String> elements = doHttpRequest();
    data.get(code).addAll(elements);

    data.get(code)
        .stream()
        .map(e -> e + "_MAPPED")
        .forEach(System.out::println);

    data.remove(code);
  }

  private void subscribeToDataFrom(String code) {
    Runnable r = () -> {
      while (true) {
        onMessageFromProvider(code, UUID.randomUUID().toString());
      }
    };

    new Thread(r).start();
    new Thread(r).start();
    new Thread(r).start();
    new Thread(r).start();
    new Thread(r).start();
  }

  public Set<String> doHttpRequest() throws InterruptedException {
    Set<String> resultsToReturn = Sets.newHashSet();
    resultsToReturn.add("B");
    resultsToReturn.add("C");
    resultsToReturn.add("D");
    resultsToReturn.add("E");
    resultsToReturn.add("F");
    Thread.sleep(1000);

    return resultsToReturn;
  }

  public void onMessageFromProvider(String code, String element) {
    final Set<String> newSet = data.computeIfPresent(code, (k, v) -> {
      v.add(element);
      return v;
    });

    if (newSet == null) {
      System.out.println("Ok, now I can do something different with: " + element);
    }
  }
}

I want to be able to execute the init code, get response from doHttpRequest, and once we have it, merge those results with the streamed results by subscribeToDataFrom, without losing any data.

Do I need any synchronised keyword to guarantee that, or is my code thread-safe and there's no way I'm losing any element coming from HTTP / Streaming?


texts:
I needed a lot of data for a tensorflow project so I made a web scraper to get all of the text and links off of websites then to repeat the process at all of those links.

I left it on overnight and it did not get much done, so I spent the day optimizing it. I can't find any ways to optimize it more (If anyone knows a way I would like to hear it.) I used it on CNN and now I have a 9 gig text file.

BTW: I used faster_than_requests and selectolax because they are faster then urllib3 and bs4 and you should check them out

import cython # helps speed up code
from selectolax.parser import HTMLParser #bs4 but faster
import faster_than_requests #urllib but faster
import _pickle as pickle #saving code
from colorama import init #just makes error messages stand out
from colorama import Fore, Back, Style

init() #colorama thing

#cdef is a cython thing, helping speed up code
cdef int i = 0

cdef list urls
cdef list text

cdef set visits #is a set for efficiency

cdef str mainsite = "https://www.cnn.com" #The main site keeps the scraper
                     #from straying too far from its original site.
cdef str source

parsing = True

try:
  with open('visits.pickle', 'rb') as f:
    visload = pickle.load(f)
    visits = visload[1]
    i = visload[0]
except Exception as e:
  print(Back.RED + "Error loading Visits: " + str(e))
  visits = set('')
  i = 0

try:
  with open('txt.pickle', 'rb') as f:
    txt = pickle.load(f)
except Exception as e:
  print(Back.RED + "Error loading txt: " + str(e))
  txt = []

try:
  with open('links.pickle', 'rb') as f:
    urls = pickle.load(f)
except Exception as e:
  print(Back.RED + "Error loading urls: " + str(e))
  urls = ["https://www.cnn.com"]

while parsing:

  try:
    if urls[0][0] == "/": #checks to see if it can go
                          # to the site directly or it needs to add
                          #the main site to the front
      source = faster_than_requests.get2str(mainsite + urls[0])
      dom = HTMLParser(source)
      print(Back.BLACK + mainsite + urls[0])
    else:
      source = faster_than_requests.get2str(urls[0])
      dom = HTMLParser(source)
      print(Back.BLACK + urls[0])

    for tag in dom.tags('p'):
      txt.append(str(dom.text())) #finds text and saves it

    for tag in dom.tags('a'):
      attrs = tag.attributes
      if 'href' in attrs:
          urls.append(attrs['href']) #finds links and saves them
  except:
    print(Back.RED + f"Error: {urls[0]}") # it will through up an error
                                          # if it tries to go to a sub-page
                                          # of another site, but this is
                                          # an intended feature

  visits.add(urls[0])
  #visits keeps track of visites web pages

  i = i + 1
  clean = True

  #clean make shure that it does not repeat a webpage.
  while clean:
    if urls[0] in visits:
      del(urls[0])
    else:
      clean = False

  print(Back.BLACK + f"urls:{len(urls)}, i:{i}, text lang:{len(txt)}")

  if i % 10000 == 0:
    #Save every 10000 webpages
    with open('txt.pickle', 'wb') as f:
      pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL)
    with open('links.pickle', 'wb') as f:
      pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL)
    with open('visits.pickle', 'wb') as f:
      pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL)

  if 0 == len(urls):
    parsing = False
    print(txt)
    with open('txt.pickle', 'wb') as f:
      pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL)
    with open('links.pickle', 'wb') as f:
      pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL)
    with open('visits.pickle', 'wb') as f:
      pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL)


texts:
This code could be better?

This is the algorithm:

Compare the 1st character to the last character
Compare the 2nd character to the second last character and so on
Stop when the middle of the string is reached
Just words

namespace Palindrome
{
    class Class1
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("Digit a word:");
                string word = Console.ReadLine();

                if (word == "exit")
                    break;

                VerifyPalindrome(word);
            }
        }

        private static void VerifyPalindrome(string word)
        {
            bool compare = true;
            int i = 0;
            while (i < word.Length- 1)
            {
                if (compare)
                {
                    for (int j = word.Length - 1; j >= 0; j--)
                    {
                        if (word[i] == word[j])
                            compare = true;
                        else
                        {
                            compare = false;
                            break;
                        }
                        i++;
                    }
                }
                else
                    break;
            }

            if (compare)
                Console.WriteLine("This is a Palindrome word");
            else
                Console.WriteLine("This is NOT a Palindrome word");
        }
    }
}


texts: Fully Generic C++ Stack Implementation Without Lists, Arrays, or Vectors

texts:
I'm trying to write a fully generic Stack in C++.  I'm not sure if this is the best way to do this.

Right now I know that the Pop method needs improvement since if T is a value type, returning a nullptr will cause a compiler error.  Also, I'm pretty sure that this can be optimized in a few ways, but I don't see any obvious areas at the moment.  Are there any other specific ways this can be improved?

Any and all feedback is appreciated.

#ifndef STACK_H
#define STACK_H

template <class T>
class Stack
{
public:
    Stack();
    Stack(T& data);
    ~Stack();

    // Public Stack operations
    void Push(T& data);
    T Pop();
    void Clear();

    // Accessors
    const T& Top() const { return m_top->m_data; }
    const T& Bottom() const { return m_bottom->m_data; }
    bool IsEmpty() const { return m_size == 0; }
    int Size() const { return m_size; }

private:
    template <class T> struct StackNode
    {
        StackNode(T& data)
        {
            m_data = data;
            m_nextNode = nullptr;
        }

        T m_data;
        StackNode<T>* m_nextNode;
    };

    int m_size;
    StackNode<T>* m_top;
    StackNode<T>* m_bottom;
};

template <class T> Stack<T>::Stack()
{
    m_top = nullptr;
    m_bottom = nullptr;
    m_size = 0;
}

template <class T> Stack<T>::Stack(T& data)
{
    m_top = m_bottom = new StackNode<T>(data);
    m_size = 1;
}

template <class T> Stack<T>::~Stack()
{
    Clear();
}

template <class T> void Stack<T>::Push(T& data)
{
    StackNode<T>* newNode = new StackNode<T>(data);
    newNode->m_nextNode = m_top;
    m_top = newNode;
    ++m_size;
}

template <class T> T Stack<T>::Pop()
{
    if (!IsEmpty())
    {
        T returnData = m_top->m_data;

        StackNode<T>* temp = m_top->m_nextNode;
        delete m_top;
        m_top = temp;
        --m_size;
        return returnData;
    }

    // there is an issue here because if T is a value type, this will cause an error
    //return nullptr;
}

template <class T> void Stack<T>::Clear()
{
    if (!IsEmpty())
    {
        StackNode<T>* next = nullptr;
        do
        {
            next = m_top->m_nextNode;
            delete m_top;
            m_top = next;
            --m_size;
        } while (m_top != nullptr);

        m_top = m_bottom = nullptr;
    }
}

#endif


texts: Calculating profit and score, if coordinates fall in a certain region of a field

texts:
My function takes the values of the profit (function declared as fieldProfit) and the field score (function declared as fieldScore). If both are above 10, then you earn a badge, hence, innerbadge = 1.

But, there's also another condition that must be met: the field or (x, y) coordinates have to fall in the area depicted as the shaded in box that has a hole in the middle.  Here's the image:

I've written the code for it, and I just wanted to make sure that my logic/syntax is correct.

 int badgeInnerCircle(int x, int y) {
       double fprofit, fscore;
       int innerbadge;

       if ((x >= 1 && x <= 20) && (y >= 1 && y <= 20)) {
          if (((x == 7 || x == 8) && (y >= 7 && y <= 14)) || ((x == 13 || x == 14)
             && (y >= 7 && y <= 14)) || ((x >= 7 && x <= 14) && (y == 7 || y == 8))
                || ((x >= 7 && x <= 14) && (y == 13 || y == 14))) {
             fprofit = fieldProfit(x, y);
             fscore = fieldScore(x, y);
             if (fprofit >= 10 && fscore >= 10) {
                innerbadge = 1;
             }
             else {
                innerbadge = 0;
             }
          }
       }
       else {
          innerbadge = -1;
       }
       return innerbadge;
    }


texts: Emit different text and sound when each of three buttons is pressed

texts:
I would like to use this same code on multiple pages of photos (to help my son recognize people). So instead of reinserting the name of each person, I created the appearingInPhoto (tuple or array), so I can utilize just .a .b .c, instead of having to go and rename each line of code.

Is there a way to simplify the code further, so I can just have code that checks if a button is pressed (check that sender.currentTitle is equal to any of the tuple values) and if yes, run this code?

print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a

This is the full function now:

var appearingInPhoto = (a:"omar", b:"john", c:"thomas")

@IBAction func buttonPressed(_ sender: UIButton) {
    var soundName: String? = nil
    if sender.currentTitle == appearingInPhoto.a {
        print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a
    }else if sender.currentTitle == appearingInPhoto.b {
        print("pressed \(appearingInPhoto.b)")
        label.text = appearingInPhoto.b
        soundName = appearingInPhoto.b
    }else if sender.currentTitle == appearingInPhoto.c {
        print("pressed \(appearingInPhoto.c)")
        label.text = appearingInPhoto.c
        soundName = appearingInPhoto.c
    }
    if let soundName = soundName {
        playSoundFile(soundName)
    }
  }


texts:
After sticking with the same handful of languages for years, I decided to learn C.

I've written a guess the number game, where it generates a random number based on the difficulty level, and then you have 5 attempts of guessing the number.

If you guess incorrect, it will give you a clue by telling you if the answer is higher or lower than your last guess. I find the game to be pretty interactive, and wanted to get a code review to see how I could improve on it.

This is my first ever C  program and I'm just looking to improve.

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

int generate_random_number(int min, int max) {
    srand ( time(NULL) );
    return min + (rand() % (max - min));
}

void play() {

    int difficulty = 1; // 1 = easy, 2 = medium, 3 = hard, 4 = insane

    printf("1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\n");
    printf("What level would you like to play: ");

    scanf("%i", &difficulty);

    int min = 0;
    int max = 0;
    int random = 0;

    if (difficulty == 1) {
        min = 0;
        max = 25;

        printf("You have selected to play easy\n\n");
    }
    else if (difficulty == 2) {
        min = 0;
        max = 50;

        printf("You have selected to play medium\n\n");
    }
    else if (difficulty == 3) {
        min = 0;
        max = 75;

        printf("You have selected to play hard\n\n");
    }
    else if (difficulty == 4) {
        min = 0;
        max = 100;

        printf("You have selected to play insane\n\n");
    }

    random = generate_random_number(min, max);

    int tries = 5;
    int won = 0;

    while (tries > 0)
    {
        int guess = 1000000; // just so it doesn't accidentally equal to random

        printf("Guess a number %i to %i: ", min, max);
        scanf("%i", &guess);

        if (guess == random) {
            won = 1;
            break;
        }
        else {
            if (guess > random) {
                printf("Incorrect guess, the answer is lower than your guess!\n\n");
            }
            else {
                printf("Incorrect guess, the answer is higher than your guess!\n\n");
            }
        }

        tries -= 1;
    }

    if (won) {
        printf("Congratulations, you have won the game!");
    }
    else {
        printf("Sorry, you are out of tries.\n\n");
    }
}

int main() {
    while (1) {
        play();
    }

    return 0;
}


texts: Convert characters to octal, binary, and integer

texts:
I have implemented a sample program that converts vector of characters to its integer representation depending on the bit size specified. I was hoping to get some input on how to simplify the sequence. I think my approach is convoluted.

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <iterator>

int OctalToBinary(int octalNum) {
    int decimalNum = 0, binaryNum = 0, count = 0;

    while (octalNum != 0) {
        decimalNum += (octalNum % 10) * pow(8, count);
        ++count;
        octalNum /= 10;
    }
    count = 1;
    while (decimalNum != 0) {
        binaryNum += (decimalNum % 2) * count;
        decimalNum /= 2;
        count *= 10;
    }
    return binaryNum;
}

int main()
{
    std::vector<char> buffer = { '3','7','4','3','0'};
    std::vector<int> bitsize = { 3,3,8 };
    std::vector<char> collection;
    std::vector<std::string> output;

    // convert characters to octal and

    for each ( char c in buffer)
    {
        int x = c - '0';
        std::stringstream opt;
        opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";

        std::string val = opt.str();

        std::copy(val.begin(), val.end()-1, std::back_inserter(collection));
    }

    int start_index = 0;
    int end_index = 0;

    // convert binary values to integer
    for (int i = 0; i < bitsize.size(); i++)
    {
        start_index = end_index;
        end_index += bitsize[i];

        std::string temporary_string(collection.begin() + start_index, collection.begin() + end_index);
        int converted_integer = std::stoi(temporary_string.c_str(), nullptr, 2);
        std::cout << temporary_string << " " << converted_integer << "\n";
    }

    // output should be 3, 7 , 140

    int x;
    std::cin >> x;
    return 0;
}


texts: Converting Pandoc Markdown images from captioned to inline

texts:
After writing a rather long document in Markdown and using pandoc to convert it to a PDF, I found, to my dismay, that many of the images were out of place, and that they all had their alternate text proudly displayed underneath them as captions. My document is rather instructional, so this rearrangement was harmful to its readability.

I eventually found a way to display the images as inline. I still wanted to write the document in standard Markdown, though, so I wrote a Python script to convert all the standalone images in a document to this inline form.

pandoc_images.py:

import sys

# Convert standalone images in standard Markdown
# to inline images in Pandoc's Markdown
# (see http://pandoc.org/README.html#images)
with open(sys.argv[1], 'r') as markdown:
    lines = markdown.read().splitlines()
    for index, line in enumerate(lines):
        is_first_line = index == 0
        preceding_blank = True if is_first_line else not lines[index - 1]

        is_last_line = index == len(lines) - 1
        following_blank = True if is_last_line else not lines[index + 1]

        is_standalone = preceding_blank and following_blank
        is_image = line.startswith('![') and '](' in line and line.endswith(')')
        print(line + ('\\\n' if is_standalone and is_image else ''))

Example (text.md):

This is some text.

![This is an image.](image.png)

### This is a header.

Running python3 pandoc_images.py text.md would produce:

This is some text.

![This is an image.](image.png)\

### This is a header.

It seems like a lot of mess (enumerate, bounds checking, etc.) for such a simple job, though. Is there any way I can improve any of this code?


texts: Operations on files and their locks - code too bulky?

texts:
A couple of hours ago I asked a question on Stackoverflow to find out if there is a good way to delete files in a folder only if all files are indeed deletable and I got some good answers that led me (I think) in the right direction

Based on the two currently most upvoted answers I scrambled together the following code:

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        File directory = new File("T:\\download\\test\\1234");

        if (safeDelete(directory)) {
            System.out.println("All deleted");
        } else {
            System.out.println("All kept");
        }
    }

    private static boolean safeDelete(File directory) {
        if (directory == null || !directory.isDirectory()
                || !directory.canWrite()) {
            return false;
        }

        // First get a lock on the directory itself
        FileLock dirLock;
        if ((dirLock = getLock(directory)) == null) {
            return false;
        }

        List<File> filesToDelete = new ArrayList<>();
        List<FileLock> fileLocks = new ArrayList<>();

        // Get a lock on all the files in the folder
        for (File file : directory.listFiles()) {

            FileLock lock;
            if (file.canWrite() && ((lock = getLock(file)) != null)) {
                filesToDelete.add(file);
                fileLocks.add(lock);
            } else {
                System.out.println("Currently unable to write to "
                        + file.getName());
                releaseLocks(fileLocks);
                return false;
            }
        }

        // If we reach this line all the files are locked for us now
        for (File file : filesToDelete) {
            if (!file.delete()) {
                System.out.println("IMPOSSIBLE");
            }
        }
        releaseLocks(fileLocks);

        directory.delete();
        releaseLock(dirLock);
        return true;
    }

    private static FileLock getLock(File file) {
        try {
            return new RandomAccessFile(file, "rw").getChannel().tryLock();
        } catch (IOException ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    private static void releaseLocks(List<FileLock> locks) {
        for (FileLock lock : locks) {
            releaseLock(lock);
        }
    }

    private static void releaseLock(FileLock lock) {
        if (lock != null) {
            try {
                lock.release();
                System.out.println("Released lock on " + lock.toString());
            } catch (IOException ex) {
                System.out.println("Cant release lock on " + lock.toString());
            }
        }

    }
}

But it seems so... bulky to me. There are many return statements in there (I personally like it better when there is only one at the very end), a lot of if-else branching, two ArrayLists that manage almost the same stuff and a lot of calls to the releaseLocks() method.

The core problem is in my opinion that I have to manage two sets of data on which I both have to operate:

The Files on which I have to execute the deletion
And the Locks which I have to release after I'm done

So the question is:Can this be done more efficiently? Should I refactor the safeDelete() into more sub-methods?


texts: Reversing an array in C++ 14, my second array requires an extra element

texts:
Hackerrank problem to reverse an array of size n.
https://www.hackerrank.com/challenges/30-arrays/
Sample Input:
4
1 4 3 2

Sample output:
2 3 4 1

Much of this code was already given, you can skip to the "This is what I did" section.
#include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string arr_temp_temp;
    getline(cin, arr_temp_temp);

    vector<string> arr_temp = split_string(arr_temp_temp);

    vector<int> arr(n);
    vector<int> arr2(n);

    for (int i = 0; i < n; i++) {
        int arr_item = stoi(arr_temp[i]);

        arr[i] = arr_item;
    }

    for (int i = 0; i <= n; i++){
        arr2[n-i] = arr[i];
    }
    for (int i = 1; i <= n; i++){
        cout << arr2[i] << " ";
    }
    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}

This is what I did
I declared another array named array2 of size n to hold the reversed value which would then be printed.
I then wrote this snippet to reverse the array and copy it to array2:
  for (int i = 0; i <= n; i++){
        arr2[n-i] = arr[i];
    }
    for (int i = 1; i <= n; i++){
        cout << arr2[i] << " ";
    }

This code works, but I feel like I have made a mistake since I have iterated n+1 times in the for loop. I tried iterating n times but one element of the array got the value 0. Indexing is also done differently since I am indexing from 1 to n. This is confusing to me, because I declared array2 as size n. How and when did the vector get resized?
Is there a more elegant solution using n iterations? If not, why not?