texts: Loop over whole array starting from any index

texts:
I recently had to repeatedly iterate over an array but increment the index to start from each time. Since this is quite cumbersome in comparison to a normal for loop I made a small template function that does this for me:

#include <algorithm>
#include <iostream>

template<typename TSize, typename TFunc>
void for_start(const TSize start, const TSize size, TFunc&& fn)
{
    for(TSize c{}, i{c + start}; c < size; ++c, ++i)
    {
        if(i >= size)
            i = 0;
        fn(i);
    }
}

template<typename TRAIter, typename TFunc>
void for_start(TRAIter start, TRAIter begin, TRAIter end, TFunc&& fn)
{
    for(TRAIter c{begin}, i{c + std::distance(begin, start)}; c != end; ++i, ++c)
    {
        if(i == end)
            i = begin;

        fn(i);
    }
}

// usage
int main()
{
    const unsigned ARR_SIZE{10};
    int arr[ARR_SIZE]{
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    };

    for_start(5u, ARR_SIZE, [arr](unsigned i)
    {
        std::cout << arr[i] << ' ';
    });
    std::cout << '\n';

    for_start(std::begin(arr) + 5, std::begin(arr), std::end(arr), [](const int* i)
    {
        std::cout << *i << ' ';
    });
}

// prints:
// 5 6 7 8 9 0 1 2 3 4
// 5 6 7 8 9 0 1 2 3 4

I'd like to get some feedback on things like usability (function name, order of parameters) and reuseability. Note that I'd like to use this function with signed & unsigned integers.


texts:
I've written a short Random Exam Generator program.
There are 6 days, 3 time slots per day. One day can not have more than 2 exams. There will be 5 exams in total.

I am fairly new to programming so I would like some feedback on how well this code is written, and if there are any ways to improve it.

var exam_days =
    { 0: 0,
      1: 0,
      2: 0,
      3: 0,
      4: 0,
      5: 0 };

var exam_array = [];

function generateSchedule() {
  for (var i = 0; exam_array.length < 5; i++){
    var time = getRandomInt(0,2);
    var day = getRandomInt(0,5);
    var exam_id = "exam-" + time + day;
    if (dayAvailable(day, exam_days) && uniqueExam(exam_id, exam_array)) {
      exam_days[day] += 1;
      exam_array.push(exam_id);
      document.getElementById(exam_id).style.background = "green";
    }
  }
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function dayAvailable(date, exam_days) {

  if (exam_days[date] < 2) {
      return true;
    }
  return false;
}

function uniqueExam(exam, exam_array)
{
    var count = exam_array.length;
    for (var i = 0; i < count; i++)
    {
        if (exam_array[i] === exam)
          return false;
    }
    return true;
}


texts: Spreadsheet generated through Google Drive file iteration

texts:
I put together a script which goes through all of the files in Google Drive, and writes a spreadsheet with all of the files with their name, containing folder, URL, and date last updated.

function Start_Up() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  sheet.clear();
  sheet.appendRow(['Name', 'Folder', 'URL', 'Updated'])

  var start_time = new Date();
    MailApp.sendEmail({
      to: 'insert e-mail',
      subject: "Master File Update - Started",
      htmlBody: "The update of the master equipment document spreadsheet was started at: " + start_time});

  var Script_Properties = PropertiesService.getScriptProperties();
  Script_Properties.deleteAllProperties();
  Iterate_Files();
}

function Delete_Triggers() {
  var Triggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < Triggers.length; i++) {
    ScriptApp.deleteTrigger(Triggers[i]);
  }
}

function Iterate_Files() {
  var Script_Properties = PropertiesService.getScriptProperties();
  var continuationToken = Script_Properties.getProperty('C_Token');

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();

  Delete_Triggers();

  var Start_Time = new Date().getTime();
  var Seconds = 0;

  if (continuationToken) {
    var files = DriveApp.continueFileIterator(continuationToken);
  } else {
    var files = DriveApp.getFiles();
  }

  var output = [];

  while (files.hasNext() && Seconds < 240) {
    var file = files.next();
    var Current_Time = new Date().getTime();
    var Seconds = Math.floor((Current_Time - Start_Time)/1000);

    var file_name = file.getName();
    if (file.getParents().hasNext()) {
      var folder_name = file.getParents().next().getName();
    } else {
      folder_name = 'Root';
    }
    var file_url = file.getUrl();
    var file_last_updated = file.getLastUpdated();
    output.push([file_name, folder_name , file_url, file_last_updated]);
  }
  if (output.length) {
    var last_row = sheet.getLastRow();
    sheet.getRange(last_row +1, 1, output.length, 4).setValues(output);
  }

  if (files.hasNext()) {
    var triggerID = null;
    continuationToken = files.getContinuationToken();
    Script_Properties.setProperty('C_Token', continuationToken);
    ScriptApp.newTrigger('Iterate_Files')
    .timeBased()
    .after(1 * 60 * 1000)
    .create();
  } else {
    Script_Properties.deleteAllProperties();
    var end_time = new Date();
    MailApp.sendEmail({
      to: 'insert email',
      subject: "Master File Update - Complete",
      htmlBody: "The update of the master equipment document spreadsheet was completed at: " + end_time});

    ScriptApp.newTrigger('Start_Up')
    .timeBased()
    .everyDays(1)
    .atHour(0)
    .create();
  }
}

It currently runs through 50,000+ files in a large number of folders and I am hoping that some of you may see areas which I may be able to improve performance in order to reduce run time.

** The sheet does not necessarily need to be cleared and re-created as long as there is a viable method of tracking which files have been indexed previously.


texts: Convert String to Integer (calculator app)

texts:
I'm currently learning Swift and today I created my first application, a simple calculator. My main goal was to practice and create something without any help. After a few hours my application was ready for use but of course not perfect. After overlooking my code I noticed that there are areas which I should improve. For example, I think I could simplify this area:

zahlXS = DisplayX.text!
zahlYS = DisplayY.text!
let zahlX = Int(zahlXS)
let zahlY = Int(zahlYS)

My goal is to take the String variable zahlXS and convert it to an  integer variable, so I'm able to calculate with my variables. Please note that I declared zahlXS and zahlYS at the very beginning of my code.

I'm also trying to use the "MVC" concept. In this application, I put my functions add and sub in the ViewController because I first created a struct in a separate file but I just couldn't access the functions in my ViewController. I tried to create a whole class instead of a struct afterwards, but this didn't solve the problem either.

import UIKit
import Foundation

var zahlXS: String = String()
var zahlYS: String = String()

func add(x: Int, y: Int) -> Int {
return x + y
}

func sub(x: Int, y: Int) -> Int {
return x - y
}

class ViewController: UIViewController {

@IBOutlet weak var DisplayX: UITextField!

@IBOutlet weak var DisplayY: UITextField!

@IBOutlet weak var Resultat: UILabel!

@IBAction func performAddition(_ sender: UIButton) {
    zahlXS = DisplayX.text!
    zahlYS = DisplayY.text!
    let zahlX = Int(zahlXS)
    let zahlY = Int(zahlYS)

    let resultAdd = add(x: zahlX!, y: zahlY!)
    Resultat.text = "The result is: \(resultAdd)"

}

@IBAction func performSubtraktion(_ sender: UIButton) {
    zahlXS = DisplayX.text!
    zahlYS = DisplayY.text!
    let zahlX = Int(zahlXS)
    let zahlY = Int(zahlYS)

    let resultSub = sub(x: zahlX!, y: zahlY!)
    Resultat.text = "The result is: \(resultSub)"

}

}


texts: jQuery multiple events execute same function refactoring

texts:
I am working a project which uses a function to show a modal dialog. The dialog can be hidden by calling the hideModal() function. This function is triggered by:

Pressing the ESC key
Clicking on the modal background
Clicking on the close button

My current code is:

 $("#modal").click(function() {
    hideModal();
});

$("#modal-object-container > a").click(function(e) {
    hideModal();
    e.preventDefault();
});

$(document).keydown(function (e) {

    if (e.keyCode == '27') {
        hideModal();
    }

});

I have the feeling there should be a faster way to bind all these events at once.


texts: Horizontally concatenating the entries of two matrices, and padding with NaNs

texts:
I have two matrices a and b that have, on each line, some values (null or not) and then a bunch of zeros at the end.

I want to construct a matrix c that for each line has the corresponding line of a from the first element till to the last not-null element, concatenated with the corresponding line of b from the first element till to the last not-null element. Like in the following example:

>> a=[1 NaN 3 0; 1 0 0 0]

a =

     1   NaN     3     0
     1     0     0     0

>> b=[1 0 1 0; 0 0 0 0]

b =

     1     0     1     0
     0     0     0     0

>> c=NaN(2,8) %same dimension as a and b

c =

   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN

        for ii=1:size(a,1)
        [v,x]=find(a(ii,:));
        if numel(x)>0 %it could be all null
            x1=a(ii,1:x(end)); %x(end) because I want to retain the zeros before the last not-null element
        end
        [v,x]=find(b(ii,:));
        if numel(x)>0
            x1=[x1 b(ii,1:x(end))];
        end
        c(ii,1:numel(x1))=x1;
        end
>> c

c =

     1   NaN     3     1     0     1   NaN   NaN
     1   NaN   NaN   NaN   NaN   NaN   NaN   NaN

How can I improve this code?
a and b always have the same dimensions (that can be different from the example though). a and b values can be positive/negative finite or infinite doubles or NaNs.
In my case I am interested only to merge two matrices.

Are there "standard" ways to vectorize a code? What do you look at when thinking to how vectorize a code?


texts:
Based on what i understood of Binary Tree, queue and recursion I implemented this Breadth First Search algorithm as follows.
Do you have any suggestions to improve (in term of readability, good practice etc...) it?
# Definition for a binary tree node.
class Node(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def preorder_print(self):
        print(self.val)
        if self.left:
            self.left.preorder_print()
        if self.right:
            self.right.preorder_print()
        return

    def postorder_print(self):
        if self.left:
            self.left.postorder_print()
        if self.right:
            self.right.postorder_print()
        print(self.val)
        return

    def inorder_print(self):
        if self.left:
            self.left.inorder_print()
        print(self.val)
        if self.right:
            self.right.inorder_print()
        return

    def bread_traversal_print(self):
        q=Queue()
        q.push(self)
        def bt():
            #import pdb;pdb.set_trace
            if not q:
                return
            node=q.pop()
            if node:
                if  node.left:
                    q.push(node.left)
                if  node.right:
                    q.push(node.right)
                print(node.val)
                bt()
        bt()

class Queue():
    def __init__(self):
        self.data = []

    def push(self,elt):
        self.data.append(elt)

    def pop(self):
        if self.data:
            return self.data.pop(0)
    def peek(self):
        if self.data:
            return self.data[0]

if __name__ == "__main__":
    #input = [l for l in 'FDJBEGKACIH']
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    print("preorder:")
    root.preorder_print()
    print("postorder:")
    root.postorder_print()
    print("inorder:")
    root.inorder_print()

    print('bread :')
    root.bread_traversal_print()

    """          1
            2       3
        4     5    6  7

    [1 2 4 5 3 6 7]

    """

EDIT: Yes BFS for Breadth First Search would be more appropriate ;)


texts: Reverse multiple strings separated by comma

