texts: Initialize a gitlab project both locally and remotely with a single command

texts:
This shell script, with only a few configurations, has the goal of initializing a project on Gitlab.com without having to go through the go through the website's ui.
This means: Let's say you just a project with a few source files, but you haven't done anything with git yet. The goal of this script is to allow you to write something like git-init-remote <my_repository_name> on the command line and have both the project on your personal gitlab.com and the local git repository.
#!/bin/sh

repo=$1
token=<YOUR-PRIVATE-TOKEN> # You get this from https://gitlab.com/-/profile/personal_access_tokens
username=<YOUR-USERNAME>

test -z $repo && echo "Repo name required." 1>&2 && exit 1

curl --request POST --header "Private-Token: $token" --header "Content-Type: application/json" --data "{\"name\":\"$repo\"}" "https://gitlab.com/api/v4/projects"

echo "\nDone initializing on remote."
echo "\nCreating local git repository..."

git init
git remote add origin https://gitlab.com/$username/$repo.git
git add .
git commit -m "Initial commit"
git push -u origin master

echo "\nDone."

I would like to have any of your thoughts on how this can break and how scalable this can go. I had trouble finding similar scripts on the web so I felt like a had to write here.


texts: stable producer/consumer threads in python

texts:
I have implemented a producer/consumer functionality using threads in a given framework and
I'm pretty sure I did not cover all possible scenarios.
I made a small reproducible version. Lines ending with # simulate the functionality of the framework.
In the original code the total number of products and consumers is not known until the end.
My goal is to wait in the producer thread until the consumer thread has finished the current product and vice versa. So the order should be:

consumer boot (first or 2nd step)
producer produce product #1 (first or 2nd step)
consumer consume product #1
producer produce product #2
consumer consume product #2
...
until there is either no product or consumer left

This is a MRE of my code (with sleeps as placeholders), alter the value of n to simulate more or less consumers:
import threading
import time

products = [1,2,3,4,5,None]               #
prodcnt = 0                               #
n = 5                                     #

def produce():
    #simulating incremental calculation of product
    while True:                           #
        global prodcnt                    #
        product = products[prodcnt]       #
        prodcnt += 1                      #

        print("  Producer: init product "+str(product))
        if product == None:               #
            global exhausted
            exhausted = True
            getProdEvent.set()
            print("  Producer: exhausted")
            return
        elif noConsumers:
            print("  Producer: no consumers left")
            return
        else:
            print("  Producer: waiting for permission to process "+str(product))
            getConsumeEvent.wait()
            print("  Producer: Permission granted "+str(product))
            time.sleep(0.01)
        print("  Producer: finished producing "+str(product))
        getProdEvent.set()
        getConsumeEvent.clear()

exhausted = False
noConsumers = False
step = 0

getProdEvent = threading.Event()
getConsumeEvent = threading.Event()

x = threading.Thread(target=produce)    #
x.start()                               #

while not exhausted and not noConsumers:
    if step > 0:
        print("Consumer: wait for product #" +str(step)+"\n", end="")
        getProdEvent.clear()
        if not exhausted:
            getProdEvent.wait()
    else:
        print("Consumer: booting ... please wait")
        time.sleep(0.02)
    print("Consumer: finishing #"+str(step))
    time.sleep(0.05)

    getConsumeEvent.set()
    if step >= n:                       # simulate no Consumers left
        print("Consumer: No consumers left")
        noConsumers = True
        getConsumeEvent.set()
    step +=1

Is there a more straight forward way to force them to wait for each other? Also I feel like my code could break easily.
The producer uses the value of step so the command step +=1 should run only if the producer is stuck in the line getConsumeEvent.wait()


texts:
For my CS minor I was assigned to implement the Quicksort algorithm in C#. I gave it a go and found that I like the implementation of the algorithm more than Mergesort. Now that I've got my Quicksort implementation running, I'm very curious about what optimizations could be done.

using System.Collections.Generic;

namespace Assignment
{
    public class QuickSort
    {
        public void Sort(List<int> list)
        {
            if (list.Count <= 1)
            {
                return;
            }

            int pivot = MedianOfThree(list);
            int equalElementCount = 0;

            List<int> smaller = new List<int>();
            List<int> bigger = new List<int>();

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == pivot)
                {
                    equalElementCount++;
                }
                else if (list[i] < pivot)
                {
                    smaller.Add(list[i]);
                }
                else
                {
                    bigger.Add(list[i]);
                }
            }

            Sort(smaller);
            Sort(bigger);

            int pointer = 0;
            for (int i = 0; i < smaller.Count; i++)
            {
                list[pointer++] = smaller[i];
            }
            for (int i = 0; i < equalElementCount; i++)
            {
                list[pointer++] = pivot;
            }
            for (int i = 0; i < bigger.Count; i++)
            {
                list[pointer++] = bigger[i];
            }
        }

        private int MedianOfThree(List<int> list)
        {
            int firstElement = list[0];
            int middleElement = list[list.Count / 2];
            int lastElement = list[list.Count - 1];

            if ((firstElement > middleElement) != (firstElement > lastElement))
            {
                return firstElement;
            }
            else if ((middleElement > firstElement) != (middleElement > lastElement))
            {
                return middleElement;
            }
            else
            {
                return lastElement;
            }
        }
    }
}


texts: Summing data from two arrays, grouped and sorted by date

texts:
I have multiple multidimensional arrays that each have the same structure with different lengths.

arr1 = [["23 Jan",3],["29 Jan",10],["19 Jan",23],["25 Jan",23]]
arr2 = [["31 Jan",7],["29 Jan",12],["01 Feb",4]]

My result would be a merged array without duplicate dates ordered by the date. For the dates that get combined, like 29 Jan above, I would add the second values together.

Here is what the outcome to the above arrays should be:

arr = [["19 Jan",23],["23 Jan",3],["25 Jan",23],["29 Jan",22],["31 Jan",7],["01 Feb",4]]

As you can see the two with the date, 29 Jan, were combined and added.

Here is my current solution:

(arr1 | arr2).group_by(&:first).
  map { |k, v| [k, v.map(&:last).inject(:+)] }.
  sort_by { |x| x.first.to_date }

Which does indeed get my the correct result, I just want to refactor it. Any suggestions/insights would be appreciated.


texts: Tail-recursive query string builder in F#

texts:
I have a situation where I'm generating a URL based on a set of query string parameters for use in an API. I know ahead of time that the values passed to this function are URL-safe and the tuples are complete, so I don't need to serialize the data or do data validation beyond just checking the length of the array.

This is a function where I'm generating a url from a (string * string)[]. I'm trying to avoid using mutable values, so this uses a tail-recursive function to build the string, with the URL being the "accumulator" value for the tail-recursion.

What I'm looking for is ways to better organize the function, flaws in the logic of the workflow, ways to make the function more readable, and just improvements in general.

let ComposeUrl (valuePairs:(string * string)[]) =
    let Composer (valuePairs:(string * string)[]) =
        let rec ComposerRec (valuePairs:(string * string)[]) (url:string) =
            match valuePairs.Length > 0 with
            | false -> url
            | true  ->
                let tail = valuePairs.[1..valuePairs.Length - 1]
                let url = url + sprintf "&%s=%s" (fst valuePairs.[0]) (snd valuePairs.[0])
                ComposerRec tail url

        let tail = valuePairs.[1..valuePairs.Length - 1]
        let url = sprintf "?%s=%s" (fst valuePairs.[0]) (snd valuePairs.[0])
        ComposerRec tail url

    match valuePairs.Length > 0 with
    | false -> ""                     // No query string parameters
    | true  -> Composer valuePairs


texts:
Mostly asking for critiques of vulnerability. Am I using any functions or methods that are unsafe?

<?php
$menu = array( "page1","page2","page3" );
$defpage = "page1";

$section = $defpage;
if ( isset( $_GET['section'] ) ) $section = $_GET['section'];
if ( !in_array( $section, $menu ) ) $section = $defpage;
?>

This is code that checks if the section is in the array and then sets it as such, but hardwires it back to default if it's not valid.


texts: Refactoring Event Handlers - How to go about this for growing WinForms application

texts:
I have a class with approximately 140 menu buttons in a nested ribbon-style menu over a canvas type area within a WinForms application.

As a result of this, a large swathe of my codebehind file consists of 140 event handlers for click events.

Many of them however, are remarkable similar, for example:

    private void btnFinancialStatusReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new FinancialStatusReport());
    }

    private void btnMonthlySalesReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new MonthlySalesReport());
    }

    private void btnDailySalesReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new DailySalesReport());
    }

SwitchCurrentControl is a private method with the responsibility of essentially taking the newly constructed UserControl and docking it correctly into the active canvas. This is irrelevant to the question but I thought somebody might ask...

The Question

For this many buttons, (140+) a good 50% of them are practically the same, the only difference being in which Control they create.

Is this acceptable, or is there a way I can refactor this to reduce the amount of handlers?

Note

Before anybody suggests I switch to WPF btw, that is not an option...unless that same person wants to come and redo all 140 associated controls for me ;-)


texts:
I'm writing a validator function that receives a byte[] and checks whether it represents a valid UTF-8 byte sequence, according to this table.

Is my approach correct?  So far it has worked fine with my tests, but I'm worried that I might be missing some edge case, or that the way I'm handling bytes is off.

And more importantly, how can I improve the conditions using bit-twiddling? I'm a bit rusty here, and I think that a comparison such as this:

if ((b & 0xFF) >> 1 == (byte) 0b1111110)

can be expressed in a simpler, more idiomatic way.

public static boolean validate(byte[] bytes) {

    int length = bytes.length;

    if (length < 1 || length > 6)
        return false;

    byte b = bytes[0];

    if (length == 1)
        return (b & (1 << 7)) == 0;

    int n;

    if ((b & 0xFF) >> 1 == (byte) 0b1111110)
        n = 5;
    else if ((b & 0xFF) >> 2 == (byte) 0b111110)
        n = 4;
    else if ((b & 0xFF) >> 3 == (byte) 0b11110)
        n = 3;
    else if ((b & 0xFF) >> 4 == (byte) 0b1110)
        n = 2;
    else if ((b & 0xFF) >> 5 == (byte) 0b110)
        n = 1;
    else
        return false;

    if (length-1 != n)
        return false;

    for (int i = 1; i < length; i++)
        if ((bytes[i] & 0xFF) >> 6 != (byte) 0b10)
            return false;

    return true;

}

And these are some tests to try it out:

byte[] bytes1 = {(byte) 0b11001111, (byte) 0b10111111};
System.out.println(validate(bytes1)); // true

byte[] bytes2 = {(byte) 0b11101111, (byte) 0b10101010, (byte) 0b10111111};
System.out.println(validate(bytes2)); // true

byte[] bytes3 = {(byte) 0b10001111, (byte) 0b10111111};
System.out.println(validate(bytes3)); // false

byte[] bytes4 = {(byte) 0b11101111, (byte) 0b10101010, (byte) 0b00111111};
System.out.println(validate(bytes4)); // false