texts:
Recently I did a lot of practice problems in brainfuck to learn better about how to use it (and to get more competent in general). Today I write a program to manipulate the input such that every word (separated by comma ,) is printed in reverse, while the commas are kept in place, which I'm quite proud of. Example provided in the statement: Input: Hello,world\0 Output: olleH,dlrow

Feel free to rip my code (and comments as well) apart and give some pointers on how my code could be improved!

>, 1:read
[ ~a:varchar a:in
[>+>+<<-] a:0 b:c:in
>>>>++++[<+++++ +++++ +>-]<[<->-] a:0 b:in [c:in-44]
<[[-]<[<+>-]>>] if c then a:in else
<[<<[.<]>[>]>.>]< print reverse then comma
, redo a':read ]
<[.<] print reverse


texts: Fastest way to remove/hide a lot of elements from a list

texts:
I have a dropdown that contains around 100,000 rows which make up a list.

<input id="search" type="text" />

item 1

item 2

        ...

item 100,000

I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not match. This is the class I wrote to perform the removing of list elements.

See the fiddle (list has about 2000 items)

// requires jQuery
var Search = (function(){

    var cls = function (name) {
        var self = this;

        self.elem = $('#' + name);
        self.list = $('#' + name).next('ul').children();
        self.elem.bind('keyup', function () { self.change(); });
    };

    cls.prototype = {
        change: function () {
            var self = this;
            // gets the closest ul list
            var typed = self.elem.val();

            // only do something if there is something typed
            if (typed !== '') {
                // remove irrelevent items from the list
                self.list.each(function () {
                    var item = $(this).html();
                    if (item.indexOf(typed) === -1)  {
                        $(this).addClass('zero');
                        // tried using a class with visibility hidden
                    } else {
                        $(this).removeClass('zero');
                    }
                });
            } else {
                // check what list items are 'hidden' and unhide them
                self.list.each(function () {
                    if ($(this).hasClass('zero')) {
                        $(this).removeClass('zero');
                    }
                });
            }
        }
    };
    return cls;
}());

I am just adding a class which adds a height: 0, and no margin, padding, etc, but I have also tried using visibility: hidden. I have also tried using the detach method in jQuery but this is about the same in terms of speed.

Are there any JavaScript experts who can see any problems with the code, or offer some optimization techniques?


texts:
Overview
Below is a simple program to estimate pi to the full precision of the provided type. It uses
Machin's formula, but this question is about coding style / choices. It compares the result to M_PI from <cmath> - best we have in C++17.
Questions

Is my use of enable_if_t appropriate and idiomatic?
Is the use of static_cast<T> for one_over_5 and one_over_239 the "best" solution here? Neccesary, and appropriate?
How about the use of decltype, ::epsilon and ::digits10?
Accuracy: How about sign =* -1 and den += 2.0 and ... = sign * ...? These are integer operations but use the floating point type.
My choice to force the user of pi<T>() to specify a T?

Note: I know the templates should probably be in header file, but all in one here for simplicity on CR.
#include <cmath>
#include <iomanip>
#include <iostream>
#include <type_traits>

template <typename T, std::enable_if_t<std::is_floating_point_v<T>, bool> = true>
T arctan(T tan) {
  // fabs(tan) > 1 will not converge
  T num  = tan;
  T den  = 1.0;
  T sign = 1.0;
  T term = num;
  T res  = num;
  while (std::fabs(term) > std::numeric_limits<T>::epsilon()) {
    num *= tan * tan;
    den += 2.0;
    sign *= -1.0;
    term = sign * num / den;
    res += term;
  }
  return res;
}

template <typename T, std::enable_if_t<std::is_floating_point_v<T>, bool> = true>
T pi() {
  T one_over_5   = static_cast<T>(1.0) / static_cast<T>(5.0);
  T one_over_239 = static_cast<T>(1.0) / static_cast<T>(239.0);
  return (static_cast<T>(4.0) * arctan<T>(one_over_5) - arctan<T>(one_over_239)) *
         static_cast<T>(4.0);
}

int main() {
  auto pi_float = pi<float>();
  auto pi_double = pi<double>();
  auto pi_long_double = pi<long double>();
  std::cout << std::setprecision(std::numeric_limits<decltype(pi_float)>::digits10)
            << pi_float << '\n'
            << std::setprecision(std::numeric_limits<decltype(pi_double)>::digits10)
            << pi_double << '\n'
            << std::setprecision(std::numeric_limits<decltype(pi_long_double)>::digits10)
            << pi_long_double << '\n'
            << M_PI << '\n';
  return EXIT_SUCCESS;
}

Output - demonstrating that M_PI from <cmath> is actually incorrect at long double precision in the last 2 digits (the correct value is 3.1415926535897932384626433...)
Note (unrelated to question, but for future reference): It turns out that the reason M_PI is "wrong" is because the M_PI macro does not specify a literal L for long double, and hence the value is rounded to double precision before being displayed. If you put a literal 3.14159265358979323846L then it is accurate. Usually that is provided as the macro M_PIl.
3.14159
3.14159265358979
3.14159265358979324
3.14159265358979312


texts:
I wrote this game to practice some simple OOP. You play against the computer, but be aware that the computer has no real AI, as it just generates its moves randomly. The loser is the one whose turn it is when there is only one match left in the stack.

import java.util.Random;
import java.util.Scanner;

class Game {

    private boolean gameOver;
    Scanner input;
    Player computer, human;

    public Game() {

        computer = new Computer();
        human = new Human();
        input = new Scanner(System.in);

    }

    public void runGame(){

        System.out.println("Welcome to the game of Nim! How many matches would you like to play with?");
        human.setMatchesLeft(input.nextInt());

        while (!gameOver){

            if (computer.getMatchesLeft() != 1){
                System.out.print("Computers move: ");
                computer.playerTurn();
                computer.printStatus();

                if (computer.getMatchesLeft() == 1) {
                    gameOver = true;
                    System.out.println("Human loses, computer wins.");
                }
            }

            if (human.getMatchesLeft() != 1){
                System.out.print("Humans move: ");
                human.playerTurn();
                human.printStatus();

                if (human.getMatchesLeft() == 1) {
                    gameOver = true;
                    System.out.println("Computer loses, human wins.");
                }
            }

        }

    }

}

abstract class Player {

    private static int matchesLeft;

    public abstract void playerTurn();
    public abstract void printStatus();

    public void setMatchesLeft(int x){
        matchesLeft = x;
    }

    public int getMatchesLeft(){
        return matchesLeft;

    }

}

class Human extends Player {

    private int humanTurn;
    private Scanner input;

    public Human(){

        input = new Scanner(System.in);
    }

    public void playerTurn(){

        humanTurn = input.nextInt();

        while ( humanTurn > (getMatchesLeft() / 2) || humanTurn < 1 ) {
            System.out.print("Illegal move. Please pick at least 1 matches.\n");
            humanTurn = input.nextInt();
        }

        setMatchesLeft(getMatchesLeft() - humanTurn);

    }

    public void printStatus(){
        System.out.println("Human removes " + humanTurn + " matches. " + getMatchesLeft() + " matches left. ");
    }
}

class Computer extends Player {

    private int computerTurn;
    Random computerGen;

    public Computer(){
        computerGen = new Random();
    }

    public void playerTurn(){

            computerTurn = computerGen.nextInt(((getMatchesLeft() / 2) - 1) + 1) + 1;

        setMatchesLeft(getMatchesLeft() - computerTurn);

    }

    public void printStatus(){
        System.out.println(computerTurn);
        System.out.println("Computer removes " + computerTurn + " matches. " + getMatchesLeft() + " matches left. ");
    }

}

public class Nm {
    public static void main (String[] args){

        Game newgame = new Game();
        newgame.runGame();

    }
}


texts:
The setPixelColor function below changes the color of pixels.
I need some suggestions to optimize this function.

Example:

public static void main(String[] args) throws IOException {
    BufferedImage pic1 = ImageIO.read(new File("Images/Input-1.bmp"));
    setPixelColor(pic1, 34, 177, 76, 127, 127, 127);
}

This changes the left image into the right image.

 private static void setPixelColor(BufferedImage imgBuf, int red, int green, int blue, int newRed, int newGreen, int newBlue) throws IOException {
    int[] RGBarray;
    int w;
    int h;

    //Declare color arrays
    int[][] alphaPixels;
    int[][] redPixels;
    int[][] greenPixels;
    int[][] bluePixels;

    w = imgBuf.getWidth();
    h = imgBuf.getHeight();

    alphaPixels = new int[h][w];
    redPixels = new int[h][w];
    greenPixels = new int[h][w];
    bluePixels = new int[h][w];

    RGBarray = imgBuf.getRGB(0, 0, w, h, null, 0, w);

    //Bit shift values into arrays
    int i = 0;
    for (int row = 0; row < h; row++) {
        for (int col = 0; col < w; col++) {
            alphaPixels[row][col] = ((RGBarray[i] >> 24) & 0xff);
            redPixels[row][col] = ((RGBarray[i] >> 16) & 0xff);
            greenPixels[row][col] = ((RGBarray[i] >> 8) & 0xff);
            bluePixels[row][col] = (RGBarray[i] & 0xff);
            i++;
        }
    }

    //Set the values back to integers using re-bit shifting
    for (int row = 0; row < h; row++) {
        for (int col = 0; col < w; col++) {
            if (redPixels[row][col] == red && greenPixels[row][col] == green && bluePixels[row][col] == blue) {
                int rgb = (alphaPixels[row][col] & 0xff) << 24 |
                        (redPixels[row][col] & newRed) << 16 |
                        (greenPixels[row][col] & newGreen) << 8 |
                        (bluePixels[row][col] & newBlue);
                imgBuf.setRGB(col, row, rgb);
            }
        }
    }

    //Write back image
    ImageIO.write(imgBuf, "bmp", new File("Images/Output2.bmp"));
}


texts:
In my project I need to send emails. Emails will have different credentials and senders. I'm thinking about "abstract factory", but will it be good solution?

public abstract class Mail
    {
        public string Body { get; protected set; }
        public string Subject { get; private set; }
        public string EmailTo { get; private set; }

        protected Mail(string subject, string emailTo)
        {
            this.Subject = subject;
            this.EmailTo = emailTo;
        }

        protected abstract void BuildBody();
    }
public class AccountMail : Mail
    {
        private string _firstName;
        private string _lastName;
        private string _email;
        private string _siteDomain;
        public AccountMail(string subject, string emailTo, string firstName, string lastName, string siteDomain, string email): base(subject, emailTo)
        {
            _firstName = firstName;
            _lastName = lastName;
            _email = email;
            _siteDomain = siteDomain;
            BuildBody();
        }

        protected override sealed void BuildBody()
        {
             StringBuilder bodyBuilder = new StringBuilder();
             base.Body = bodyBuilder.ToString();
        }

That is abstract Mail and concrete Mail. Do I really need abstract MailSender and concrete MailSender for each email? This is quick solution, because I needed this functionality right now. It's working like this:

public abstract class MailSender
    {
        public abstract void SendMail(string subject, string emailTo, string firstName, string lastName);
    }
public class AccountMailSender : MailSender
    {
        public override void SendMail(string subject, string emailTo, string firstName, string lastName)
        {
            AccountMail mail = new AccountMail(subject, emailTo, firstName, lastName, "");
            Task.Factory.StartNew(() =>
            {
                MailMessage mailMessage = new MailMessage(ConfigSettings.EmailFrom, mail.EmailTo, mail.Subject, mail.Body);
                mailMessage.IsBodyHtml = true;
                SmtpClient client = new SmtpClient(ConfigSettings.EmailServer, ConfigSettings.EmailPort);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(ConfigSettings.EmailUser, ConfigSettings.EmailPassword);

                try
                {
                    client.Send(mailMessage);
                }
                catch
                {

                }
            });

        }
    }

I know that it's bad and that I need to refactor, but I also need your advice.


texts:
I'm new to Go, and as a learning project I've been implementing RC4, attempting to follow pseudo-code in the Wikipedia links (and trying not to look at the far-superior version in the crypto package).

Some questions:

Wikipedia suggests computing new array indexes using mod 256 at several points throughout the implementation.  However, mod 256 results in index out of bound errors or "constant 256 overflows byte".  What am I missing?
The crypto package returns a custom "Cipher" type, which has the rc4 function implemented on it.  Is this idiomatic Go (returning an objecty type) or something specific for the rc4 implementation?
any suggestions to improve clarity/speed/accuracy?

Source:

package main
import "fmt"

func ksa(keystring string) ([256]byte) {
  var key = []byte(keystring)
  var s [256]byte
  var j byte

  for i := 0; i < 255; i++ {
    s[i] = byte(i)
  }
  for i := 0; i < 255; i++ {
    j = (j + s[byte(i)] + key[i % len(key)]) % 255
    s[j], s[i] = s[i], s[j]
  }
  return s
}

func rc4(bufferstring string, key [256]byte) ([]byte) {
  buffer := []byte(bufferstring)
  res := make([]byte, len(buffer))
  var x, y, k, r byte = 0, 0, 0, 0

  for i, b := range(buffer) {
    x = (x + 1) % 255
    y = (y + key[x] % 255)
    y, x = x, y
    k = key[(key[x] + key[y]) % 255]
    r = b ^ k

    fmt.Printf("i: %d, b: %c, x: %#X, y: %#X, k: %#X, r: %#X  \n", i, b, x, y, k, r)
    res[i] = r
  }
  return res
}

func main() {
  keystring := "Secret"
  plaintext := "Attack at dawn"
  key := ksa(keystring)

  encrypted := rc4(plaintext, key)

  unencrypted := rc4(string(encrypted), key)

  fmt.Println("Encrypted")
  fmt.Printf("hex: %#X\n", string(encrypted))
  fmt.Printf("string: %s\n", string(encrypted))

  fmt.Println("Un-Encrypted")
  fmt.Printf("hex: %#X\n", string(unencrypted))
  fmt.Printf("string: %s\n", string(unencrypted))
}


texts: Expression evaluators, with possible short circuit evaluation

texts:
I'm writing a project, and the part I'm doing now is getting bloated real fast. How can I remove this nested if statements, but still have the same behaviour?

It would be nice the the resulting code was succinct, and extra local flags weren't required. This might not look so bad now, but I'm planning on writing more methods, up to T16, you can imagine how bad these nested if statements will get.

using ContainerExpressions.Containers;
using System;

namespace ContainerExpressions.Expressions.Core
{
    internal static class Compose
    {
        public static Response<T> Evaluate<T>(Func<Response<T>> func) => func();

        public static Response<TResult> Evaluate<T1, TResult>(Func<Response<T1>> func1, Func<T1, Response<TResult>> funcResult)
        {
            var response = new Response<TResult>();

            var result = func1();
            if (result)
            {
                response = response.WithValue(funcResult(result));
            }

            return response;
        }

        public static Response<TResult> Evaluate<T1, T2, TResult>(Func<Response<T1>> func1, Func<T1, Response<T2>> func2, Func<T2, Response<TResult>> funcResult)
        {
            var response = new Response<TResult>();

            var result1 = func1();
            if (result1)
            {
                var result2 = func2(result1);
                if (result2)
                {
                    response = response.WithValue(funcResult(result2));
                }
            }

            return response;
        }

        public static Response<TResult> Evaluate<T1, T2, T3, TResult>(Func<Response<T1>> func1, Func<T1, Response<T2>> func2, Func<T2, Response<T3>> func3, Func<T3, Response<TResult>> funcResult)
        {
            var response = new Response<TResult>();

            var result1 = func1();
            if (result1)
            {
                var result2 = func2(result1);
                if (result2)
                {
                    var result3 = func3(result2);
                    if (result3)
                    {
                        response = response.WithValue(funcResult(result3));
                    }
                }
            }

            return response;
        }
    }
}


texts: SSH Class with a method for downloading via SCP

texts:
I am looking for a code review on this class. I found myself writing this logic a lot, so trying to save myself some time.

require 'etc'
require 'net/ssh'
require 'net/scp'

class SSHOps
  def initialize(host, user=Etc.getlogin, *args)
    @host = host
    @user = user
    @keys = args.empty?  \
    ? args << Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa' \
    : args
  end

  ##
  # Download a file over SCP.
  #
  # ==== Attributes
  #
  # * +hostname+ - Target hostname to download the file from.
  # * +filename+ - Filename to download.
  def download_file(remote_path, local_path)
    ssh = Net::SSH.start(@host, @user, :keys => @keys)
    ssh.scp.download(remote_path, local_path, :preserve => true)
    ssh.close
  end

end


texts: Frontmost window of the current application that passes a predicate check

texts:
After resigning active state (going to the background), the mainWindow property of the main window in the app returns false.

Nevertheless, I need a to find that window even when my app is not active, so I came up with the following code, which works:

public let App = NSApplication.sharedApplication() // just some sugar

public extension NSApplication {

    public func frontmostWindow(_ accept: (NSWindow -> Bool)? = nil) -> NSWindow? {
        for windowNumber in NSWindow.windowNumbersWithOptions(0) as? [Int] ?? [] {
            if let window = windowWithWindowNumber(windowNumber) {
                if let accept = accept {
                    if accept(window) {
                        return window
                    }
                } else {
                    return window
                }
            }
        }
        return nil
    }
}

With this, I can now get the first window of my app in the current ordering that passes the provided predicate check (accept: NSWindow -> Bool). This is because I normally would not be interested in the menu bar or the status item, which all have associated windows that belong to my app (which is what I would get if I do not pass any predicate). As an example, say I have some:

class PimpedUpWindow: NSWindow, ExtraTranslucent {}

the frontmost instance of which I wish to find after the app launches and is no longer the active app. Using the extension above I can:

App.frontmostWindow { $0 is PimpedUpWindow }

or

App.frontmostWindow { $0 is ExtraTranslucent }

Of course, I can provide any other predicate of type NSWindow -> Bool, but I figure I will often enough want to just check the type or protocol conformance. So I might as well add two convenience methods for just those occasions:

public extension NSApplication {

    public func frontmost <T> (windowOfType: T.Type) -> T? {
        return frontmostWindow { $0 is T } as? T
    }

    public func frontmostWindow <P> (conformingTo: P.Type) -> NSWindow? {
        return frontmostWindow { $0 is P }
    }
}

Now, I can simply:

App.frontmost(PimpedUpWindow)

Which actually returns a PimpedUpWindow?, and:

App.frontmostWindow(ExtraTranslucent)

which returns an NSWindow?.

All ideas, criticisms, and comments very welcome!


texts:
I need to know whether I am doing the best way of binding click event through elements in jQuery. I need to avoid duplicate code in my function (since lot of duplicate code is repeated in all functions).

How can I clean this up and do it in a better way?

 $(".nna-icon-excel").click(function (e) {
                var $this = $(this);
                $this.parent().attr("href", "?excel=1")
                var href = $this.parent().attr("href");
                if (activeTab.toLowerCase() == "table") {
                    action = "expand";
                }
                else {
                    action = "expandheatmap";
                }
                $this.parent().attr("href", href + "&from=" + action + "&expand=" + Expand + "");
            });
            $(".nna-icon-pdf").click(function (e) {
                var $this = $(this);
                $this.parent().attr("href", "?savehtml=1&openpdf=1&orientation=@ViewBag.PdfOrientation")
                var href = $this.parent().attr("href");
                if (activeTab.toLowerCase() == "table") {
                    action = "expand";
                }
                else {
                    action = "expandheatmap";
                }
                $this.parent().attr("href", href + "&from=" + action + "&tabactive=" + action + "&expand=" + Expand + "");
            });
            $(".gridoptions-anchor").click(function (e) {
                var $this = $(this);
                $this.attr("href", "/home/xx/Index" + "/?columnchooser=1");
                var href = $(this).attr("href");
                var action = "";
                if (activeTab.toLowerCase() == "table") {
                    action = "expand";
                }
                else {
                    action = "expandheatmap";
                }

              $this.attr("href", href  + "&from=" +action + "&expand=" + Expand+ "");

            });


texts: Retrieve data from two different rows in a single SQL query?

texts:
I've a table with the following data

and I need to find the number of minutes between two jobs (Say A and C).
The following query works but wondering, if there is a simpler way to achieve the same.
  DECLARE @StartTime datetime
    Declare @EndTime datetime
    set @StartTime = (SELECT start_time from table where jobname = 'A' )
    set @EndTime = (SELECT end_time from table where  jobname = 'C' )
    select datediff(minute,@StartTime, @EndTime) numberOfMinutes


texts: Android LiveData Shared between activities by Application Session

texts:
I'm developing an app that use socket to receive messages from a chat.
I'm using an MVP approach and I store the data in a Singleton class named DataBridge like this:

class myApplication: Application() {

    val dataBridge: DataBridge = DataBridge()
    val deviceManager: DeviceManager = DeviceManager(this)

    override fun onCreate() {
        super.onCreate()
        instance = this

        //init Logger
        TimberImplementation.init()

        //init Maps
        Mapbox.getInstance(this, MAP_ACCESS_TOKEN)
    }

    companion object {
        lateinit var instance: InfiniteApplication
            private set
    }
}

I have the following scenario:

Main Activity: create socket connection and update data in DataBridge class. It has a ViewPagerAdapter with 4 fragments. Each Fragment has it's own Presenter.
Chat Activity: listen changes from DataBridge like onNewMessage (fired by HomeActivity) and display the chat

The question is: is a good practice to share Live Model by Application and make it accessible from presenter of different activities?


texts: Vectorized crosstabulation in Python for two arrays with two categories each

texts:
I have two Python lists, label and presence. I want to do cross-tabulation and get the count for each block out of four, such as A, B, C, and D in the below code.

Both the lists have values True and False.
I have tried Pandas' crosstab function. However, it's slower than my code which is below.
One problem with my code is it's not vectorized and is using a for loop which slows things down.

Could the below function in Python be made any faster?
def cross_tab(label,presence):
    A_token=0
    B_token=0
    C_token=0
    D_token=0
    for i,j in zip(list(label),list(presence)):
        if i==True and j==True:
            A_token+=1
        elif i==False and j==False:
            D_token+=1
        elif i==True and j==False:
            C_token+=1
        elif i==False and j==True:
            B_token+=1
    return A_token,B_token,C_token,D_token

Some sample data and example input and output.
##input
label=[True,True,False,False,False,False,True,False,False,True,True,True,True,False]
presence=[True,False,False,True,False,False,True,True,False,True,False,True,False,False]

##processing
A,B,C,D=cross_tab(label,presence)
print('A:',A,'B:',B,'C:',C,'D:',D)

##Output
A: 4 B: 2 C: 3 D: 5

Edit: Answer provided by Maarten Fabre below is working perfectly. To anyone who will stumble here in future, the logic flow is as follows.
Goal: find a way for vectorization: Below are the solution steps

Analyze and find unique value at each evaluation. This will help save logical output in single array.
By multiplying 2 with any given array and adding resultant array with other array we can get results in single array with unique coded value for each logic.
Get count of the unique element in array and fetch values.
Since calculation can be done in arrays without loop, convert list into np array to allow vectorized implementation.


texts:
mysql> select count(username) from users where no_tweets  > 50;
+-----------------+
| count(username) |
+-----------------+
|          282366 |
+-----------------+
1 row in set (5.41 sec)

mysql> select sum(no_tweets) from users where no_tweets > 50;
+----------------+
| sum(no_tweets) |
+----------------+
|       38569853 |
+----------------+
1 row in set (1.75 sec)

I have that many users, who have collectively tweeted that many tweets. My aim is to store them in a file and then find out what a user generally tweets about (for starters, my aim is to run vanilla LDA and see if it works well on short documents), but the problem is that I ran the python code like an hour back and it has still not finished even 2% of users. I have posted the python code below.

'''
The plan is : Find out all users  from the users database who have more than 50 tweets
Create a file for them in the directory passed as an argument with the same name as the username and write all the tweets in them
'''
def fifty(cursor):
    ''' Find all users and return , all of them having more than 50 tweets'''
    cursor.execute("select username from users where no_tweets>50")
    return cursor.fetchall()

def connect():
    ''' Cursor for mySQLdb'''
    conn = MySQLdb.connect(host="localhost",user="rohit",passwd="passwd",db="Twitter")
    return conn.cursor()

def tweets(cursor,name):
    ''' All tweets by a given user'''
    cursor.execute("select tweets from tweets where username='"+name+"'")
    return cursor.fetchall()
import sys,os,MySQLdb
directory = sys.argv[1] #Directory to write the user files
cursor = connect()
rows = fifty(cursor) #Find all users who have more than 50 tweets

for i in rows:#For all users
    data = open(os.path.join(directory,i[0]),'w') #Open a file same as their name
    allTweets = tweets(cursor,i[0]) #Find all tweets by them
    for j in allTweets:
        data.write(j[0]+"\n") #Write them
    data.close()

The problem is that the code is running too slow and at this rate, it will take more than a day for it to finish writing all files. So some way that would make it faster would be great. So yeah, that is the question.


texts: Semaphore implementation by file locking in a bash script

texts:
This implementation is inspired by the POSIX functions sem_wait() and sem_post(). It tries to get rid of busy loops in the code and appears to work after some simple tests that have been done. But code involving concurrency is hard to get right. Hopefully, there are no race conditions and/or deadlocks in it.

Update 1

semInit() was changed a little bit since the last test. The change had a missing semicolon issue causing syntax error which I have just corrected in this update.

#!/bin/bash

##  Filename: semaphore.bash.inc

##  Blocking other processes by running the function as a
##  process to occupy flock semFile.
lkrRun()
{
    {
        flock -x 5
        while :; do
            sleep 30
        done
    } 5>/tmp/semFile
}

semInit()
{
    local semValArgInit="$1"
    { [ -z "$semValArgInit" ] || [ $semValArgInit -lt 0 ]; } && semValArgInit=0
    echo $semValArgInit >/tmp/semVal
    \rm -f /tmp/lkrPid
    touch /tmp/auxFile
    touch /tmp/semFile
}

semWait()
{
    local semValTmp
    while :; do
        flock -x 5
        [ $(cat /tmp/semVal) -eq 0 ] || {
            semValTmp=$(cat /tmp/semVal)
            let semValTmp--
            echo $semValTmp >/tmp/semVal
            flock -u 5
            break
        }
        { [ -f /tmp/lkrPid ] && kill -0 $(cat /tmp/lkrPid); } || {
            lkrRun &
            echo $! >/tmp/lkrPid
        }
        flock -u 5

        ##  Block point to prevent processes from busying at looping.
        ##  It should still work without it but just become
        ##  inefficient.
        flock -x 6

        flock -u 6
    done 5>/tmp/auxFile 6>/tmp/semFile
}

semPost()
{
    local semValTmp
    {
        flock -x 5
        semValTmp=$(cat /tmp/semVal)
        let semValTmp++
        echo $semValTmp >/tmp/semVal

        ##  Kill the whole locker's process group to relinquish
        ##  flock semFile and resume processes blocked on it.
        [ -f /tmp/lkrPid ] && kill -9 -- -$(cat /tmp/lkrPid)

        \rm -f /tmp/lkrPid
    } 5>/tmp/auxFile
}


texts: Printing integers up to 1000 and are not multiples of 5

texts:
How can I shorten this?

.equ SWI_PrStr, 0x69
.equ SWI_PrInt, 0x6b
.equ StDout, 1
.equ SWI_EXIT, 0x11

.global _start
start:

MOV R5, #1
MOV R6, #1
MOV R7, #1000

LOOPHERE:

CMP R5, R7
BLE LOOPBODY
B LOOPDONE

LOOPBODY:

CMP R6, #5
BLT LOOPIF
MOV R6, #0
B LOOPNEXT

LOOPIF:

MOV R0, #StDout
MOV R1, R5
swi SWI_PrInt

ldr R1, =EOL
swi SWI_PrStr

B LOOPNEXT

LOOPNEXT:

ADD R5, R5, #1
ADD R6, R6, #1
B LOOPHERE

LOOPDONE:
swi SWI_EXIT

.data

EOL: .asciz "\n"
.end


texts:
I am trying to write a function that detects if two strings are anagrams of one another; more specifically, I want the function to be linear in its time complexity (\$O(n)\$ where \$n\$ is the length of the given string(s)).

My approach for doing this is to essentially maintain a dictionary of the characters and their occurrences. For the first string, I increment the key corresponding to a character; for the second string, I decrement the key corresponding to the character. At the end, I check if every key in the dictionary has a value of 0: if so, the number of chars in the first string 'cancel out' those in the second, which means the occurrences are equal and the strings are anagrams. Else, the strings are not anagrams.

Does this function run in linear time? When I iterate through the strings to add to the dictionary, that's linear I think. But does checking every key in the dictionary afterwards take linear time as well? If so, this would be quadratic in its complexity. How would I resolve the issue then, since I think to make this function linear the dictionary must be used but in a smarter way.

  def are_anagrams(s1,s2):
      """Returns True if s1 and s2 are anagrams of one another.
         False otherwise.
         Precondition: s1, s2 are both strings """

    if len(s1) != len(s2): #automatic failure
        return False

    #same length
    d = {}
    index = 0
    bound = len(s1)
    while index < bound: #iterate through each string and its chars
        s1_char = s1[index]
        s2_char = s2[index]

        #update d for s1
        if s1_char not in d:
            d[s1_char] = 1
        elif s1_char in d:
            d[s1_char] += 1

        #update d for s2
        if s2_char not in d:
            d[s2_char] = -1
        elif s2_char in d:
            d[s2_char] -= 1

        index += 1

    for key in d:
      if d[key]: #if d[key] != 0, one string has an additional/fewer
                 #character
          return False
    return True


texts: Queries using multiple tables and ANDs: should that be avoided?

texts:
This is a part of a project I am working on. I need advice and criticism regarding the data base design and general approach to querying the data. I am not at all experienced with relational data bases (as you should notice), and even though I have tried to invest some time in reading up I am currently forced to just move along as fast as possible.

Currently using SQLite3, and most probably sticking with it.

The data base schema goes along the lines of:

-- gene ids and protein names
CREATE TABLE ensemblid (
    geneid TEXT NOT NULL PRIMARY KEY,
    description TEXT, -- not used so far
    name TEXT NOT NULL
);

-- tss id and site and study names
CREATE TABLE tissue_source_site (
    tss TEXT PRIMARY KEY,
    source_site TEXT NOT NULL,
    study_name TEXT NOT NULL,
    bcr TEXT NOT NULL -- not used so far
);

-- sample type id and its human-readable definition
CREATE TABLE sample_type (
    sample_type TEXT PRIMARY KEY,
    definition TEXT NOT NULL,
    short_letter_code TEXT NOT NULL -- not used so far
);

-- analyte id and its human-readable definition
CREATE TABLE portion_analyte (
    analyte TEXT PRIMARY KEY,
    definition TEXT NOT NULL
);

-- tables containing indices into two LARGE data matrices of REALs
-- that are currently **not** in the relational database
CREATE TABLE mrna_rows (
    rowindex INTEGER PRIMARY KEY,
    geneid TEXT NOT NULL
);
CREATE TABLE ampl_rows (
    rowindex INTEGER PRIMARY KEY,
    geneid TEXT NOT NULL
);
CREATE TABLE ampl_cols (
    rowindex INTEGER PRIMARY KEY,
    tss TEXT NOT NULL,
    patient TEXT NOT NULL
);
CREATE TABLE mrna_cols (
    rowindex INTEGER PRIMARY KEY,
    tss TEXT NOT NULL,
    patient TEXT NOT NULL,
    sample_type TEXT NOT NULL,
    vial TEXT NOT NULL,
    portion TEXT NOT NULL,
    analyte TEXT NOT NULL
);

First off, I do realize that I have not put any effort at that moment to ensure data integrity (apart from the obvious PRIMARY KEY and NOT NULL). There are a few foreign keys lurking in there: for example, the tss column in both ampl_cols and mrna_cols is the same tss that is the primary key of the tissue_source_site table. Another issue is that the patient column, in every table it is used, is a unique identifier consistent across all tables. The data, as I have it, contains no further information about "patients", so I have not felt the need to make it a unique column in a table of its own.

After some trial and error, and much unsuccessful mucking around with the different JOINs, I eventually got to the schema above, and the following "style" of querying it:

  Get the names of sites and studies, along with number of patients present in both data sets.

SELECT tissue_source_site.source_site, tissue_source_site.study_name, COUNT(1)
FROM tissue_source_site, ampl_cols, mrna_cols
WHERE ampl_cols.patient == mrna_cols.patient
    AND tissue_source_site.tss == ampl_cols.tss
    AND tissue_source_site.tss == mrna_cols.tss
GROUP BY tissue_source_site.tss;

Which gives me the expected results:

UCSF|Breast invasive carcinoma|8
Walter Reed|Breast invasive carcinoma|65
-- and so on

Is this a valid approach? Is there a point at which I will hit a wall, concerning the length of the queries (endless ANDs) or performance-wise? How about this table.column way of doing everything: I did not really see this used much the tutorials I did (in a hurry). What are the drawbacks of doing it like that? Is it wiser to figure out how JOIN works? Or WITH table AS? Or something else I am totally unaware of?


texts:
This header implements a very simple set of C (only) functions for logging.
This is part of a larger collection of utility functions aimed to be used during the development process, meaning that they are intended to provide quick, easy to use solutions that could be replaced in the production code if needed.

To ease with reading the code, I've removed the (rather verbose) comments with the documentation. You can find it in the README.md file here.

Beside the printf()-like functions, there are a couple of functions that may be used for testing and debugging purpose.

I'm very interested in any feedback you may have, especially in the area of usability.

#ifndef UTL_H
#define UTL_H

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <time.h>
#include <ctype.h>

#ifndef UTL_NOLOG

#define logprintf(...)  utl_log_printf(__VA_ARGS__)

#define logclose()      utl_log_close("LOG STOP")
#define logopen(f,m)    utl_log_open(f,m)

#ifndef NDEBUG
#define logcheck(e)     utl_log_check(!!(e),#e,__FILE__,__LINE__)
#define logassert(e)    utl_log_assert(!!(e),#e,__FILE__,__LINE__)
#define logdebug        logprintf
#else
#define logcheck(e)     utl_log_one()
#define logassert(e)    ((void)0)
#define logdebug(...)   ((void)0)
#endif

#define _logprintf(...) ((void)0)
#define _logdebug(...)  ((void)0)
#define _logcheck(...)  utl_log_one()
#define _logassert(...) ((void)0)
#define _logopen(f,m)   ((void)0)
#define _logclose()     ((void)0)

void utl_log_close(char *msg);
void utl_log_open(char *fname, char *mode);
int  utl_log_check(int res, char *test, char *file, int line);
void utl_log_assert(int res, char *test, char *file, int line);
void utl_log_printf(char *format, ...);
int  utl_log_one(void);

#ifdef UTL_MAIN

static FILE *utl_log_file = NULL;

void utl_log_close(char *msg)
{
  if (msg) logprintf(msg);
  if (utl_log_file && utl_log_file != stderr) fclose(utl_log_file);
  utl_log_file = NULL;
}

void utl_log_open(char *fname, char *mode)
{
  char md[2];
  md[0] = (mode && *mode == 'w')? 'w' : 'a'; md[1] = '\0';
  utl_log_close(NULL);
  utl_log_file = fopen(fname,md);
  logprintf("LOG START");
}

void utl_log_printf(char *format, ...)
{
  va_list  args;
  char     log_tstr[32];
  time_t   log_time;

  if (!utl_log_file) utl_log_file = stderr;
  time(&log_time);
  strftime(log_tstr,32,"%Y-%m-%d %X",localtime(&log_time));
  fprintf(utl_log_file,"%s ",log_tstr);
  va_start(args, format);
  vfprintf(utl_log_file, format, args);
  va_end(args);
  fputc('\n',utl_log_file);
  fflush(utl_log_file);
}

int utl_log_check(int res, char *test, char *file, int line)
{
  logprintf("CHK %s (%s) %s:%d", (res?"PASS":"FAIL"), test, file, line);
  return res;
}

void utl_log_assert(int res, char *test, char *file, int line)
{
  if (!utl_log_check(res,test,file,line)) {
    logprintf("CHK EXITING ON FAIL");
    logclose();
    exit(1);
  }
}

int utl_log_one() {return 1;} /* to avoid warnings */

#endif /* UTL_MAIN */
#endif /* UTL_NOLOG */
#endif /* UTL_H */


texts:
I've written a simple script to refresh the page when the page has been updated.

How it works:

The Javascript polls a PHP script and sends it the current URL and the current version, the PHP script then queries MySQL which returns the true version of the page.

Here is the PHP

if (isset($_GET['URL']) && isset($_GET['CurrentVersion'])) {

$URL = mysqli_real_escape_string($DBConnection, $_GET['URL']);
$CurrentVersion = mysqli_real_escape_string($DBConnection, $_GET['CurrentVersion']);

$Query = "SELECT ID, URL, CurrentVersion FROM PageUpdates WHERE URL = '$URL'";
$Query = $DBConnection->query($Query);

if ($Query->num_rows == 1) {
    $Row = $Query->fetch_assoc();
    if ($Row['CurrentVersion'] > $CurrentVersion) {
        echo "TRUE";
    } else {
        echo "FALSE";
    }
} else {
    echo "FALSE";
}
}

and here is the Javascript

CheckForUpdate();
function CheckForUpdate() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (this.responseText == "TRUE") {
            document.location.reload(true);
        } else {
            setTimeout(function() { CheckForUpdate() }, 50000);
        }
        console.log(this.responseText);
    }
};
xhttp.open("GET", "/IsPageUpdated.php?URL="+ window.location+"&CurrentVersion="+CurrentWebpageVersion, true);
xhttp.send();
}

CurrentWebpageVersion is defined in a script in the HTML so I can set it with PHP.


texts:
I'm currently building a text editor using contenteditable and RoR back end. As the editor is WYSIWYG and trying to follow DRY, I used only one file to 3 actions: Show, Edit and New.

Edit and new will pretty much be the same, however, show won't be editable and won't show the Subtitle if it's empty. I was doing it all through JavaScript, but it didn't feel right to me, so I decided to make it using rails.

This is the final result. 0 Javascript, all rails. It is working now, but it's not DRY. There are lots of repeated conditions.

How can this code be more DRY and human-readable?

%section#text-editor-container
  %article#new-text
    %section#text-header.new-text-container.row{style: ("background: url('#{@text.text_images.last.photo.url}') center center no-repeat transparent; background-size: cover;" unless @text.text_images.empty?)}
      - if (current_page?(edit_text_url(@text)) || current_page?(new_text_url))
        .picture-icon.hidden-xs.col-sm-1.col-md-1.col-lg-1
          = render 'direct_upload', callback: text_cover_url
      %h1#title.col-xs-12.col-sm-11.col-md-11.col-lg-11.placeholdify{class: ('editable' if current_page?(edit_text_url(@text)) || current_page?(new_text_url)), contenteditable: (true if current_page?(edit_text_url(@text)) || current_page?(new_text_url)), data: {placeholder: t(:title)}}= raw(@text.title) unless @text.title.nil?
      - if (((@text.subtitle.nil? || @text.subtitle.empty?) && (current_page?(edit_text_url(@text)) || current_page?(new_text_url))) || !@text.subtitle.empty?)
        %h2#subtitle.col-xs-12.col-sm-11.col-md-11.col-lg-11.placeholdify{class: ('editable' if current_page?(edit_text_url(@text)) || current_page?(new_text_url)), contenteditable: (true if current_page?(edit_text_url(@text)) || current_page?(new_text_url)), data: {placeholder: t(:sub_title)}}= raw(@text.subtitle) unless @text.subtitle.nil?
    %section#text-commands-bar.new-text-container
      -if @text.is_draft
        %span.pull-left= t(:text_still_draft)
      %ul.pull-right.options
        - if (current_page?(new_text_url) || current_page?(edit_text_url(@text)))
          %li.drop_down_menu#menu_categoria.text-center
            = select("text", "category_id", Category.all.collect { |c| [t(c.locale_key.to_sym), c.id]}, {include_blank: t(:select_cat)})
          %li.drop_down_menu#menu_lingua.text-center
            = select("text", "language_id", Language.all.collect { |l| [l.name, l.id] }, {include_blank: t(:select_lan)})
          %li
            %button#publish= t(:publish)
          %li.drop_down_menu#menu_salvar.text-center
            = link_to t(:save_draft), @text, class: 'btn'
        - elsif (!current_page?(new_text_url) && !current_page?(edit_text_url(@text))) && (!@current_user.nil? && @current_user.id == @text.user_id)
          %li
            = link_to '', edit_text_path(@text), class: 'btn icon-editor edit-icon'
          %li
            = link_to '', text_path(@text), method: :delete , data: {confirm: t(:exclusion_confirm)},class: 'btn icon-editor delete-icon'

    %section#text-body.new-text-container
      %p#text.placeholdify{class: ('editable' if current_page?(edit_text_url(@text)) || current_page?(new_text_url)),contenteditable: (true if current_page?(edit_text_url(@text)) || current_page?(new_text_url)), data: {placeholder: t(:new_text)}}= @text.description.html_safe unless @text.description.nil?