texts: Smith-Waterman algorithm for local sequence alignment with affine gap penalties

texts:
The following is a summary from the top of my head so please correct me if I'm wrong. See the Wikipedia article for more.

This is about determining the (score / edit distance of the) most similar substrings of two given strings.

For example, given the two sequences

TGTTACGG and
GGTTGACTA

the optimal (w.r.t. to a certain scoring function) local alignment would be

GTTA-C
GTTGAC

I am using a slightly different way to score introduction and continuation of gaps than in the Wikipedia article. Technically, in addition to one scoring matrix / edit graph, you have two more - each accounting for gaps in one of the input words.

Given two input words a = a1 a2, ..., an, b = b1 b2 ... bm, let s_ij denote the score of the optimal local alignment of a1..ai and b1..bj. This then gives the following recurrence:

With rho penalty for introducing a gap; sigma penalty for continuing a gap; and delta a function that assigns a score to two matched characters (e.g. 1 if equal, -1 if unequal). The higher the score the better.

This can be solved using Dynamic Programming.

On the basis of this blog article I wrote the following Haskell code:

import qualified Data.Array as Array
import Data.Array

scoreLocal :: String -> String -> Float
scoreLocal a b = maximum mid
  where (m, n) = (length a, length b)

        -- use input as arrays for fast direct indexing
        v = Array.listArray (1, m) a
        w = Array.listArray (1, n) b

        -- declare scoring fns for each "edit graph level"
        scmid i 0 = 0
        scmid 0 j = 0
        scmid i j = maximum [ 0                                  -- start here ("free" edges from (0,0))
                            ,(mid ! (i-1, j-1)) + δ (v!i) (w!j) -- match or mismatch
                            , low ! (i  , j)                     -- end deletion / gap
                            , upp ! (i  , j)                     -- end insertion / gap
                            ]

        scupp i 0 = 0
        scupp 0 j = 0
        scupp i j = maximum [
                              (upp ! (i, j-1)) - σ          -- cont gap  in v
                            , (mid ! (i, j-1)) - ρ          -- start gap in v
                            ]

        sclow i 0 = 0
        sclow 0 j = 0
        sclow i j = maximum [
                              (low ! (i-1, j)) - σ          -- cont gap  in w
                            , (mid ! (i-1, j)) - ρ          -- start gap in w
                            ]

        -- declare content of "edit graph levels"
        mid = Array.listArray bounds
                [scmid i j | (i, j) <- Array.range bounds]
        low = Array.listArray bounds
                [sclow i j | (i, j) <- Array.range bounds]
        upp = Array.listArray bounds
                [scupp i j | (i, j) <- Array.range bounds]

        bounds = ((0,0), (m,n))

        δ v w |  v == w   =  1  -- match
              | otherwise = -2  -- mismatch

        ρ = 5
        σ = 0.5

Question

I dont have much experience yet with Haskell. Can (parts of this) be written in a nicer way?


texts:
This code simply returns a small section of HTML code and then gets rid of all tags except for break tags.

It seems inefficient because you cannot search and replace with a beautiful soup object as you can with a Python string, so I was forced to switch it back and forth from a beautiful soup object to a string several times so I could use string functions and beautiful soup functions.  It seems that there must be a simpler way to do this without switching back and forth between soup objects and strings.