= hidden_field_tag 'my_text', @text.id


texts:
I have the below class which moves the AI towards the given plant, this works well however it feels really messy.

Any input as to a better way to lay out the logic would be really grateful, the logic follows the idea that we will take the x and y positions of the AI from the plants position, if the values are positive we add 30 and if it is negative we take away 30

If you need any more explaining of the logic let me know.

private void movePosistion(Plant p) {
        /*
         * set which direction to move,the number generated relates to the
         * direction as below:
         *      1   2   3
         *      4       5
         *      6   7   8
         */
        int xdiff = p.getXpos() - xpos;
        int ydiff = p.getYpos() - ypos;
        if (xdiff > 0){
            if (ydiff > 0){
                //8
                xpos += 30;
                ypos += 30;
            }else if(ydiff < 0){
                //3
                xpos += 30;
                ypos -= 30;
            }else{
                //5
                xpos += 30;
            }
        }else if(xdiff < 0){
            if (xdiff > 0){
                //6
                xpos -= 30;
                ypos += 30;
            }else if(xdiff < 0){
                //1
                xpos -= 30;
                ypos -= 30;
            }else{
                //4
                xpos -= 30;
            }
        }else{
            if (ydiff < 0){
                //7
                ypos -= 30;
            }else{
                //2
                ypos += 30;
            }
        }

        if (xpos > 720)
            xpos = 1;
        if (ypos > 720)
            ypos = 1;
        if (xpos < 1)
            xpos = 720;
        if (ypos < 1)
            ypos = 720;
    }


texts: Replace values in R data frame according to values in other data frame

texts:
I would like to change row names values from a first data frame if these rows names are present in another data frame, and change it to a corresponding value (defined in the second data frame). I could do it with a for loop, but I wonder what would be some other more suitable ways to do it in R.

Here is a toy dataset (my real dataset has 10^5 rows):

df <- data.frame("sample_1" = rep(0,3), "sample_2" = rep(0,3), row.names = paste0('gene_', seq(1, 3)), stringsAsFactors = FALSE)
annotation <- data.frame("gene" =  paste0('gene_', seq(1, 2)), 'name' = paste0('name_', seq(1, 2)), stringsAsFactors = FALSE)
df$gene <- rownames(df)

Initial data frames:

df
       sample_1 sample_2   gene
gene_1        0        0 gene_1
gene_2        0        0 gene_2
gene_3        0        0 gene_3

annotation
    gene   name
1 gene_1 name_1
2 gene_2 name_2

Solution found:

for (x in rownames(df)){
  if (x %in% annotation$gene){
    df[x,]$gene <- annotation$name[which(annotation$gene == x)]
  }
}
rownames(df) <- df$gene
df$gene <- NULL

Resulting data frame:

df
       sample_1 sample_2
name_1        0        0
name_2        0        0
gene_3        0        0


texts: Moving elements satisfying a predicate from one container to another

texts:
I've implemented a C++ algorithm that moves elements satisfying a given unary predicate from one container into the other, deleting them from the input container.

This is my implementation:

/**
 * Moves all elements in the input container
 * that satisfy the given predicate
 * into the output container,
 * and erases them from the input container.
 * @tparam Container The container type.
 * @tparam UnaryPredicate The predicate type.
 * @param in The input container.
 * @param out The output container.
 * @param predicate The predicate to satisfy.
 */