def whiteScrape(webaddress):
     url = (webaddress)
     ourUrl = opener.open(url).read()

     soup = BeautifulSoup(ourUrl)
     soup = soup.find("div", { "class" : "addy" })
     #below code will delete tags except /br
     soup = str(soup)
     soup = soup.replace('
' , '^')
     soup = BeautifulSoup(soup)
     soup = (soup.get_text())
     soup = str(soup)
     soup=soup.replace('^' , '
')

     return soup

The original HTML is something like:

 blah blah
 blahblah
 blah

The output should be:

blah blah
 blahblah
 blah


texts: Better way to display list of categories

texts:
I need to display a list of category links, like so:

Category 1, Category 2, Category 3

I've got it working already but the code seems pretty repetitive and a bit of a mess, I was wondering if there was a better way of doing it.

This is what I've got so far:

for (var i = 0; i < data['categories'].length; i++) {
    var comma = document.createTextNode(', ');
    var link = document.createElement('a');
        link.setAttribute('href', '#journal__category--' + data['categories'][i]['url_title'] );
        link.setAttribute('class', 'js--page__link');
        link.innerHTML = data['categories'][i]['category_name'];

        document.getElementById('js--journal__categories').appendChild(link);
        if( (i + 1) != data['categories'].length ) {
            document.getElementById('js--journal__categories').appendChild(comma);
        }
}


texts: Count the frequency of items in an array

texts:
The question is:

  Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.

Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.

The part which needs more efficient ways to present:

 for(int i = 0; i < inputSize; i++) {
        if(inputValue[i] == 80) {
            tempCount80++;
        } else if(inputValue[i] == 81) {
            tempCount81++;
        } else if(inputValue[i] == 82) {
            tempCount82++;
        } else if(inputValue[i] == 83) {
            tempCount83++;
        } else if(inputValue[i] == 84) {
            tempCount84++;
        } else if(inputValue[i] == 85) {
            tempCount85++;
        } else {
            cout << "Error Accurs." << endl;
        }
    }

    cout << 80 << "      " << tempCount80 << endl;
    cout << 81 << "      " << tempCount81 << endl;
    cout << 82 << "      " << tempCount82 << endl;
    cout << 83 << "      " << tempCount83 << endl;
    cout << 84 << "      " << tempCount84 << endl;
    cout << 85 << "      " << tempCount85 << endl;

The original code is: -

#include <iostream>
using namespace std;

int main() {
    const int inputSize = 10;
    int inputValue[inputSize];
    int tempCount80 = 0;
    int tempCount81 = 0;
    int tempCount82 = 0;
    int tempCount83 = 0;
    int tempCount84 = 0;
    int tempCount85 = 0;

    for(int i = 0; i < inputSize; i++) {
        int tempValue = 0;
        cout << "Please enter a number between 80 and 85: ";
        cin >> tempValue;

        if(tempValue > 79 && tempValue < 86) {
            inputValue[i] = tempValue;
        } else {
            cout << "The number must be between 80 and 85" << endl;
            do {
                i--;
                break;
            } while(i > 0);
        }
    }

    for(int i = 0; i < inputSize; i++) {
        if(inputValue[i] == 80) {
            tempCount80++;
        } else if(inputValue[i] == 81) {
            tempCount81++;
        } else if(inputValue[i] == 82) {
            tempCount82++;
        } else if(inputValue[i] == 83) {
            tempCount83++;
        } else if(inputValue[i] == 84) {
            tempCount84++;
        } else if(inputValue[i] == 85) {
            tempCount85++;
        } else {
            cout << "Error Accurs." << endl;
        }
    }

    cout << 80 << "      " << tempCount80 << endl;
    cout << 81 << "      " << tempCount81 << endl;
    cout << 82 << "      " << tempCount82 << endl;
    cout << 83 << "      " << tempCount83 << endl;
    cout << 84 << "      " << tempCount84 << endl;
    cout << 85 << "      " << tempCount85 << endl;

    return 0;
}

The output is as expected, but need to find more efficient ways to solve the question.


texts: Date and time of an article in a humanized and localized way

texts:
The goal is displaying the date and time of an article in a humanized and localized way:

Yesterday
13:21

or if the Swedish language parameter is set it will display:

Igår
13:21

And if the date wasn't yesterday or today, it will print the date and 24-hour time. I think I succeeded with everything except handling the timezone:

def datetimeformat_jinja(value, format='%H:%M / %d-%m-%Y', locale='en'):
    now= datetime.now()
    info = None
    if datetime.date(value) == datetime.date(now):
      info= _('Today')
    elif (now - value).days < 2:
      info= _('Yesterday')
    else:
      month = value.month
      if month == 1:
        info = str(value.day)+' '+_('Jan')
      elif month == 2:
        info = str(value.day)+' '+_('Feb')
      elif month == 3:
        info = str(value.day)+' '+_('Mar')
      elif month == 4:
        info = str(value.day)+' '+_('April')
      elif month == 5:
        info = str(value.day)+' '+_('May')
      elif month == 6:
        info = str(value.day)+' '+_('June')
      elif month == 7:
        info = str(value.day)+' '+_('July')
      elif month == 8:
        info = str(value.day)+' '+_('Aug')
      elif month == 9:
        info = str(value.day)+' '+_('Sep')
      elif month == 10:
        info = str(value.day)+' '+_('Oct')
      elif month == 11:
        info = str(value.day)+' '+_('Nov')
      else:
        info = str(value.day)+' '+_('Dec')
    return info+'<br>'+format_time(value, 'H:mm', locale=locale)

The above code localizes and humanizes the output:

Today
3:29

I can also switch languages to, for example, Portuguese:

Hoje
3:29

Where "Hoje" means "today," so the filter appears to work.

Could you please review it or give me a hint on how I can admit my code to also allow time zones? I use babel for localization and Jinja2 for rendering.


texts:
I was making a pong game when I realized (by looking at other people's examples) that my Pong code was very messy and not organized. I would like to ask for assistance.

import java.awt.*;
import java.awt.Component;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;

public class Pong {

  JFrame frame;
  //JButton up;
  //JButton down;
  JTextField controls;
  MyDrawPanel drawPanel;
  int y = 325;
  int edge;
  int bx = 650;
  int by = 325;
  boolean gameOn = true;

  public static void main(String[] args) {
    Pong game = new Pong();
    game.go();
  }

  public void go() {

    frame = new JFrame();
  //  up = new JButton();
    //down = new JButton();
    controls = new JTextField();
    drawPanel = new MyDrawPanel();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(controls);
    controls.requestFocus();
    controls.addKeyListener(new keyListener());
    frame.setTitle("Pong");
    frame.setSize(1366,768);
    frame.getContentPane().setBackground(Color.black);

  /*  up.setText("UP");
    up.setBackground(Color.white);
    up.addActionListener(new upListener());
    down.setText("DOWN");
    down.setBackground(Color.white);
    down.addActionListener(new downListener());

    frame.getContentPane().add(BorderLayout.SOUTH, down);
    frame.getContentPane().add(BorderLayout.NORTH, up); */
    frame.getContentPane().add(drawPanel);

    frame.setVisible(true);

    while(gameOn) {

    }
  }

  class keyListener implements KeyListener {
    public void keyPressed(KeyEvent e) {
    //  int id = e.getID();
      char key = e.getKeyChar();
      //System.out.println("Key Pressed" + " " + key);

      if(key == 'w' && y > 0) {
        y = y-4;
        drawPanel.repaint();
        edge = 0;
      }

      else if(key == 's' && y < 560) {
        y = y+4;
        drawPanel.repaint();
        edge = 0;
      } else {
        if(edge < 3) {
        System.out.println("edge");
        edge++;
       }
      }
    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {

    }
  }

/*  class upListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      System.out.println("left");
      for(int i = 20; i > 0; i--) {
        Timer timer = new Timer(5, this);
      //  timer.setInitialDelay(19000);
        timer.start();
        y--;
        drawPanel.repaint();
      }
    }
  }
  class downListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      System.out.println("right");
      y = y + 10;
      drawPanel.repaint();
    }
  } */
  class MyDrawPanel extends JPanel {

    public void paintComponent(Graphics g) {
      g.setColor(Color.black);
      g.fillRect(0,0,this.getWidth(),this.getHeight());

      g.setColor(Color.white);
      g.fillRect(1300,y,30,150);

      g.setColor(Color.white);
      g.fillOval(bx,by,20,20);
    }
  }
}


texts: SQLite UPDATEs for persons and a subclass

texts:
I am using Java with SQLite and I am wondering if I am in the right track onto writing good code i.e. more or less reusable:

SQL scheme:

CREATE TABLE Pessoa (
  CPF VARCHAR(11)  NOT NULL  ,
  telefone INTEGER    ,
  celular INTEGER    ,
  nome VARCHAR(255)      ,
PRIMARY KEY(CPF));

CREATE TABLE Mecanico (
  Pessoa_CPF VARCHAR(11)  NOT NULL  ,
  apelido INTEGER  NOT NULL    ,
PRIMARY KEY(Pessoa_CPF)  ,
  FOREIGN KEY(Pessoa_CPF)
    REFERENCES Pessoa(CPF)
      ON DELETE NO ACTION
      ON UPDATE NO ACTION);

   final static String UPDATE = "UPDATE ";
      private static void alterarWrapper(String query){
      Connection connection = null;
        try
        {
          // create a database connection
          //connection = DriverManager.getConnection("jdbc:sqlite:4rodas.db");
          connection = DriverManager.getConnection("jdbc:sqlite:C:/dropbox/4rodas.db");
          Statement statement = connection.createStatement();
          statement.setQueryTimeout(30);
          statement.executeUpdate(UPDATE + query);
        }
        catch(SQLException e)
        {
          System.err.println(e.getMessage());
        }
        finally
        {
          try
          {
            if(connection != null)
              connection.close();
          }
          catch(SQLException e)
          {
            System.err.println(e);
          }
        }
      }

      public static void atualizar(Mecanico mecanico){
          String pessoa = "Pessoa SET telefone="+mecanico.getTelefone()+
                  ",celular="+mecanico.getCelular()+",nome='"+mecanico.getNome()+
                  " where CPF='"+mecanico.getCPF()+"';";
          System.out.println(pessoa);
          alterarWrapper(pessoa);
          String apelido = "Mecanico SET apelido='"+mecanico.getApelido()+
                            "' where Pessoa_CPF='"+ mecanico.getCPF()+"';";
          System.out.println(apelido);
          alterarWrapper(apelido);
      }
      public static void atualizar(Pessoa cliente){
          String pessoa = "Pessoa SET telefone="
                  +cliente.getTelefone()+",celular="+cliente.getCelular()+",nome="+cliente.getNome()+" where CPF='"+ cliente.getCPF() +"';";
          alterarWrapper(pessoa);
      }

My doubts are:

About the update methods are they are updating everything but the primary key, because I cannot really see how to implement a way of updating just the necessary.
Is it a good idea to do atualizar(Class class) and then format and use the wrapper?


texts:
I'm rather new to C#, and found relevant subclassing examples surprisingly hard to come by. I've whipped up this class that appears to work, but am pretty sure this is not optimal:

private class ThrottledRestClient
{
    int pause;  // mininum ms between requests
    double rpm;  // max requests per minute
    long last_request_time;
    RestClient client;
    public ThrottledRestClient(string url, HttpBasicAuthenticator auth, double rpm = 60)
    {
        this.client = new RestClient(url);
        this.client.Authenticator = auth;
        this.rpm = rpm;
        this.pause = (int)((60 / rpm) * 1000);
    }

    public IRestResponse Execute(RestRequest request)
    {
        long now = DateTime.Now.Ticks;
        int wait = pause - (int)((now - this.last_request_time) / TimeSpan.TicksPerMillisecond);
        if (wait > 0)
        {
            //Console.WriteLine("Waiting ms: " + wait);
            Thread.Sleep(wait);
        }
        this.last_request_time = DateTime.Now.Ticks;

        return this.client.Execute(request);
    }
}

How could this be better? Is there an existing solution I haven't found?


texts: Get all children recursively in Entity Framework Core

texts:
In Entity Framework Core we can have recursive entities. But we cannot do an "Include" for these recursives (can we?). So I wrote a Get-method that does it for me:

First, this is my RecursiveEntity<T> base-class:

public class Entity : IEntity
{
    [Key]
    public int Id { get; set; }
}

public abstract class RecursiveEntity<TEntity> : Entity, IRecursiveEntity<TEntity>
    where TEntity : RecursiveEntity<TEntity>
{
    public virtual TEntity Parent { get; set; }
    public virtual ICollection<TEntity> Children { get; set; }
}

And this is my Repository-base-class for recurisve entities:

public abstract class RecursiveRepository<T, TDataContext>
    where T : RecursiveEntity<T> where TDataContext : DbContext
{
    protected IEnumerable<T> Get(Expression<Func<T, bool>> expression)
    {
        IQueryable<T> parents = DataContext.Set<T>()
            .Include(x => x.Children)
            .Where(w => w.Parent == null)
            .Where(expression);

        foreach (T entity in parents)
        {
            if (entity.Children != null && entity.Children.Any())
                entity.Children = _getChildren(entity, expression).ToList();

            yield return entity;
        }
    }

    private IEnumerable<T> _getChildren(T parentEntity, Expression<Func<T, bool>> expression)
    {
        IQueryable<T> children = DataContext.Set<T>()
            .Include(x => x.Parent)
            .Where(w => w.Parent != null && w.Parent.Id == parentEntity.Id)
            .Where(expression);

        foreach (T entity in children)
        {
            entity.Children = _getChildren(entity, expression).ToList();
            yield return entity;
        }
    }
}

Any suggestion what I can do better?
Is it a good solution to do that many DataContext<Set>-accesses and assign them  to the parent with ToList()?


texts: Could anyone say if this is a reliable shuffling code?

texts:
I am trying to prove the famous "Monty Hall Paradox":

  The Monty Hall problem is a probability puzzle named after Monty Hall, the original host of the TV show Let’s Make a Deal. It’s a famous paradox that has a solution that is so absurd, most people refuse to believe it’s true.

private static void suffle(ulong numberOfTries)
    {
        int correctHits = 0;
        int wrongHits = 0;

        var prizeIndex = new Random();

        for (ulong i = 1; i <= numberOfTries; i++)
        {
            int[] doors = { 1, 2, 3 };

            var prizeDoor = doors[prizeIndex.Next(0, doors.Length)] ;

            var selectedDoor = doors[prizeIndex.Next(0, doors.Length)];

            int discardedDoor = doors[prizeIndex.Next(0, doors.Length)];

            while (discardedDoor == prizeDoor || discardedDoor == selectedDoor)
            {
                discardedDoor = doors[prizeIndex.Next(0, doors.Length)];
            }

            var correctGuess = selectedDoor == prizeDoor;

            if (correctGuess) correctHits++;
            else wrongHits++;

            Console.WriteLine($"Prize Door: {prizeDoor}\nSelected Door: {selectedDoor}\nDiscarded Door: {discardedDoor}\nRight Guess? {correctGuess}\n\n");
        }

        Console.WriteLine($"Right Guesses: {correctHits} / {numberOfTries}\nWrong Guesses: {wrongHits} / {numberOfTries}");
    }


texts: Pack several file documents into the single archive file in c#

texts:
public byte[] PackToZip(IEnumerable<byte[]> files)
    {
        using (var archiveStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
            {
                foreach (var file in files)
                {
                    var entryName = string.Format("entry name");
                    using (var entryStream = archive.CreateEntry(entryName).Open())
                    {
                        entryStream.Write(file, 0, file.Length);
                    }
                }
            }

            return archiveStream.ToArray();
        }
    }

Is it safe, robust and efficient?


texts: Split dictionary of lists into two dicts based on binary values

texts:
I have a very large dictionary that contains key-value pairs where the key is a string and the value a list. All lists have the same lengths. I want to split up the dataset (dictionary) in two based on the values in one of the lists. One of the lists will contain binary values (i.e. 0 or 1). I want to split up the dictionaries so that one of them contains all those where the binary value is 0 and the other where it is 1.

(It is easier to understand this when you mentally transform the dataset in a table where each index of the lists is a row, and where the dictionary values are column names.)

I guess I could first convert the dict to a Pandas dataframe and then subset the dataframe, and convert the resulting dataframes back to dicts, but I only want to do this if it proves to be faster than doing it with dictionaries only.

The following code works (test it here), but as said I'm not sure about efficiency. I'm only interested in Python >= 3.6

from collections import defaultdict

def split_d(d, key):
  include = defaultdict(list)
  exclude = defaultdict(list)

  for i in range(0, len(d[key])):
    binary = d[key][i]
    for k, v in d.items():
      if k == key:
        continue

      if binary == 0:
        exclude[k].append(v[i])
      elif binary == 1:
        include[k].append(v[i])
      else:
        raise ValueError(f"Key {key} is not binary. Expected values 0 or 1")

  return include, exclude

d = {
  'prof': [1,0,0,1,1,1,1,1,0,1],
  'val': [45,12,36,48,48,59,5,4,32,7]
}

print(split_d(d, 'prof'))


texts:
For my CS class I have to write a HiLo game using multithreading.  I am brand new to multithreading and not sure how to best implement it.  The program below works, but I am wondering if there is a better way to do it.  When it is run the user will input an int, which is the amount of time that they will have to guess the correct number.  If the timer runs out the game will end.  I am not supposed to use the Timer object but instead use the System.currentTimeMillis().

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

class Game implements Runnable {
    private static long time;
    private long timer;
    private static long gameTime;

    public Game(int n){
        gameTime=n;
    }

    public void run() {
        time=System.currentTimeMillis();
        while(true){
            timer=(System.currentTimeMillis()-time)/1000;
            if(timer>=gameTime){
                System.out.println("Oops! Time is up - try again.");
                break;
            }
        }
    }
}

public class Hilo {

    public static void main(String[] args) {
        if (args.length!=1){
            System.err.println("Must enter time");
        }
        Random rand = new Random();
        int max=100;
        int min=1;
        int number=rand.nextInt((max-min)+1)+min;
        int gameTime=Integer.parseInt(args[0]);
        System.out.println("Welcome to HiLo!");
        System.out.println("You have "+gameTime+" seconds to guess a number between 1 and 100.");
        Thread clock1 = new Thread(new Game(gameTime));
        clock1.start();

        while(clock1.isAlive()==true){
            System.out.println(">");
            Scanner sc = new Scanner(System.in);
            int input = sc.nextInt();

            if(clock1.isAlive()==true&&input==number){
                System.out.println("You Win!");
                break;
            }else if(clock1.isAlive()==true&&input<number){
                System.out.println("Higher!");
            }else if(clock1.isAlive()==true&&input>number){
                System.out.println("Lower!");
            }
        }
    }
}


texts: Regex to match each line in a file, with windows and/or linux line break included, even for missing line break at EOF

texts:
My requirement is to match each line of a text file, including the line terminator of each, at most excluding the terminator of the last line, to take into account the crippled, non POSIX-compiant files generated on Windows; each line terminator can be either \n or \r\n.
As a consequence, no character in the file should be left unmatched.
The best regex I could come up with is this:
\n|\r\n|[^\r\n]++(\r\n|\n)?

Is this the best I can write, performance-wise?
Please, if you use the ^/$ anchors or similar, comment about that, because their behavior is dependent on whether the engine considers them as multiline by default.


texts: Express compatible JSON Web Token authentication middleware

texts:
I am writing an Express.js middleware function in a TypeScript NodeJS project that uses a function from a third-party module to perform a small workload. When writing unit tests, I want to mock this third-party function. In the following code, the decodeFunction parameter is what I used as a seam to inject the dependency (or, when writing unit tests, a mock). Here it is:
/**
 * Returns a middleware function that performs authentication using a JSON Web
 * Token (JWT).
 *
 * @remarks
 * This middleware is intended to be used during test mode only and should not
 * be considered secure.
 *
 * @param - decodeFunction - A function that decodes a JWT. *
 * @returns An Express-compatible middleware function that authenticates a JWT.
 */
export function getJwtAuthMiddleware(
    decodeFunction: DecodeFunction = decode
): (req: Request, res: Response, next: NextFunction) => Promise<void> {
    return async (req, res, next) => {
        const { authorization } = req.headers || "";

        if (!authorization) {
            next(new HttpException(401, "An authorization header is required."));
            return;
        }

        const [authType, token] = authorization.trim().split(" ");

        if (authType !== "Bearer") {
            next(new HttpException(401, "The specified authentication scheme is not supported."));
            return;
        }

        try {
            const result = await decodeFunction(token, config.testModeJwtSecret, false, "HS256");
            req.user = { id: result.sub };
            next();
        } catch (error) {
            next(new HttpException(401, "Authorization is required.", error));
        }
    };
}

This seems to work just fine, but I'm relatively inexperienced with TypeScript/JavaScript and would love to hear from the community here as to whether there are alternative approaches I should consider or best practices I've ignored.


texts:
I wrote this program where you can input x amount of words that of length x that checks if the grid formed is the same words vertically as they are horizontally:

F I L E
I C E D
L E A D
E D D Y

The words can be entered in any order and the letters must stay in the same order. i.e. F I L E can't be F E L I

The permutations part of my code is so I can get all permutations of the words to check if they work in a grid

This feels very clunky and I'd like to slim it down. Does anyone have any suggestions?

import sys
import itertools
numWords = int(raw_input('Enter Number of Words: '))
words = []
stuff = []
for i in range(numWords):
    word = raw_input('Enter Word: ')
    if len(word) != numWords:
        print('Not Valid Grid')
        sys.exit()
    words.append(word)

stuff = list(itertools.permutations(words))
for i in range(len(stuff)):
    count = 0
    for j in range(0,4):
        s = ''
        for k in range(0,4):
            if stuff[i][j][k] == stuff[i][k][j]:
                s += stuff[i][k][j]
                if s in stuff[i]:
                    count += 1
    if count == numWords:
        for l in stuff[i]:
            print l
        sys.exit()
print('Not a Valid Grid')


texts:
I designed a "Ticker" based on how I imagine Minecraft's tick system works. My ticker calls a method tickRate times a second and provides a Delta Time value (deltaTime) to the method being called.

The issue I have with my code is that I find the update method (which handles timing) to be ugly but I'm not sure what I can do.

My ticker class is designed to be instantiated and used whenever, it does not have to be used right away (which is why I don't set any time related information in the constructor). This is why there is a check for nextTick and lastTick being 0 inside update, as to ensure that the delta time does not go crazy on the first tick. The issue with this is that it looks a bit ugly, however I'm not sure what I could do. I could move the reset code into the reset method, however that would now mean that the reset method is time dependant, and must be only be called when you intend to use the ticker.

Ticker.java

import java.util.HashSet;
import java.util.Set;

public class Ticker {
    private long lastTick;
    private long nextTick;
    private int tickRate;

    private Set<TickListener> tickListeners = new HashSet<>();

    public Ticker(int tickRate) {
        this.tickRate = tickRate;
    }

    public void addTickListener(TickListener listener) {
        tickListeners.add(listener);
    }

    public void removeTickListener(TickListener listener) {
        tickListeners.remove(listener);
    }

    public void setTickRate(int tickRate) {
        this.tickRate = tickRate;
    }

    public int getTickRate() {
        return tickRate;
    }

    public void reset() {
        lastTick = 0;
        nextTick = 0;
    }

    public boolean update() {
        long currentTime = System.currentTimeMillis();

        if (currentTime >= nextTick) {
            long targetTimeDelta = 1000L / tickRate;

            if (lastTick == 0 || nextTick == 0) {
                lastTick = currentTime - targetTimeDelta;
                nextTick = currentTime;
            }

            float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;

            for (TickListener listener : tickListeners) {
                listener.onTick(deltaTime);
            }

            lastTick = currentTime;
            nextTick = currentTime + targetTimeDelta;

            return true;
        }

        return false;
    }
}

TickListener.java

public interface TickListener {
    void onTick(float deltaTime);
}

Example usage

Ticker ticker = new Ticker(20); // 20 ticks per second

ticker.addTickListener(new TickListener() {

    @Override
    public void onTick(float deltaTime) {
        System.out.println(String.format("Ticked with deltaTime %f", deltaTime));
    }
});

while (true) {
    ticker.update();
}


texts:
A user wrote an issue asking if inside the bio (or any arbitrary tag), any tagged accounts can be automatically linked like on Github.

I gave them this function:

I was going to use string.split(" "), but then I realized that if I did that I would destroy the specific formatting of the text if I used array.join(" ") after all of the formatting changes.

Ex:
Original: "I work for the coolest companies: @aws, @microsoft, and @apple"

Joined: "I work for the coolest companies: @aws , @microsoft , and @apple"

The commas are messed up.

Is there a way to slim it down and/or simplify it?  JS isn't my strongest language.


texts:
I wrote a class that can convert to and fro from Roman Numerals and Decimals. I would appreciate critical points on everything, especially:

Shortening my code.
Choosing a better approach.
Using better/new features of Java 8.

And so on...

I didn't add JavaDoc because I am expecting suggestions for a better approach. I will document it then. Here is the class:

RomanNumeral.java

package library.util;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * A "recreational" class that provides that functionality of converting
 * values to and fro from Roman numerals.
 *
 * @author Subhomoy Haldar
 */
public class RomanNumeral {

    private final String representation;
    private final int value;

    private RomanNumeral(String representation, int value) {
        this.representation = representation;
        this.value = value;
    }

    @Override
    public String toString() {
        return representation;
    }

    public int getValue() {
        return value;
    }

    public static RomanNumeral of(String representation) throws
            NumberFormatException,
            ArithmeticException {
        // Zero wasn't supported then...
        if (representation.isEmpty()) {
            throw new NumberFormatException("Empty String.");
        }
        int value = 0, previous = 0;
        StringBuilder builder = new StringBuilder(representation);
        builder.reverse();  // go in the opposite manner
        for (int i = 0; i < builder.length(); i++) {
            try {
                int current = map.get(String.valueOf(builder.charAt(i)));
                // If the value suddenly drops then subtract, don't add.
                value += current < previous ? -current : current;
                previous = current;
            } catch (NullPointerException e) {
                // A NullPointerException will be thrown only if the
                // character is not present in the map.
                throw new NumberFormatException
                        ("Unrecognised character : " + builder.charAt(i));
            }
        }
        // calling representationOf() makes sure that "IIIII" becomes "V".
        return new RomanNumeral(representationOf(value), value);
    }

    public static RomanNumeral valued(int value) {
        return new RomanNumeral(representationOf(value), value);
    }

    public static String representationOf(int value)
            throws ArithmeticException {
        // The valid range is (0, 5000)
        if (value <= 0 || value >= 5_000) {
            throw new ArithmeticException("Unsupported value : " + value);
        }
        int copy = value;
        StringBuilder builder = new StringBuilder(10);  // 4999 gives 10 chars
        // The descending order is maintained
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            int v = entry.getValue();
            String k = entry.getKey();
            while (copy >= v) {
                copy -= v;
                builder.append(k);
            }
        }
        return builder.toString();
    }

    private static final Map<String, Integer> map;

    static {
        // Using LikedHashMap ensures retention of order.
        Map<String, Integer> temporary = new LinkedHashMap<>(13);
        // Initialize in descending order.
        temporary.put("M", 1_000);
        temporary.put("CM", 900);
        temporary.put("D", 500);
        temporary.put("CD", 400);
        temporary.put("C", 100);
        temporary.put("XC", 90);
        temporary.put("L", 50);
        temporary.put("XL", 40);
        temporary.put("X", 10);
        temporary.put("IX", 9);
        temporary.put("V", 5);
        temporary.put("IV", 4);
        temporary.put("I", 1);
        // Make an unmodifiable map out of it .
        map = Collections.unmodifiableMap(temporary);
    }

}

The algorithm for converting from Roman to Decimal is adapted from this post.


texts:
This is my solution to this LeetCode problem.

Essentially you want to get the next board state for a Minesweeper game. All test cases passed and the submission was accepted on leetcode. The submission on leetcode was I used a depth first search approach (hopefully it is implemented correctly).

I believe the run time for this is \$O(n)\$, where \$n\$ is the number of total squares, and each square is visited at most once, correct? The space complexity I believe is also \$O(n)\$, as I keep track of each visited square in the revealed_squares hash. Also, I wanted to note that the update_board method at the very end is the default method provided by LeetCode for use in the test cases.

class MineSweeper
      attr_accessor :board, :revealed_squares
      def initialize(board)
        @board = board
        @revealed_squares = {}
      end

  def click_pos(pos)
    @overall_count = 0
    return @board if @revealed_squares[pos]
    i = pos[0]
    j = pos[1]
    if @board[i][j] == 'M'
      @board[i][j] = 'X'
      return @board
    end

    self.dfs(pos)
  end

  def get_neighbors(square)
    i = square[0]
    j = square[1]
    top = i - 1 >= 0 ? i - 1 : nil
    bottom = i + 1 < @board.length ? i + 1 : nil
    left = j - 1 >= 0 ? j - 1 : nil
    right = j + 1 < @board[0].length ? j + 1 : nil

    possible_positions = [[top, left], [top, right], [bottom, left], [bottom, right], [top, j], [bottom, j], [i, left], [i,right] ]

    valid_positions = possible_positions.select{|pos| !@revealed_squares[pos] && (pos[0] && pos[1]) }

    valid_positions
  end

  def get_mine_count(pos)
    nbrs = get_neighbors(pos)
    count = 0
    nbrs.each do |sq|
      i = sq[0]
      j = sq[1]
      if @board[i][j] == 'M'
         count += 1
      end
    end

    [count, nbrs]
  end

  def dfs(pos)
    i = pos[0]
    j = pos[1]
    @overall_count += 1
    count_and_nbrs = get_mine_count(pos)
    mine_count = count_and_nbrs[0]
    nbrs = count_and_nbrs[1]
    @revealed_squares[pos] = nbrs
    if mine_count > 0
       @board[i][j] = mine_count
       return @board
    else
       @board[i][j] = 'B'
       nbrs.each do |nbr|
          self.dfs(nbr)
       end
    end

    return @board
  end
end

def update_board(board, click)
  m = MineSweeper.new(board)
  m.click_pos(click)
  m.board
end


texts: Binary search modification for "swaped" array

texts:
I was making an algorithm for a task I found in a book. It says that there is sorted array, that was swapped so it looks like "4567123", and was proposed to use binary search modification.

Below is my solution in java.

The thing is, I'm a bit cringed that I can't process cases for array size of 2, 3 generically (for case of size 1 it's obvious that it'll require a specific case). Not that I need a solution that'll do that generically for 2, 3 array size cases. But I more like to know, is it a problem. Also I addressed a problem when array wasn't swaped at all. And I'm not sure that I should've done this, if preconditions are clearly specified. Btw binary search doesn't check that it's input is sorted.

So, more what I need is not code review itself, but more of advise, is my hardcoded cases and support for nonswaped array is good or bad. I myself believe that cases are fine, as algorithm compares 2 values, and thus requires at least 2 values to be compared, also it searches for the "peak and drop". But I'll probably try to modify it so it won't cover non-swaped array case and generically work for 2, 3 size array.

//file SwapedArraySearch.java\
public class SwapedArraySearch {
    public static int search(int[] arr) {
        switch (arr.length){
            case 1:
                return arr[0];
            case 2:
                return arr[0] > arr[1]?arr[1]:arr[0];
            case 3:
                return arr[0] > arr [1] ? (arr[1] > arr[2]?arr[2]: arr[1]):
                                            (arr[0] > arr[2]?arr[2]: arr[0]);
        }
        int x = arr[0];
        int n = arr.length/2;
        int prevn = arr[n] > x ? arr.length -1 : 1;
        int t;
        while(prevn != n) {
            if (x < arr[n]) {
               if (arr[n] > arr [n + 1] )
                   return arr[n+1];
                t = n;
                n = n + (prevn - n)/2;
                prevn = t;
            } else {
                if (arr[n - 1] > arr[n])
                    return arr[n];
                t = n;
                n = prevn + (n - prevn)/2;
                prevn = t;
            }
        }
        return arr[0] > arr[1] ? arr[arr.length - 1] : arr[0];
    }

    public static void main(String... args) {
        int[] arr = new int[args.length];
        for (int i = 0; i < args.length; i++)
            arr[i] = Integer.valueOf(args[i]);
        System.out.println(search(arr));
    }
}

EDIT: the task is to find the lowest element

EDIT2: after much more thinking I boiled down my search function to this:

x = arr[arr.length - 1]
a = 0
b = arr.length
while b - a > 2
 if x > arr[(a+b)/2]
  b = (a+b)/2
 else
  a = (a+b)/2
return arr[(a+b)/2]

the key point to simplification was to understand that middle element can always be calculated as (a+b)/2.


texts: Doubly linked list reimplemented with smart pointers

texts:
I need some suggestions on my reimplementation of a doubly linked list with smart pointers since I'm new to smart pointers in C++.

I read some docs on smart pointers and found out there are shared_ptr<Obj>, unique_ptr<Obj> and weak_ptr<Obj>. I only use shared_ptr<Obj> in my current code, but I'm not sure how to use unique_ptr<Obj> in my doubly linked list. I would like someone can give me some pointers on how and where to use unique_ptr<Obj> in my DLL.

class Node{
    public:
        int data;
        Node(int data){
            this->data = data;
        }
    public:
        shared_ptr<Node> prev;
        shared_ptr<Node> next;
};

class LinkedList{
    public:
        shared_ptr<Node> head;
        shared_ptr<Node> tail;
    public:
        LinkedList(){}

        void fun(){
            printf("fun()\n");
        }

        void append(shared_ptr<Node> node){
            if(!head){
                head = node;
                tail = head;
            }else{
                tail->next = node;
                node->prev = tail;
                tail = node;
            }
        }

        void print(){
            shared_ptr<Node> curr = head;
            while(curr){
                printf("[%d]\n", curr->data);
                curr = curr->next;
            }
        }
        void remove(shared_ptr<Node> node){
            shared_ptr<Node> curr = head;
            if(node && curr){
                while(curr){
                    if(curr == node){
                        if(curr->prev == nullptr){
                            if(curr->next == nullptr){
                                // [curr]
                                node.reset();
                                head.reset();
                                tail.reset();
                            }else{
                                // [curr]->[]
                                shared_ptr<Node> next = curr->next;
                                curr->next.reset();
                                next->prev.reset();
                                head = next;
                            }
                        }else{
                            if(curr->next == nullptr){
                                // []->[curr]
                                shared_ptr<Node> prev = curr->prev;
                                curr->prev.reset();
                                prev->next.reset();
                                tail = prev;
                            }else{
                                // []->[curr]->[]
                                shared_ptr<Node> next = curr->next;
                                shared_ptr<Node> prev = curr->prev;
                                next->prev = prev;
                                prev->next = next;
                            }
                        }
                    }
                    curr = curr->next;
                }
            }
        }
};


texts: Expanding url from shortened url obtained from tweet

texts:
I have a twitter data set. I have extracted all the expanded urls from the json and now am trying to resolve the shortened ones. Also, I need to check which urls are still working and only keep those.

I am parsing over 5 million urls. The problem is that the code below is slow. Can anyone suggest how to make it faster? Is there a better way to do this?

import csv
import pandas as pd
from urllib2 import urlopen
import urllib2
import threading
import time

def urlResolution(url,tweetId,w):

    try:

        print "Entered Function"
        print "Original Url:",url

        hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

        #header has been added since some sites give an error otherwise
        req = urllib2.Request(url, headers=hdr)
        temp = urlopen(req)
        newUrl = temp.geturl()
        print "Resolved Url:",newUrl
        if newUrl!= 'None':
            print "in if condition"
            w.writerow([tweetId,newUrl])

    except Exception,e:
        print "Throwing exception"
        print str(e)
        return None

def urlResolver(urlFile):
    df=pd.read_csv(urlFile, delimiter="\t")

    df['Url']
    df2 = df[["Tweet ID","Url"]].copy()
    start = time.time()

    df3 = df2[df2.Url!="None"]

    list_url = []
    n=0
    w = csv.writer(open("OUTPUT_FILE.tsv", "w"), delimiter = '\t')
        w.writerow(["Tweet ID","Url"])

    maxC = 0
    while maxC < df3.shape[0]:
        #creates threads
        #only 40 threads are created at a time, since for large number of threads it gives <too many open files> error
        threads = [threading.Thread(target=urlResolution, args=(df3.iloc[n]['Url'],df3.iloc[n]['Tweet ID'],w)) for n in range(maxC,maxC+40)]

        for thread in threads:
                thread.start()
        for thread in threads:
                thread.join()
        if maxC+40 >= df3.shape[0]:
            threads = [threading.Thread(target=urlResolution, args=(df3.iloc[n]['Url'],df3.iloc[n]['Tweet ID'],w)) for n in range(maxC,df3.shape[0])]

                    print "threads complete"
                    for thread in threads:
                            thread.start()
                    for thread in threads:
                            thread.join()
            break
        maxC = maxC + 40
    print "Elapsed Time: %s" % (time.time() - start)

    w.close()

if __name__ == '__main__':
    df3 = urlResolver("INPUT_FILE.tsv")


texts:
I would like to get a few tips on how to improve this program, which is supposed to help recovering lost passwords from .zip files.

import zipfile
import string
import itertools
import random
import time

"""
Zipfile password cracker using a dictionary attack and, if not successful,
switches to bruteforce
"""

def crack(zipfilename,dictionary):

    t0=time.time()
    password = None
    zip_file = zipfile.ZipFile(zipfilename)
    alphabet = string.ascii_letters + string.digits + string.punctuation

    #Tries at first a dictionary attack

    with open(dictionary, 'r') as f:
        for line in f.readlines():
            password_string = line.strip('\n')
            try:
                password = bytes(password_string, 'utf-8')
                zip_file.extractall(pwd=password)
                t1=time.time()
                total = t1 - t0
                print('Password found : %s' %password_string)
                print('Time spent : %f seconds' %total)
                return
            except:
                pass

    #If the password hasn't been found yet, the function switches to bruteforce

    nbcharmax = 10 #Maximum length to test

    for i in range(1,nbcharmax):
        print('Testing length = %i' % i)
        for j in itertools.product(alphabet, repeat=i):
            try:
                password_string=''.join(j)
                password = bytes(password_string, 'utf-8')
                zip_file.extractall(pwd=password)
                t1=time.time()
                total = t1 - t0
                print('Password found : %s' %password_string)
                print('Time spent : %f seconds' %total)
                return
            except:
               pass

if __name__ == "__main__":
    crack('test.zip','dictionary.txt')

So now the program seems to work fine but is a bit slow in my opinion. I'm wondering if there's a faster way than zip_file.extractall() to open archive files?


texts: A more efficient way to make JQL (Jira Query Language)

texts:
So my code here takes some parameters and then creates an SQLesque type of string (JQL).

function makeJQL(status, project, priority, description, summary){
    var arr = new Array();
    // Could put a null check here if all parametres are undefined
        if(status.length > 0){
            jql = "status="+'"'+status+'"';
            arr.push(jql)
        }
        if(project.length > 0){
            jql = "project="+'"'+project+'"';
            arr.push(jql)
        }
        if(priority.length > 0){
            jql = "priority="+'"'+priority+'"';
            arr.push(jql)
        }
        if(description.length > 0){
            jql = "description="+'"'+description+'"';
            arr.push(jql)
        }
        if(summary.length > 0){
            jql = "summary="+'"'+ summary +'"';
            arr.push(jql)
        }
        var jql = "";
        for(var i = 0; i < arr.length; i++){
            jql = jql + arr[i]+ ' AND '
        }
        jql = jql.substring(0, jql.length - 5);
        return jql
}

The only thing is, is that there is a lot of code repetition, but I don't know how to overcome this really. I also haven't put a null check in because if the function is called, there has to be parameters passed.


texts:
I was told to have my code reviewed here as I am a total beginner to Python.
I made a small Tkinter script that generates a 4x4 field of buttons and randomly recolors them when clicking on any button, but I was told that the code is not clean. If someone could point out a few flaws and some possible enhancements that would relly help a lot.

from tkinter import *
from random import randint

window = Tk()
window.title("Test")
window.geometry('200x200')
color = ["red","blue","green","yellow","black","purple","orange"]
RandInt = 0
j = 0
h = 0

def ButtonDef(xvar = 0,yvar = 0):
    btn = Button(window,command =lambda:[RandomColor()])
    btn.grid()
    btn.place(x = xvar*50, y = yvar*50, width = 50, height = 50)

    def RandomColor():
        for child in window.winfo_children():
            child.configure(bg=color[randint(0,6)])

while j in range (4):
    i = 0
    j += 1
    while i in range (4):
        ButtonDef(i,h)
        i += 1
        if i == 4:
            h += 1
window.mainloop()


texts: Treat undef in Perl's  operator as +inf instead of 0

texts:
I have to sort some numbers with Perl. But some of the numbers are undefined. Perl's compare operator <=> treats undef as -inf 0. The result is, that the undefined numbers are at the beginning:

perl -MData::Dumper -e 'print Dumper(sort {$a <=> $b} 3, undef, 2, 1);'
$VAR1 = undef;
$VAR2 = 1;
$VAR3 = 2;
$VAR4 = 3;

I want them to occur at the end, because they represent new items, which should be added at the end. This means I am looking for a way to change the way Perl treats undef. In my case undef should be treated as +inf instead of -inf 0. I came up with the following expression.

($a <=> $b) * ((defined $a)*2-1) * ((defined $b)*2-1)

Is it always correct or did I miss anything?

And is there an easier way to achieve the same?


texts:
I am learning Haskell and as exercise I am doing Project Euler Problems. In this case PE1.

-- Sum any given finite Airthmetic Progression
sumAP :: Integer -> Integer -> Integer -> Integer
sumAP first limit step = do
  let last  = limit - (limit `rem` step)
  let terms = (last - first) `quot` step + 1
  let avg   = first + last
  terms * avg `quot` 2

Now, off the bat I am shadowing the last function. How could I rename this variable along with first?

Is there any way I can improve readability? Any edge case or fail case I haven't covered? Any performance fail?


texts: Stack Exchange Data Explorer query to find upvoted questions with only downvoted answers

texts:
I have written a SQL query against the Stack Exchange Data Explorer that identifies answered questions with a positive score for which all the answers have a negative score (this was an answer to this Meta Stack Exchange post, though the code in that post is different from what I've posted below).

It's a fairly straightforward query; you can see it and run it on the Data Explorer (where you can also examine the schemata of the tables), and I have reproduced it below for your convenience.

SELECT
  q.Id AS [Post Link], -- this alias makes the Data Explorer do magic link rendering
  MAX(q.Score) AS [Score],
  COUNT(a.Id) AS [AnswerCount],
  AVG(CAST(a.Score AS float)) AS [AvgAnswerScore]
FROM
  Posts AS q
  -- INNER JOIN => At least one answer
  INNER JOIN Posts AS a
    ON q.Id = a.ParentId
WHERE
  -- Question has a positive score
  q.Score >= 1
GROUP BY
  q.Id
HAVING
  -- Zero answers with a non-negative score
  SUM((CASE WHEN a.Score >= 0 THEN 1 ELSE 0 END)) = 0
ORDER BY
  [Score] DESC,
  [AnswerCount] DESC

While I of course would love to hear anything you have to say about this code, I am particularly interested in the following:

Stylistic tips - coming from the perspective of a PEP8-adhering Python guy, the huge inhomogeneity in SQL coding styles makes me queasy.
MAX(q.Score) looks really stupid and is semantically wrong, since there's obviously only one q.Score for each q.Id since they come from the same table, and q.Id is the primary key of that table. But putting q.Score into the GROUP BY also seems weird to me, since that's not semantically what I'm doing either. Is there a better way to approach this?
How do the performance characteristics of the HAVING clause here differ from instead using a WHERE clause of the form below?

q.Score >= 1
AND NOT EXISTS (
  SELECT 1
  FROM Posts AS a2
  WHERE a2.ParentId = q.Id AND a2.Score >= 0
)

My sense is that HAVING SUM(...) = 0 is probably better, since, uh... there doesn't need to be a new subquery for each row of the outer query? But I don't know if that is true or even makes sense.


texts: Filter then map instances from a stream and other Java 8 hiccups

texts:
I'm having a hard time rewriting this method to something more legible and understandable for the reader.

static Stream<Class<? extends MyType>> collectMyTypes(Object o) {
  return Reflection.lineage(o.getClass())
      .flatMap(c -> Arrays.stream(c.getDeclaredFields()))
      .map(Field::getGenericType)
      .filter(t -> t instanceof ParameterizedType)
      .map(t -> (ParameterizedType) t)
      .filter(t -> t.getRawType() == MyTypeWrapper.class)
      .map(t -> t.getActualTypeArguments()[0]) //MyTypeWrapper is final and has only 1 type argument.
      .filter(t -> t instanceof Class)
      .map(t -> (Class<? extends MyType>) t);
}

Here are the tools/classes I use:

Reflection.lineage(Class<T>) iterates over all parents classes of T;
MyTypeWrapper is defined as final class MyTypeWrapper<T extends MyType>;
MyType is defined as abstract class MyType.

What annoys me with this code is that it's barely legible, mostly because of the succession of filter on instance then map. I tried to find in Java 8  something similar to Guava's Iterables.filter(Iterable<?>,Class<T>) but haven't found any (yet, I implemented a similar method, but the code then looks like Lisp). Also, the call to Arrays.stream disturbs me. Yeah, I could split it into .map(Class::getDeclaredFields).flatten(Arrays::stream) but this would add some unnecessary complexity, wouldn't it?

Anyways, any input is welcome.

Given the example below, this method will keep/skip various fields.

class GoodExample extends MyType {}
class BadExample extends MyType {}
class Example {

  // GoodExample will be returned.
  MyTypeWrapper<GoodExample> object1;

  // BadExample will be skipped because the type is a wildcard
  MyTypeWrapper<? extends BadExample> object2;

  // There is no type to return so this field is skipped.
  MyTypeWrapper object3;

  // This is not an instance of MyTypeWrapper so it's skipped.
  Object object4;

  // This is generic, but still not a MyTypeWrapper, so it's skipped.
  List<BadExample> object5;
}

Edit:

Originally the method was this:

  List<Class<? extends MyType>> types = new ArrayList<>();
  Reflection.lineage(o.getClass())
      .forEach((c) -> {
        for (Field f: c.getDeclaredFields()) {
          Type type = f.getGenericType();
          if (!(type instanceof ParameterizedType)) {
            continue;
          }
          ParameterizedType pType = (ParameterizedType)type;
          if (pType.getRawType() != MyTypeWrapper.class) {
            continue;
          }
          // length is 1.
          Type argType = pType.getActualTypeArguments()[0];
          if (!(argType instanceof Class)) {
            continue;
          }
          Class<? extends MyType> argClass = (Class<? extends MyType>)argType;
          types.add(argClass);
        }
      });
return types;


texts: Removing all delegates from an event dispatcher

texts:
Given a class which is an event dispatcher whose underlying store is a dictionary of events whose key is the event type private readonly Dictionary<Type, Delegate> _applicationEventHandlers;, is this the correct way to remove all remaining delegates when the class needs to be disposed?

    private void RemoveAllListeners()
    {
        foreach (Type handlerType in _applicationEventHandlers.Keys)
        {
            Delegate handlers = _applicationEventHandlers[handlerType];
            Delegate.RemoveAll(handlers, handlers);
        }
    }

Or is there a better way? I have included the whole class below for clarity.

using System;
using System.Collections.Generic;

internal class ApplicationEventDispatcher : IApplicationEventDispatcher, IDisposable
{
    private bool _disposed;
    private readonly Dictionary<Type, Delegate> _applicationEventHandlers;

    public ApplicationEventDispatcher()
    {
        _applicationEventHandlers = new Dictionary<Type, Delegate>();
    }

    ~ApplicationEventDispatcher()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (_disposed) return;

        if (disposing)
        {
            // free other managed objects that implement IDisposable only
            RemoveAllListeners();
        }

        // release any unmanaged objects
        // set the object references to null

        _disposed = true;
    }

    public void AddListener<T>(ApplicationEventHandlerDelegate<T> handler) where T : IApplicationEvent
    {
        if (_applicationEventHandlers.ContainsKey(typeof(T)))
        {
            Delegate handlersForType = _applicationEventHandlers[typeof(T)];
            _applicationEventHandlers[typeof(T)] = Delegate.Combine(handlersForType, handler);
        }
        else
        {
            _applicationEventHandlers[typeof(T)] = handler;
        }
    }

    public void RemoveListener<T>(ApplicationEventHandlerDelegate<T> handler) where T : IApplicationEvent
    {
        if (_applicationEventHandlers.ContainsKey(typeof(T)))
        {
            var handlerToRemove = Delegate.Remove(_applicationEventHandlers[typeof(T)], handler);
            if (handlerToRemove == null)
            {
                _applicationEventHandlers.Remove(typeof(T));
            }
            else
            {
                _applicationEventHandlers[typeof(T)] = handlerToRemove;
            }
        }
    }

    private void RemoveAllListeners()
    {
        foreach (Type handlerType in _applicationEventHandlers.Keys)
        {
            Delegate handlers = _applicationEventHandlers[handlerType];
            Delegate.RemoveAll(handlers, handlers);
        }
    }

    public void Dispatch(IApplicationEvent @event)
    {
        if (@event == null)
        {
            return;
        }

        if (_applicationEventHandlers.ContainsKey(@event.GetType()))
        {
            _applicationEventHandlers[@event.GetType()].DynamicInvoke(@event);
        }
    }
}


texts:
Original question:

Enum list to STL container

Goal: Write a function enumToSTLContainer() that is to return any STL container whose elements are from a specified enum list.

The current solution below uses the assumption that the enum underlying values start at zero and are consecutive, and hence needs improvement.  The solution is in C++11 rather than C++14 so that everyone here should be able to compile it.

#include <iostream>
#include <vector>
#include <set>

enum MyEnum {A, B, C, D, E, NumElements};

template <std::size_t...> struct index_sequence {};

template <std::size_t N, std::size_t... Is>
struct make_index_sequence_helper : make_index_sequence_helper<N-1, N-1, Is...> {};

template <std::size_t... Is>
struct make_index_sequence_helper<0, Is...> {
    using type = index_sequence<Is...>;
};

template <std::size_t N>
using make_index_sequence = typename make_index_sequence_helper<N>::type;

template <typename RETURN_TYPE, std::size_t... TYPES>
inline RETURN_TYPE helper (index_sequence<TYPES...>) {
    return {static_cast<typename RETURN_TYPE::value_type>(TYPES)...};
}

template <typename CONTAINER, std::size_t N>
CONTAINER enumToSTLContainer() {
    return helper<CONTAINER> (make_index_sequence<N>());
}

int main() {
    const std::vector<MyEnum> enumVector = enumToSTLContainer<std::vector<MyEnum>, NumElements>();
    for (MyEnum x : enumVector)
        std::cout << x << ' ';  // 0 1 2 3 4
    const std::set<MyEnum> enumSet = enumToSTLContainer<std::set<MyEnum>, NumElements>();
    std::cout << "\n\n";
    for (MyEnum x : enumSet)
        std::cout << x << ' ';  // 0 1 2 3 4
}

I would appreciate if someone could show me how to improve this solution where the enum underlying values are not consecutive.  Ideally NumElements should not be needed either.  I presume only make_index_sequence_helper needs to be modified according the MyEnum underlying values?

The only generalization that I could come up with is the lousy:

template <typename CONTAINER, std::size_t... Is>
CONTAINER enumNonContiguousToSTLContainer() {
    return helper<CONTAINER> (index_sequence<Is...>());
}


texts: Folder browser dialog to remember recent folder. Which method is better?

texts:
which of the following code you prefer and why?

The scenario is, I need to pass the recent folder path  to folder browser dialog and if user selects any folder, need to save it back. The value is stored in Application settings.

My settings class.

    internal sealed class Settings : ApplicationSettingsBase
    {
        private static readonly Settings DefaultInstance = (Settings)Synchronized(new Settings());

        public static Settings Default
        {
            get { return DefaultInstance; }
        }

        [UserScopedSetting]
        public string RecentFolder
        {
            get { return (string) this["RecentFolder"]; }
            set
            {
                this["RecentFolder"] = value;
                Save();
            }
        }
}

Method 1.

var dialog = new FolderBrowserDialog
            {
                SelectedPath = Settings.Default.RecentFolder
            };

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK && dialog.SelectedPath.Length > 0)
            {
                Settings.Default.RecentFolder = dialog.SelectedPath;
               //action goes here
            }

Method 2: using extension methods.

    public static class FolderBrowserDialogExtensions
    {
//The extension method is in separate project where we don't have reference to the settings class.

        public static DialogResult ShowDialog(this FolderBrowserDialog dialog, ApplicationSettingsBase settings, string key)
        {
            dialog.SelectedPath = settings[key].ToString();

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK || result == DialogResult.Yes)
            {
                settings[key] = dialog.SelectedPath;
                settings.Save();
            }
            return result;
        }
    }

            var dialog = new FolderBrowserDialog();

            DialogResult result = dialog.ShowDialog(Settings.Default, "RecentFolder");

            if (result == DialogResult.OK && dialog.SelectedPath.Length > 0)
            {
               //action goes here
            }


texts:
In my application we have four inputs radio controls and on the load the value is checked to true. When the user select another radio and then save the form I want to get the new value. I am using the find class but then I need to use checked[0]. Is there a better way to do this?
JS
$("#form").submit(function (event) {
   event.preventDefault();
     console.log('free-text-form');
            var sortOrder = $(this).data('sortorder');
            console.log(sortOrder);
            var form = $(this);
            console.log('Processing Current Check');
            var checked = form.find(".radio-Class:checked");
            var currentChecked = checked[0];
            console.log(currentChecked);
            console.log(currentChecked.value);
            if (checkedRegRef.length == 1) {
                var NewId = currentChecked.value;
                 console.log(NewId);
            }
});

Working Example
https://jsfiddle.net/tjmcdevitt/vh9n5srL/87/


texts:
I saw somewhere on here that it helps reduce spam by adding a dummy input field that you hide with display: none, and like if it's filled out, then it's obviously a bot sending the message. Well, I did something kind of like that but initially set it to = 0. So if it's not 0 then it doesn't send the form, since a bot would have changed the value to something else. I don't know if that will really work effectively or not. If you have a better way to do something like that, please share.
I don't know if my token validation stuff is anywhere close to how it should be. Please let me know if what I'm doing with that is even adding any security or not.
After the user submits the form, I put some echo's in so that what they entered is still shown in the form fields, in case there was an error so they don't lose what they typed. Is my use of htmlspecialcharacters needed there?

Please share any other comments, recommendations, improvements, etc, etc that you see with my code, because I really want to get better at this and your answers almost always help me understand things better. You know, the manual can be kind of confusing at times when your new so having a master coder review your code and explain things helps so much for me.

<?php

session_start();

function getIp() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
         $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

if($_POST['yourlastname'] === '0') {
    if ($_SESSION['token1'] == $_POST['token']) {
    echo "
checker: " . $_SESSION['token1'] . "  and the post token " . $_POST['token'] ."
";
        if(filter_var($_POST['youremail'], FILTER_VALIDATE_EMAIL)) {
            $name = htmlspecialchars($_POST['yourname']);
            $email = htmlspecialchars($_POST['youremail']);
            $from = $name . ' - ' . $email;
            $ip = getIp();
            $message = htmlspecialchars($_POST['yourmessage']) . "\r\n" .
                          'Name : ' . $name . "\r\n" .
                          'Email : ' . $email . "\r\n" .
                          'User IP: ' . htmlspecialchars($ip);
            $message = wordwrap($message, 60, "\r\n");
            $headers = 'From: ' . $from . "\r\n" .
                          'Reply-To: ' . $email;
            mail('email@example.com', 'Static Subject', $message, $headers);
        }
    }
}

$token1 = md5(microtime(true));
$_SESSION['token1'] = $token1;

?>

<!DOCTYPE html>

<meta charset="utf-8">
<title>Tittle</title>

<?php $token2 = md5(microtime(true)); ?>
<form method="post" name="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

<input name="token" type="hidden" value="<?php echo htmlspecialchars($token2); ?>">

Your Name:
<input class="required" id="yourname" name="yourname" type="text" value="<?php if(isset($_POST['yourname'])) { echo htmlspecialchars($_POST['yourname']); } ?>">

Your Last Name:
<input class="required" id="yourlastname" name="yourlastname" type="text" style="display: none;" value="0">

Your Email:
<input class="required" id="youremail" name="youremail" type="text" value="<?php if(isset($_POST['youremail'])) { echo htmlspecialchars($_POST['youremail']); } ?>">

Your Message:
<textarea class="required" id="yourmessage" name="yourmessage" cols="30" rows="8"><?php if(isset($_POST['yourmessage'])) { echo htmlspecialchars($_POST['yourmessage']); } ?></textarea>

<input type="submit" id="send" value="Send">

</form>


texts: Database schema for a products and bugs aggregator

texts:
As an exercise in learning, I'm creating a bugs/issues tracking and "aggregator" web application. A simple app consisting of products, issues, reviews and links related to it. The links will be urls pointing to issues/reviews already created on external sites (bugzillas, stackoverflow, etc). Here is my initial effort towards creating the database schema of the app:

CREATE TABLE PRODUCT (
    ID INTEGER PRIMARY KEY,
    NAME VARCHAR(255), --Samsung Galaxy, Apple iphone, Dell Inspiron, GNOME Desktop, etc.
    VERSION VARCHAR(255), --S5, v3.14, etc.
    IMAGE VARCHAR(255), --PATH TO UPLOADED IMAGE FILE
    CATEGORIES VARCHAR(255),
    TAGS VARCHAR(255),
    CREATOR VARCHAR(255) --EMAIL ADDRESS OF PRODUCT UPLOADER
);

CREATE TABLE REVIEWS (
    ID INTEGER PRIMARY KEY,
    PRODUCT_ID INTEGER,
    CREATOR VARCHAR(255), --EMAIL ADD. OF REVIEWER
);

CREATE TABLE ISSUES(
    ID INTEGER PRIMARY KEY,
    PRODUCT_ID INTE GER,
    CREATOR VARCHAR(255), --EMAIL ADDRESS
    DESCN VARCHAR(255), --DESCRIPTION
    LINKS VARCHAR(255)
);

CREATE TABLE LINKS(
    ID INTEGER PRIMARY KEY,
    PRODUCT_ID INTEGER,
    LINK_TYPE VARCHAR(255), --ISSUE OR REVIEW OR OTHER (STACKOVERFLOW/REDDIT/HN CONTENT)
    DESCN VARCHAR(255), --A SHORT PREVIEW OF LINKED CONTENT
    URL VARCHAR(255),
    LAST_UPDATED DATETIME, --CRAWLER TIMESTAMP
);

CREATE TABLE LINK_VOTES(
    ID INTEGER PRIMARY KEY,
    LINK_ID INTEGER,
    VOTER VARCHAR(255), --EMAIL ADD. OF THE VOTER
    VOTE INTEGER, --1==UP, 0==DOWN
);

Appreciate if you can provide me suggestions, improvements, etc.


texts: Create a binary search tree from a sorted array (increasing order)

texts:
Description:

Since the input array is sorted, we can take the middle element of the array to be parent and recursively do the same on the left and right halves to create left and right sub trees of the parent.

class Node{
        int data;
        Node left;
        Node right;
        Node(int x)
        {
            data = x;
        }
    }
    public class createBSTFromSortedArray {

        public static Node getBST(int[] sortedArray, int start, int end)
        {
            if(start <= end)
            {
            int mid = (start+end)/2;
            Node root = new Node(sortedArray[mid]);
            root.left = getBST(sortedArray,start,mid-1);
            root.right = getBST(sortedArray, mid+1,end);
            return root;
            }
            return null;
        }

        public static void printTree(Node root)
        {
            if(root == null)
            {
                return ;
            }

            printTree(root.left);
            System.out.println(root.data);
            printTree(root.right);
        }
        public static void main(String[] args) {
            int[] input = {};
            Node root = getBST(input, 0 , input.length - 1);
            printTree(root);
            }
    }


texts: Reload polyline midpoints into parallel tables

texts:
I have an Oracle GIS database that has spatial tables. The records in the spatial tables have a geometry column that contains polylines.

I've written a Python 2.7.16 script that calculates the midpoint of the polylines and inserts the midpoint information into parallel tables. The script will be run as part of a nightly scheduled job on a server.

Note: I use the short form FC in the code, which stands for Feature Class. A feature class is an ESRI GIS term that can be thought of as a table with a geometry column.

What the code does:

Loops through a list. Each row in the list has an input FC, a target FC, and an ID field.
For each row in the list:

Truncate the target FC
Populate the target FC with midpoints from the input FC

So yeah, I'm new to Python. How can the code be improved?

import arcpy
conn = "Database Connections\\<YOUR CONNECTION.sde>\\"

#This script only works for polyline feature classes (not polygons or points).
#Caution! The target FCs will get truncated! All records in the target FCs will be deleted.

#       INPUT FC               TARGET FC                     ID FIELD (for both the input FC and the target FC)
lstFC = [\
        ["<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"   ],\
        ["<OWNER>.<SEWER>"   , "<OWNER>.S_SEWER_MIDPOINT"  , "SEWER_ID" ],\
        ["<OWNER>.<ROAD>"    , "<OWNER>.S_ROAD_MIDPOINT"   , "ROAD_ID"  ],\
        ]

def ReloadMidpoints():
    for fc in lstFC:
        inputFC  = conn + (fc)[0]
        targetFC = conn + (fc)[1]
        idField  = (fc)[2]

        arcpy.TruncateTable_management(targetFC)
        print "<" + targetFC + "> has been truncated."

        with arcpy.da.SearchCursor(inputFC, ['SHAPE@', idField]) as s_rows:
            with arcpy.da.InsertCursor(targetFC, ['SHAPE@', idField, "MIDPOINT_X","MIDPOINT_Y"]) as i_rows:
                for row in s_rows:
                    Midpoint = row[0].positionAlongLine(0.50,True).firstPoint
                    rowVals = [(Midpoint.X,Midpoint.Y),s_rows[1],Midpoint.X,Midpoint.Y]
                    i_rows.insertRow(rowVals)

        print "<" + targetFC + "> has been reloaded with midpoints that were generated from <" + (inputFC) + ">."
        print ""

ReloadMidpoints()
print "Complete."


texts:
I have written a function that copies memory from one destination to another. I would like you to view my code and tell me if I have to fix something. That's the code:
void* memCopy(void* destination, const void* source, size_t size)
{
    double *a = (double*)source, *b = (double*)destination;
    void* end = a + (size / sizeof(double));
    while ((void*)a < end)
    {
        *b = *a;
        ++a;
        ++b;
    }
    char* a2 = (char*)a;
    char* b2 = (char*)b;
    end = a2 + (size % sizeof(double));
    while (a2 < end)
    {
        *b2 = *a2;
        ++a2;
        ++b2;
    }
    return destination;
}

I have used double* to make the function faster.


texts:
I am learning C and I have some trouble with pointers. I decided to create a queue to practice a bit. The program works as intended, however I want to know some good practices and suggestions.

Here is queue.c:

#include <stdlib.h>
#include "bank_sim.h"
#include "queue.h"

void initiliaze(Queue *queue) {
        queue->head = NULL;
        queue->tail = NULL;
}

void enqueue(Queue *queue, Customer *customer) {
        if (queue->head == NULL) {
                queue->head = customer;
                queue->tail = customer;
                queue->customer_cnt++;
        } else {
                queue->tail->next = customer;
                queue->tail = customer;
                queue->customer_cnt++;
        }
}

Customer *dequeue(Queue *queue) {
        if (queue->head == NULL) {
                return NULL;
        } else {
                Customer *head_customer = queue->head;
                queue->head = queue->head->next;
                head_customer->next = NULL;
                queue->customer_cnt--;
                return head_customer;
        }
}

queue.h:

#ifndef QUEUE_H
#define QUEUE_H
#include "bank_sim.h"

typedef struct {
        Customer *head;
        Customer *tail;
        int customer_cnt;
} Queue;

void initiliaze(Queue *queue);
void enqueue(Queue *queue, Customer *customer);
Customer *dequeue(Queue *queue);

# endif

Finally bank_sim.h:

#ifndef BANK_SIM_H
#define BANK_SIM_H

typedef struct Customer Customer;

struct Customer {
        int id;
        int service_time;
        struct Customer *next;
};

typedef struct {
        Customer *customer;
        int occupied;
} Bank_Teller;

#endif

Comments regarding anything is welcome including whether my structure for Customer and Queue can be improved.


texts: Leetcode: Longest substring without repeating characters

texts:
I saw the editorial solutions for this problem, but they are written in an unfamiliar language. I'd like to post my code, which worked, and understand the timing of my solution. I don't understand how to judge Big-O time yet.

def length_of_longest_substring(s)

    longest_sub,current_sub = "",""
    s.each_char do |c|
      if current_sub.include?(c)
        longest_sub = current_sub if current_sub.length > longest_sub.length
        current_sub=current_sub[current_sub.index(c)+1..-1]+c
      else
        current_sub+=c
      end
    end
    longest_sub = current_sub if current_sub.length > longest_sub.length
    longest_sub.length
end

I assume that since I'm creating strings, my space complexity suffers somewhat. I'm not really sure how I would speed things up with time.


texts: Simple Calculator to add/subtract/multiply/divide 2 inputs

texts:
This is for an assignment in my robotics class so the requirements I needed to meet was that it had to be in a while loop and the input numbers needed to be float point. I just want to make sure that I'm not using any bad practices and if there are any areas that can be improved.
while (True):
    # Gets operator, converts to int and breaks if its not a number
    try: operator = int(input("Choose an Operator:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\nInput (1/2/3/4):"))
    except:
        print('Invalid Input: Choose A Valid Operation')
        break

    # Checks the operator is within 1 and 4
    if operator > 4 or operator < 1:
        print('Invalid Input: Choose A Valid Operation')
        break

    # Gets first and second number, converts numbers to float and breaks if its not a number
    try: firstnum = float(input('First Number:'))
    except:
        print('Invalid Input: Not a valid number')
        break
    try: secondnum = float(input('Second Number:'))
    except:
        print('Invalid Input: Not a valid number')
        break

    if operator == 1:
        print('{0} + {1} ='.format(firstnum, secondnum), end =" ")
        print(firstnum + secondnum)
        break
    if operator == 2:
        print('{0} - {1} ='.format(firstnum, secondnum), end =" ")
        print(firstnum - secondnum)
        break
    if operator == 3:
        print('{0} * {1} ='.format(firstnum, secondnum), end =" ")
        print(firstnum * secondnum)
        break
    if operator == 4:
        print('{0} / {1} ='.format(firstnum, secondnum), end =" ")
        print(firstnum / secondnum)
        break


texts: Filtering a List based on a Suffix and avoid duplicates

texts:
I was wondering if there is a better way to solve this issue.
I have a list like this:
imp_list=["aa","daa","ab","as","aem",
      "aum","aw","aa","acm","at",
      "ar","aa_imp","daa_imp","ab_imp",
      "as_imp"]

I want to select all the strings that have the _imp suffix, plus all the the strings that have no _imp partner.
That's because aa_imp it's just a modified version of aa, and for me, in a large sense, it's a replica.
So I created this function:
def imputed_handler(my_list):
  imp=[x for x in my_list if "imp" in x]

  cleaned_imp=set(map(lambda x: x.replace("_imp",""),imp))

  not_imp=[x for x in my_list if "imp" not in x]
  set_list=set(my_list)
  no_replica=list(set_list-cleaned_imp)
  print(no_replica)
  return no_replica

Running the code as described above
test=imputed_handler(imp_list)

I get the following output:
['at', 'acm', 'aw', 'ar', 'daa_imp', 'aem', 'as_imp', 'ab_imp', 'aa_imp', 'aum']

Do better solutions exist? Thanks for your time, and let me know if something is not clear :)


texts:
Here's the problem statement for Minimum Scalar Product

You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors
is the smallest possible, and output that minimum scalar product.

Please review my code.

#include<iostream>
#include<vector>
#include<algorithm>

int main() {
    int t;
    std::cin >> t;
    while (t--) {
        std::size_t n;
        std::cin >> n;
        if (n != 0) {
            int product = 0;
            std::vector<int> x(n);
            for (std::size_t x_index = 0; x_index < n; ++x_index) {
                std::cin >> x[x_index];
            }
            std::vector<int> temp(n);
            for (std::size_t t_index = 0; t_index < n; ++t_index) {
                std::cin >> temp[t_index];
            }
            sort(x.begin(),x.end());
            sort(temp.begin(),temp.end());
            std::vector<int> y(n);
            for (std::size_t y_index = 0; y_index < n; ++y_index) {
                y[y_index] = temp[temp.size()-1-y_index];
            }
            for (std::size_t i = 0; i < n; ++i) {
                product += x[i]*y[i];
            }
            std::cout << product << '\n';
        }
    }
}

How can I make this code better and faster? Particularly without using an additional vector? And is there a better solution?


texts: Using one parent model and other extending it in a PHP framework

texts:
I have multiple models which all have the same functions in my framework. I decided to create one "parent" model and all of my other models would extend and inherit its functions like this.

My other models would be like this:

class Games_model extends MY_Model {
    protected $table = 'games';
    protected $_default_select = array();
    protected $_default_join = array();

    public function __construct()  {
        $this->_default_select = array(
            $this->table.'.*',
            $this->table.'.id as id',
            $this->table.'.name as name',
            'categories.id as cat_id',
            'categories.name AS cat_name'
        );
        $this->_default_join = array('categories', 'categories.id = fiches.console_id', 'left');
    }
}

Here's how I use it:

$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();

Is it a better idea to do like that or to have all the code of MY_Model in Games_model?


texts:
I'm working on a project (in C++98) that uses a grammar validation service to validate mapping expressions for a small DSL. To simplify the project code, I've written a small interface for using the validator service, which I'm hoping to get some feedback on.

exprval_expressionvalidator.h:

#ifndef EXPRVAL_EXPRESSIONVALIDATOR_H
#define EXPRVAL_EXPRESSIONVALIDATOR_H

#include "gval_stub_validator.h"

#include <map>
#include <string>

namespace exprval {

// Abstract base implementation of validator for expressions of arbitrary type.
// Derived class must implement a public interface method to call the private
// templated method `validate()`.
template <typename EXPR_T>
class ExpressionValidator {

public:

    // Return codes for validation success
    enum ReturnCode { INVALID, VALID };

    // Destructor
    virtual ~ExpressionValidator();

private:

    // Return `VALID` if `expr` is valid, else return `INVALID`.
    virtual ReturnCode validate(const EXPR_T& expr) = 0;

};

template <typename EXPR_T>
inline ExpressionValidator<EXPR_T>::~ExpressionValidator() {}

class MappingExpressionValidator : public ExpressionValidator<std::string> {

public:

    // Return `VALID` if `mapping_expr` with inline tokens `inline_tokens` is
    // valid, else return `INVALID`.
    ReturnCode validate(const std::string& mapping_expr,
                        const std::map<unsigned int, std::string> inline_tokens);

private:

    // Stub for grammar validation service
    gval_stub::GrammarValSvcStub d_grammar_val_stub;

    // Return `VALID` if `expr` is valid, else return `INVALID`.
    virtual ReturnCode validate(const std::string& expr);

};

}  // Close namespace `exprval`

#endif

exprval_expressionvalidator.cpp:

#include "exprval_expressionvalidator.h"

namespace exprval {

typedef MappingExpressionValidator::ReturnCode RC;

RC MappingExpressionValidator::validate(const std::string& mapping_expr,
                                        const std::map<unsigned int,
                                              std::string>& inline_tokens) {
    typedef std::map<unsigned int, std::string>::const_iterator InlineTokenIt;

    for (InlineTokenIt it = inline_tokens.begin(); it != inline_tokens.end(); ++it) {
        const unsigned int token_id = it->first;
        const std::string& token_text = it->second;

        // Register token with grammar validation service
        d_grammar_val_stub.register_token(token_id, token_text);
    }

    return validate(mapping_expr);
}

RC MappingExpressionValidator::validate(const std::string& expr) {
    // Execute call to validation service
    return d_grammar_val_stub.is_valid_mapping_expr(expr);
}

}  // Close namespace `exprval`

(I've removed a few comments and parts of the code that is specific to our application.)

As I'm fairly new to C++, I am looking for overall feedback as far as language usage, with specific focus on the following items:

General C++ style and API design
Naming conventions
Documentation
Conformance to C++ template and inheritance usage paradigms