template <class Container, class UnaryPredicate>
void move_and_erase_if(Container &in, Container &out, UnaryPredicate predicate) {
    // sort the input container so that all elements that
    // satisfy the predicate are moved to the end.
    std::sort(in.begin(), in.end(), [=](auto &a, auto &b){
        return !predicate(a) && predicate(b);
    });

    // find the first element in the sorted container
    // that satisfies the predicate.
    // all elements following that element
    // also satisfy the predicate.
    auto it = std::find_if(in.begin(), in.end(), [=](auto &val) {
        return predicate(val);
    });

    // move the elements satisfying the predicate
    // into the output container.
    std::move(it, in.end(), std::back_inserter(out));

    // erase the elements satisfying the predicate
    // from the input container.
    in.erase(it, in.end());
}

Is there a more efficient way to achieve this? Specifically, the call to std::find_if bugs me, as it applies the predicate to all elements a second time, until it finds the first one that satisfies it.

I've written an example application using the algorithm on ideone.


texts: UIButton Subclass - Overriding getters to return placeholder/default values

texts:
I'm in the process of converting a custom UIButton from Objective-C to Swift which has custom properties and default values for those properties:

MyButton.h

@interface MyButton : UIButton

@property (nonatomic, strong) IBInspectable UIColor *buttonColor;
@property (nonatomic, strong) IBInspectable UIColor *buttonSelectedColor;

// ...

@end

MyButton.m

@implementation MyButton

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self adjustButtonColor];
    }

    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self adjustButtonColor];
    }

    return self;
}

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];

    [self adjustButtonColor];
}

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];

    [self adjustButtonColor];
}

- (void)adjustButtonColor
{
    if (self.selected || self.highlighted) {
        self.backgroundColor = [self buttonSelectedColor];
    } else {
        self.backgroundColor = [self buttonColor];
    }
}

#pragma mark - Default colors

- (UIColor *)buttonColor
{
    if (!_buttonColor) {
        _buttonColor = [UIColor grayColor];
    }
    return _buttonColor;
}

- (UIColor *)buttonSelectedColor
{
    if (!_buttonSelectedColor) {
        _buttonSelectedColor = [self.buttonColor colorWithAlphaComponent:.5];
    }
    return _buttonSelectedColor;
}

#pragma mark - Public

- (void)setButtonColor:(UIColor *)buttonColor
{
    _buttonColor = buttonColor;

    [self updateButton];
}

@end

I have attempted to replicate this pattern in Swift with public vars which return a default value, or access a private optional variable which is returned if it exists.  I have also overridden the selected and highlighted properties, updating the button colors in didSet:

class MyButton: UIButton {

    private var _buttonColor: UIColor?
    var buttonColor: UIColor {
        get {
            if let color = _buttonColor { return color }
            return UIColor.grayColor()
        } set {
            _buttonColor = newValue
        }
    }

    private var _buttonSelectedColor: UIColor?
    var buttonSelectedColor: UIColor {
        get {
            if let selectedColor = _buttonSelectedColor { return selectedColor }
            return self.buttonColor.colorWithAlphaComponent(0.5)
        } set {
            _buttonSelectedColor = newValue
        }
    }

    override var selected: Bool {
        didSet {
            adjustButtonColor()
        }
    }

    override var highlighted: Bool {
        didSet {
            adjustButtonColor()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        adjustButtonColor()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        adjustButtonColor()
    }

    func adjustButtonColor() {
        if selected || highlighted {
            backgroundColor = buttonSelectedColor
        } else {
            backgroundColor = buttonColor
        }
    }
}

A few questions:

Is this an appropriate use of private variables?  Is there any way to accomplish the behavior I want with a single variable rather a second optional settable variable for each color?
Is overriding UIButton properties to call adjustButtonColor in didSet abuse of the getter/setter?
If initWithCoder is a failable initializer do I need to check if self is nil before calling adjustButtonColor()?


texts: Flask route to pull data from database for getJSON to process

texts:
I am developing a reporting application in Flask where I pull data in a route function from a postgresql database and jsonify the data. On the client side I have some javascript that does a $.getJSON on the route to request the data.

Here is what the code looks like.

Flask route

def get_db():
    if not hasattr(g, 'postgres_db'):
        g.postgres_db = connect_db()
    return g.postgres_db

@main.route('/Q5')
@login_required
def failed_access():
    failed_query = """select * from prototype.Q5"""
    db = get_db()
    with db.cursor(cursor_factory=RealDictCursor) as cur:
        cur.execute(failed_query)
        results = cur.fetch_all()
     data = json.dumps(results, indent=2, default=date_handler)
     return data

Client side javascript looks like this:

$.getJSON('/Q5', function genChart() { blah() }));

Everything works fine but I want to make sure that there is something I am not missing or could be doing a better way.


texts: Extracting all the data from a table out of a javascript encrypted website

texts:
I've written a script to harvest all the data out of a table from a webpage using python in combination with selenium. It takes a while to parse them all. There are seven steps to hurdle to get to the target page. The search criterion for the table is "pump". However, when the table shows up, there is an option button to select "ALL" appearing in the downmost portion. After selecting the "All" from the options, the site then displays the data with full table. This script is able to automate the whole procedure. I tried to make my code faster using explicit wait maintaining the guidelines of selenium. It is doing it's job perfectly now. Here is the working code.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')

driver.find_element_by_id('disclaimer-accept').click()

wait.until(EC.visibility_of_element_located((By.ID, "medicine-name")))
driver.find_element_by_id('medicine-name').send_keys('pump')

wait.until(EC.visibility_of_element_located((By.ID, "medicines-header-text")))
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()

wait.until(EC.visibility_of_element_located((By.ID, "ctl00_body_MedicineSummaryControl_cmbPageSelection")))
driver.find_element_by_id("ctl00_body_MedicineSummaryControl_cmbPageSelection").click()
driver.find_element_by_xpath('//option[@value="all"]').click()

wait.until(EC.visibility_of_element_located((By.ID, "ctl00_body_MedicineSummaryControl_grdSummary")))
tab_data = driver.find_element_by_id("ctl00_body_MedicineSummaryControl_grdSummary")

list_rows = []
for items in tab_data.find_elements_by_xpath('.//tr'):
    list_cells = []
    for item in items.find_elements_by_xpath('.//td[@class="row-odd"]|.//td'):
        list_cells.append(item.text)
    list_rows.append(list_cells)
for data in list_rows:
    print(data)

driver.quit()


texts:
I have a text file and I was curious about what character appears how often in the text.

Any review is appreciated.

public class CountLetters {
    public static void main(String[] args) throws Exception {
        TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
        File file = new File("C:/text.txt");
        Scanner scanner = new Scanner(file,"utf-8");
        while (scanner.hasNext()) {
            char[] chars = scanner.nextLine().toLowerCase().toCharArray();
            for (Character c : chars) {
                if(!Character.isLetter(c)){
                    continue;
                }
                else if (hashMap.containsKey(c)) {
                    hashMap.put(c, hashMap.get(c) + 1);
                } else {
                    hashMap.put(c, 1);
                }
            }
        }
        for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

The output will be for example:

a: 1202
b: 311
c: 603
d: 510
e: 2125
f: 373
g: 362
h: 718
i: 1313
j: 5
k: 74
l: 678
m: 332
n: 1129
o: 1173
p: 348
q: 40
r: 812
s: 1304
t: 1893
u: 415
v: 195
w: 314
x: 86
y: 209
z: 9


texts:
I am writing some Java code and am coming across a try/catch block in which I decided to verify the value is not null before parsing it:

String parsedValue = DEFAULT_VALUE;
try {
  if (myValue != null) {
    parsedValue = parse(myValue);
  }
} catch (ParseException e) {
  log(e);
}

Regarding the code above, my question is, is it better to nest the if loop into the try/catch block or vice-versa?

In other words, is the previous code better or the following:

String parsedValue = DEFAULT_VALUE;
if (myValue != null) {
  try {
    parsedValue = parse(myValue);
  } catch (ParseException e) {
    log(e);
  }
}

EDIT: As @Brythan raised the issue, for simplicity, let's assume here that log is a method in a random logging library, and has the 2 signatures log(Exception) and log(String). Like that we avoid creating an Exception to log a message, it makes the code clearer.

As @h.j.k raised another issue, here myValue could be null, this is no exceptional case, but if myValue has been assigned a value (not null), it should be parseable, and only in that case I expect an Exception to be thrown by parse(String).


texts: Markov chain-based random text generator in Perl

texts:
This is the first thing I've written in Perl besides one-liners. It just generates random text based on a text file. I was inspired by this. Any tips on making this better are welcome. I'd especially like to know if there are more idiomatic ways I could do certain things.

#!/usr/bin/env perl
use strict;
use warnings;
use File::Open qw(fopen);
use Data::Munge;

my $k = shift;                  # k-gram length
my $n = shift;                  # number of iterations
my $file = shift;
my $long_string = slurp fopen $file;

# loop through each k-gram; if no entry exists in %markov_chain,
# initialize it to an empty array. In either case, push the next
# k-gram into the array.

my %markov_chain;               # hash of arrays

for my $i (0 .. (length $long_string) - 1) {
  my $curr = substr $long_string, $i, $k;
  my $next = substr $long_string, $i + 1, $k;
  $markov_chain{$curr} //= [];
  push $markov_chain{$curr}, $next;
}

# Take the first k-gram from the original document. Draw a random
# k-gram from this k-gram's entry in %markov_chain. This will be the
# k-gram for the next iteration. Print the last character of the
# k-gram.

sub rand_elem { $_[rand @_] }

my $seed = substr $long_string, 0, $k;
print $seed;
for my $i (0 .. $n) {
  $seed = rand_elem @{$markov_chain{$seed}};
  print substr $seed, -1;
}


texts: Improved stack implementation using a linked list

texts:
This is a followup to

Simple stack implementation using linked list

Since my original stack implementation has lots of bugs that I did not notice, I thought I would recreate and try to improve it. Please review this version.

Note about pointers: I know using std::unique_ptr is better so we don't need to do manual deletes, but when I tried it here it results in disaster. I think I don't yet know how to really use it. So I did not use it in this code.

template<class T>
struct Node {
    T item;
    Node* next;
    Node(const T& t, Node* link) :item{t}, next{link} { }
};

template<class T>
class Stack {
public:
    Stack() : first{nullptr}, n{0} {}
    int size() const { return n; }
    bool empty() const { return n == 0; }
    Stack(const Stack&);
    Stack(Stack&&);
    Stack& operator=(const Stack&);
    Stack& operator=(Stack&&);
    void push(const T&);
    void pop();
    T peek() const;
    ~Stack() {
        while (!empty()) {
            pop();
        }
    }
private:
    Node<T>* first;
    std::size_t n;
};

template<class T>
Stack<T>::Stack(const Stack& s) :first{nullptr}, n{0}{
    for (auto t = s.first; t != nullptr; t = t->next) {
        push(t->item);
    }
}

template<class T>
Stack<T>& Stack<T>::operator=(const Stack& s) {
    for (auto t = s.first; t != nullptr; t = t->next) {
        push(t->item);
    }
    return *this;
}

template<class T>
Stack<T>::Stack(Stack&& s) :first{s.first}, n{s.n} {
    s.first = nullptr;
    s.n = 0;
}

template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
    first = s.first;
    n = s.n;
    s.first = nullptr;
    s.n = 0;
    return *this;
}

template<class T>
void Stack<T>::push(const T& t) {
    first = new Node<T>{t,first};
    ++n;
}

template<class T>
void Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    Node<T>* oldfirst = first;
    first = first->next;
    delete oldfirst;
    --n;
}

template<class T>
T Stack<T>::peek() const {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    return first->item;
}

How can I make this code better, particularly copy and move?


texts: Android audio recording using AudioRecord and ByteBuffer

texts:
I'm developing an audio recorder app for android using AudioRecord class to have a low level access to audio samples.

mRecordingThread = new Thread(new Runnable() {
    @Override
    public void run() {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
        try {
            FileChannel fileChannel = new FileOutputStream("/foo/bar/temp.wav").getChannel();
            ByteBuffer audioBuffer = ByteBuffer.allocateDirect(mBufferSize).order(ByteOrder.nativeOrder());

            mAudioRecord.startRecording();
            mIsRecording = true;
            while (mIsRecording) {
                int readSize = mAudioRecord.read(audioBuffer, audioBuffer.capacity());
                if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize == AudioRecord.ERROR_BAD_VALUE) {
                    Logger.getInstance().e("Could not read audio data.");
                    break;
                }
                try {
                    audioBuffer.limit(readSize);
                    fileChannel.write(audioBuffer);

                    audioBuffer.rewind(); // set buffer's position to 0.
                    mAudioDataReceiver.onAudioDataReceived(audioBuffer, mConfig.getSampleWidth());

                    audioBuffer.clear(); // set buffer's limit to its capacity, set position to 0.

                } catch (IOException e) {
                    Logger.getInstance().e(e);
                }
            }
            fileChannel.close();

        } catch (IOException e) {
            Logger.getInstance().e(e);
            // ...
        }
    }
});
mRecordingThread.start();

As shown in the above code, i'm writing the samples to a file as well as passing them to another function mAudioDataReceiver.onAudioDataReceived for visualisation (generate waveform, analyse loudness, etc.). I'm using ByteBuffer as container so i can easily convert it to other type (ShortBuffer or FloatBuffer, depending on the given sample width) before processing the samples

public void onAudioDataReceived(ByteBuffer buffer, int sampleWidth) {
    switch (sampleWidth) {
        case 8: // 8-bit = 1 byte per sample
            onAudioDataReceived(buffer);
            break;
        case 16: // 16-bit = 2 bytes per sample
            onAudioDataReceived(buffer.asShortBuffer());
            break;
        case 32: // 32-bit = 4 bytes per sample
            onAudioDataReceived(buffer.asFloatBuffer());
            break;
    }
}

Question: This line is kinda worrying to me:

ByteBuffer audioBuffer = ByteBuffer.allocateDirect(mBufferSize).order(ByteOrder.nativeOrder());

Is it right to set the byte ordering to native order? Will this work with every device?

Also, is there anything wrong in my code that would potentially mess up the quality of the audio?

Sorry if my questions sound silly, i'm relatively new to android/java development/audio processing, so please bear with me. Thanks


texts: Python Turtle - Olympic flag re-creation

texts:
I made a program to draw the Olympic flag in Python using the turtle module. I am able to make a basic version of it but i think that there is still room for improvement!

Quick note: I am new to python and my code may not be of the best quality...

Ideally the outcome should look like this...

As you can see there is this 'overlapping' of the circles in the picture which makes the the circles look rather like rings that are on one another. I cannot implement that in my code. Like i said this is a basic version of it.

My code output:

Compare both pictures and you can see the difference.

Here is my code:

import turtle

def c1():
    t = turtle.Pen()
    t.reset()
    t.up()
    t.goto(-165,0)
    t.down()
    t.width(10)
    t.color("blue")
    t.circle(75)

def c2():
    t = turtle.Pen()
    t.reset()
    t.up()
    t.goto(0,0)
    t.down()
    t.width(10)
    t.color("black")
    t.circle(75)

def c3():
    t = turtle.Pen()
    t.reset()
    t.up()
    t.goto(165,0)
    t.down()
    t.width(10)
    t.color("red")
    t.circle(75)

def c4():
    t = turtle.Pen()
    t.reset()
    t.up()
    t.goto(-82.5,-85)
    t.down()
    t.width(10)
    t.color("yellow")
    t.circle(75)

def c5():
    t = turtle.Pen()
    t.reset()
    t.up()
    t.goto(82.5,-85)
    t.down()
    t.width(10)
    t.color("green")
    t.circle(75)

c1()
c2()
c3()
c4()
c5()

It would be awesome if anyone could provide some advice to improve the program in any way.


texts:
I was given the following instructions

  Using the below HTML, using ONLY CSS, JavaScript or jQuery create the following (see attached gif animation):

This is a cube

This is a triangle

This is a big, green circle

  Rules:

  The HTML cannot be modified in any way
  For the animation portion, please use JavaScript;  however, no 3-rd party jQuery or JavaScript plugins allowed
  Compatibility: IE 9+, FF 4+, Chrome 10+, Safari 5.1+

I fudged the HTML some, especially when it came to making the Circle's text wrap to a second line and stay in the middle of the Circle.

$(document).ready(function() {
 downUp();
 upDown();
 spin();
});

function downUp() {
 $('.downUp').animate({'top': 500}, {
  duration: 1500,
  complete: function() {
   $('.downUp').animate({'top': 0}, {
    duration: 1500,
    complete: downUp
   });
  }
 });
}

function upDown() {
 $('.upDown').animate({'top': 0}, {
  duration: 1500,
  complete: function() {
   $('.upDown').animate({'top': 500}, {
    duration: 1500,
    complete: upDown
   });
  }
 });
}

function spin() {

 var degree = 0, timer;
 rotate();
 function rotate() {
 timer = setTimeout(function() {
  $('.spin').css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
  $('.spin').css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
  $('.spin').css({ '-ms-transform' : 'rotate(' + degree + 'deg)'});
  ++degree; rotate();
  },5);
 }
}
#square {
  position: absolute;
  height: 200px;
  width: 200px;
  background: black;
  /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(black, gray, black);
  /* For Safari 5.1 to 6.0 */
  background: -moz-linear-gradient(black, gray, black);
  /* For Firefox 3.6 to 15 */
  background: linear-gradient(black, gray, black);
  text-align: center;
  line-height: 200px;
  color: white;
}
#triangle {
  position: absolute;
  left: 250px;
  top: 500px;
  width: 0px;
  height: 50px;
  border-style: solid;
  border-width: 0 100px 160px 100px;
  border-color: transparent transparent red transparent;
  white-space: nowrap;
  box-sizing: border-box;
  text-indent: -50px;
  line-height: 250px;
  color: white;
}
#circle {
  position: relative;
  top: 250px;
  left: 500px;
  height: 200px;
  width: 200px;
  background-color: green;
  border-radius: 100px;
  -moz-border-radius: 100px;
  -webkit-border-radius: 100px;
  text-align: center;
  color: white;
  display: table-cell;
  vertical-align: middle;
}

This is a square

This is a triangle

This is a big,

green circle

JSFiddle

I borrowed some code from a StackOverflow answer to make the circle spin, it can be found here

I am sure that the up down code can be found places on the internet as it is super simple.

I am sure that there is something that I could be doing better on the JavaScript side of things within the restrictions I have been given.


texts:
I never really bothered using mod_rewrite to achieve SEO friendly names but I've always admired from a distance because I've never been good at regex.

The below .htaccess file does work, but I'm sketchy about all of it and maybe I've structured it incorrectly, furthermore it looks terrible and I know that I'm doing it wrong.

It's the very last line that has my most concerns, it sends anything other than what is matched in the first lookup to pageLoader.php and then that obviously loads the view.

Any tips, even small things would assist as this is something I want to get my head around.

RewriteEngine On

ReWriteRule ^css/custom.css$ PlugCMS/public/genCSS.php
ReWriteRule ^js/custom.js$ PlugCMS/public/genJS.php

ReWriteRule ^plugcms$ PlugCMS/index.php [NC]

ReWriteRule ^send-mail$ PlugCMS/public/mailhandler.php [NC]
ReWriteRule ^index\.php$ PlugCMS/public/pageLoader.php?slug=/ [NC]

ReWriteRule ^(?=^(?:(?!PlugCMS|css|js|img|robots.txt|sitemap.xml|font|fonts|sandbox|private|output).)*$)([A-Za-z0-9-]+).*$ PlugCMS/public/pageLoader.php?slug=$1 [NC,L]


texts:
I have a word document with 450 pages (and growing) in witch I make a search and replace (linking referencies) after inserting new text. Unfortunately this procedure is very slow.

Have you any suggestions to speed up this search/replace-function? Eg. by defining the range for the funtion to only new added text since last saving the doc (no idea if that would be possible)?

Sub AddLinks_OG()

Dim Rng As Range, SearchString As String, Id As String, PathDatenServer As String, PathArchiv As String, LinkDatenServer As String, LinkArchiv As String

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

Set Rng = ActiveDocument.Range

SearchString = "([A-Z]{2}[0-9]{6})"
PathDatenServer = "\\Srvdat02\OGZ\Geschäft\S3\"
PathArchiv = "\\Srvarc01\OGZ\Geschäft\S3\"

    With Rng.Find
    .MatchWildcards = True
        Do While .Execute(findText:=SearchString, Forward:=False) = True
            Id = Rng.Text
            LinkDatenServer = PathDatenServer & Id & "-O\U.doc"
            LinkArchiv = PathArchiv & Id & "-O\U.doc"

            ' If file exists in local filesystem link to that
            If Dir(LinkDatenServer) <> "" Then
                ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
                    Address:=LinkDatenServer, _
                    SubAddress:="", TextToDisplay:=Rng.Text
                Rng.Collapse wdCollapseStart

            ElseIf Dir(LinkArchiv) <> "" Then
                ' If file exists in archive link to archive
                ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
                    Address:=LinkArchiv, _
                    SubAddress:="", TextToDisplay:=Rng.Text
                Rng.Collapse wdCollapseStart
            End If

        Loop
    End With

End Sub


texts: React container component to fetch paginated data for a stateless table component

texts:
TableContainer.js does the common task of fetching data and passing it to a lower component, Table.js, which is a stateless functional component.

currentPage is stored in redux, I did this just to practice redux.

Question 1

Is this all reasonable?

Question 2

I noticed that the component will re-render when it receives a new currentPage and then re-renders again, once the data is loaded. The first re-render is not necessary as nothing changes before data is actually loaded. Should I just live with this or should I implement shouldComponentUpdate() to check if data has changed. Or is that potentially even more costly than the re-render itself?

Question 3

Is using componentDidUpdate() to check if currentPage has changed and then re-load the data a good way of controlling the load process?

Question 4

Is building the URL this way acceptable?

const pageParam = currentPage ? "?_page=" + currentPage : "";
fetch('https://jsonplaceholder.typicode.com/posts/' + pageParam)

TableContainer.js

import React from 'react';
import PropTypes from 'prop-types';
import Table from "../components/Table";
import Pagination from "../components/Pagination";
import {connect} from "react-redux";
import {changePage} from "../js/actions";

const PAGE_COUNT = 10;

const mapStateToProps = state => {
    return { currentPage: state.currentPage }
};

const mapDispatchToProps = dispatch => {
  return {
    changePage: page => dispatch(changePage(page))
  };
};

class ConnectedTableContainer extends React.Component {
    state = {
        data: [],
        loaded: false,
    };

    handlePageChange = page => {
        if (page < 1 || page > PAGE_COUNT) return;
        this.props.changePage(page);
    };

    loadData = () => {
        this.setState({ loaded: false });
        const { currentPage } = this.props;
        console.log("load data: " + currentPage);
        const pageParam = currentPage ? "?_page=" + currentPage : "";
        fetch('https://jsonplaceholder.typicode.com/posts/' + pageParam)
            .then(response => {
                if (response.status !== 200) {
                    console.log("Unexpected response: " + response.status);
                    return;
                }
                return response.json();
            })
            .then(data => this.setState({
                data: data,
                loaded: true,
            }))
    };

    componentDidMount() {
        this.loadData(this.props.currentPage);

    }

    componentDidUpdate(prevProps) {
       if (prevProps.currentPage != this.props.currentPage) {
            this.loadData();
        }
    }

    render() {
        const { loaded } = this.state;
        const { currentPage } = this.props;
        console.log("render page: " + currentPage);
        return (

                    <Pagination onPageChange={ this.handlePageChange } pageCount={ PAGE_COUNT } currentPage={ currentPage }/>

        )
    }
}

ConnectedTableContainer.propTypes = {
    changePage: PropTypes.func.isRequired,
    currentPage: PropTypes.number.isRequired,
};

ConnectedTableContainer.defaultProps = {
    currentPage: 1,
};

const TableContainer = connect(mapStateToProps, mapDispatchToProps)(ConnectedTableContainer);

export default TableContainer;


texts:
I'm trying to implement a sparse vector (most elements are zero) dot product calculation. My major idea is to represent each sparse vector as a list (which holds only non-zero dimensions), and each element in the list is a 2-dimensional tuple -- where first dimension is index of vector, and 2nd dimension is its related value.

Any comments about my code improvement, bugs, etc. are appreciated. I also welcome any good advice for in general how to best implement dot product for sparse vector using Python.

def dot_product(v1, v2):
    i1 = 0
    i2 = 0
    result = 0.0
    while i1 < len(v1) and i2 < len(v2):
        if v1[i1][0] == v2[i2][0]:
            result += v1[i1][1] * v2[i2][1]
            i1 += 1
            i2 += 1
        elif v1[i1][0] > v2[i2][0]:
            i2 += 1
        else:
            i1 += 1

    return result
if __name__ == "__main__":
    v1 = [(0, 2), (1, 4), (5, 6)] # (2,4,0,0,0,6)
    v2 = [(1,3),(2,4),(5,7)] #(0,3,4,0,0,7)
    print dot_product(v1, v2)


texts: SQL query to select all teachers not in different table

texts:
For homework I had to do the following:

  Give a list of all the teachers that don't have a classroom assigned to them.

It involves the following 2 tables:

Code inside Groups table would be the classroom in this case and TeacherId matches the Id inside Teachers table.

My solution to the problem is the following query:

SELECT Id, FirstName, MiddleName, LastName
FROM Teachers
WHERE Id NOT IN (SELECT TeacherId FROM Groups)

It works perfectly, however, I wonder if there was a better solution using JOINs.

Edit:

I should mention there is a CONSTRAINT on the Groups table:

ALTER TABLE Groups
ADD CONSTRAINT [FK_Groups_Teachers]
FOREIGN KEY (TeacherId)
REFERENCES [Teachers] ([Id])


texts:
Im not a programmer, but somehow like trying to make something, almost like a hobby.
As of now i have made a list of different gameobjects (models) and i need to choose right one from that list. Everything works but i would like to see how someone who undestands what they'r doing could change the choosing part.

So first is my tile that that hold information:

using System;
using UnityEngine;

[Serializable]
public class Tiles {

public string Name;
public Type TileType;
public Vector3 Cordinates;
public GameObject Tile;

public Tiles()
{
    Name = "Unset";
    TileType = Type.Unset;
    Cordinates = new Vector3(0, 0, 0);
    Tile = null;
}

public Tiles(string name, Type type, Vector3 cord, GameObject tile)
{
    Name = name;
    TileType = type;
    Cordinates = cord;
    Tile = tile;
}

public enum Type
{
    Unset,
    Sand,
    Obstacle,
    ObstaclePass
}

}

And my so called Map, it draws it aswell just to be easy. Inside this map there is GetTileType() - it returns that gameobject i am drawing.

using System.Collections.Generic;
using UnityEngine;

public class Map : MonoBehaviour {

public Vector2 MapSize = new Vector2(5,5);
public List<Tiles> MapTile = new List<Tiles>();
//AllTiles holds all the gameobject i'm choosing from
public List<GameObject> AllTiles = new List<GameObject>();

public void GenerateMap()
{
    for (int x = 0; x < MapSize.x; x++)
    {
        for (int z = 0; z < MapSize.y; z++)
        {
            //just so i could test if it draws different gameobject
            if (x == 2 && z == 2)
            {
                MapTile.Add(new Tiles("Obstacle", Tiles.Type.Obstacle, new Vector3(x, 0, z), GetTileType(Tiles.Type.Obstacle)));
            }
            else
            {
                MapTile.Add(new Tiles("Unset", Tiles.Type.Unset, new Vector3(x, 0, z), GetTileType(Tiles.Type.Unset)));
            }
        }
    }
}

//This is my question
public GameObject GetTileType(Tiles.Type type)
{
    switch (type)
    {
        case Tiles.Type.Unset:
            return AllTiles[0];
        case Tiles.Type.Obstacle:
            return AllTiles[1];
        case Tiles.Type.ObstaclePass:
            return AllTiles[2];
        default:
            break;
    }
    return AllTiles[0];
}

public void DrawMap()
{
    for (int i = 0; i < MapTile.Count; i++)
    {
        Instantiate(MapTile[i].Tile, MapTile[i].Cordinates, Quaternion.Euler(90, 0, 0), transform);
    }
}

private void Start()
{
    GenerateMap();
    DrawMap();
}
}

I really could make it either with switch or if statment. Switch looks better for me so i stick with it, but somehow i think there should be better and cleaner way. Or should i choose the tile in Tiles class? So what are other options of doing this? Or something that really should be changed in this code. (not really trying to make anything here, just try something few times a week)


texts: Binary search on string in alphabetical order

texts:
The code for a binary search on an ordered string by alphabetical orders seems to work.  I am wondering if there is a better way to write this.

function binary_search(arr, letter){
    var first = 0;
    var middle = Math.floor(arr.length/2);
    var last = arr.length -1;

    while(true){
        var test = arr[last];
        if(arr[middle] === letter){
            return true
        }else if(arr[first] >= letter && letter < arr[middle]){
            last = middle -1;
            middle = Math.floor((first + last)/2);
        }else if (arr[middle] < letter && letter <= arr[last]){
            first = middle +1;
            middle = Math.floor((first + last)/2);
        }else {
            return false;
        }
    }
}

var str ="abcdefg"
console.log(binary_search(str, "g"));
console.log(binary_search(str, "a"));
console.log(binary_search(str, "e"));
console.log(binary_search(str, "z"));


texts:
I've written an interrupted bubble sort, which prints the intermediate result after some specified number of iterations of bubble sort. But I seem to have an speed issue. Could anyone help me spot some places that need to be optimized or are just plain wrong?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;
using std::stoi;
using std::stringstream;

template<typename T>
void printVector(vector<T> vect) {
    for(int i = 0; i < vect.size(); i++) {
        if(i == 0) {
            cout << vect[i];
        } else {
            cout << " " << vect[i];
        }
    }
    cout << endl;
}

template<typename T>
void swap(T &elementOne, T &elementTwo) {
    T temp = elementOne;
    elementOne = elementTwo;
    elementTwo = temp;
}

void bubbleSort(vector<int> numbers, long int iterations) {
    for(int i = 0; i < iterations; i++) {
        for(int j = 0; j < numbers.size(); j++) {
            if(numbers[j] > numbers[j + 1]) {
                swap(numbers[j], numbers[j + 1]);
            }
        }
    }
    printVector(numbers);
}

void parse(string line) {
    size_t delimiterPos = line.find("|");
    long int iterations = stol(line.substr(delimiterPos + 1));
    string numbersString = line.substr(0, delimiterPos - 1);

    stringstream numbersSS(numbersString);
    vector<int> numbers;
    int tempNum;
    while(numbersSS >> tempNum) {
        numbers.push_back(tempNum);
    }
    bubbleSort(numbers, iterations);
}

int main(int argc, const char * argv[]) {
    ifstream file(argv[1]);
    string line;
    while(getline(file, line)) {
        parse(line);
    }
    return 0;
}


texts: Refactoring same loop logic with different input data

texts:
I have these two methods:

public static String buildLine(String[] values) {
    StringBuilder lineBuilder = new StringBuilder();
    for (int i = 0; i < values.length - 1; i++) {
        lineBuilder.append(values[i]).append(SEPARATOR);
    }
    lineBuilder.append(values[values.length - 1]);
    return lineBuilder.toString();
}

public static String buildLineFromNodeWorker(String[] values, NodeDecorator nodeWorker) {
    StringBuilder lineBuilder = new StringBuilder();
    for (int i = 0; i < values.length - 1; i++) {
        lineBuilder.append(
                nodeWorker.getItemValueFromAttribute(values[i]))
                .append(SEPARATOR);
    }
    lineBuilder
            .append(nodeWorker
                    .getItemValueFromAttribute(values[values.length - 1]));
    return lineBuilder.toString();
}

they're identical except for what I'm passing to the append method from the StringBuilder.

I'm not able to find a way to write the "business logic" of the loop just once.


texts:
I am looking for some different approaches to this following OOP scenario.

 Dim pb As Object = Nothing

 If radCars.Checked = True Then

     Dim productBase As ProductsBase(Of CarColumns)
     productBase = New Cars(fileLocation)

     pb = productBase

  ElseIf radTrucks.Checked = True Then

     Dim productBase As ProductsBase(Of TruckColumns)
     productBase = New Truck(fileLocation)

     pb = productBase

  End If

  pb.Parse()
  pb.AddRows()
  ....

Having to declare the object above and losing intelisense seems off.  The base class if using generics because the Truck and Car classes use different column classes for the parsing and adding of columns in the db.

Base Class:

Public MustInherit Class ProductsBase(Of T)

    Sub New(filePathString As String)
        FilePath = filePathString
    End Sub

    MustOverride Sub Parse()
    MustOverride Sub DeleteRows()
    MustOverride Sub AddRows(ByVal rows As IEnumerable(Of T), pageNumber As Integer)

    Property ParseResult As ProductLookupContainer(Of T)

End Class

Car Class:

Public Class Cars
    Inherits ProductsBase(Of CarColumns)

    Sub New(filePath As String)
        MyBase.New(filePath)
    End Sub

    Public Overrides Sub AddRows(rows As IEnumerable(Of CarColumns), pageNumber As Integer)
        DatabaseHelper.AddItemsToDB(Of CarProduct)(ConnectionString, rows, pageNumber)
    End Sub

    Public Overrides Sub DeleteRows()
        DatabaseHelper.DeleteRows(ConnectionString, "CarProducts")
    End Sub

    Public Overrides Sub Parse()

        Dim pf As New ParseFile(FilePath)
        Dim result = New ProductLookupContainer(Of CarColumns)
        result = pf.ParseCars

       'Set object
       ParseResult = result

    End Sub

End Class