texts:
Continued from Playing "craps" for the win

  You roll two dice. Each die has six faces, which contain one, two,
  three, four, five and six spots, respectively. After the dice have
  come to rest, the sum of the spots on the two upward faces is
  calculated. If the sum is 7 or 11 on the first throw, you win. If the
  sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e.,
  the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
  throw, that sum becomes your “point.” To win, you must continue
  rolling the dice until you “make your point” (i.e., roll that same
  point value). You lose by rolling a 7 before making your point.

// Craps.java

package co.vu.xxx.craps;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Scanner;

public class Craps {
    private int point;
    public static enum possibleResults {UNDEFINED, WIN, LOSE};
    protected possibleResults gameResult;
    private String cause;
    private static SecureRandom randomNumbers = new SecureRandom();

    public Craps() {
        gameResult = possibleResults.UNDEFINED;
    }

    public static int rollDice() {
        int randN = 2 + randomNumbers.nextInt(6) + randomNumbers.nextInt(6);
        System.out.printf("Rolling dice... You got %d%n", randN);
        return randN;
    }

    public void firstRoll() throws IOException {
        waitUser();
        int tmp = rollDice();
        switch (tmp) {
            case 7:case  11:
                gameResult = possibleResults.WIN;
                cause= String.format("you have got a lucky number in the first round: %d.", tmp);
                break;
            case 2:case 3:case 12:
                gameResult = possibleResults.LOSE;
                cause= String.format("you have got an unlucky number in the first round: %d.", tmp);
                break;
            default:
                point = tmp;
        }
    }

    public void declareResult() {
        if(point != 0) {
            System.out.printf("You need to make your point: %d%n", point);
        }
        switch (gameResult) {
            case LOSE:
                System.out.printf("You have lost, because %s%n", cause);
                break;
            case WIN:
                System.out.printf("You have won, because %s%n", cause);
                break;
            case UNDEFINED:
                System.out.println("Game continues...\n");
                break;
        }
        System.out.println();
    }

    public void moreRolls() {
        waitUser();
        int tmp = rollDice();
        if(tmp == point) {
            gameResult = possibleResults.WIN;
            cause = "you have made your point!";
        } else if(tmp == 7) {
            gameResult = possibleResults.LOSE;
            cause = "you have hit 7 before making your point.";
        }
    }

    private void waitUser() {
        Scanner inputScan = new Scanner(System.in);
        System.out.print("Press enter to start rolling: ");
        String input = inputScan.nextLine();
    }
}

// UseCraps.java

package co.vu.xxx.craps;

import java.io.IOException;

public class UseCraps {
    public static void main(String[] args) throws IOException {
        Craps crapObj = new Craps();
        crapObj.firstRoll();
        crapObj.declareResult();
        while(crapObj.gameResult == Craps.possibleResults.UNDEFINED) {
            crapObj.moreRolls();
            crapObj.declareResult();
        }
    }
}


texts:
I would like to write a function in C that turns all negative values into zeros then shifts the positive numbers to the beginning of the array, maintaining the order of the positive integers in the array.

void shift_positives(int values[], int num_values) {
    int i;
    int last_zero = 0;
    int j;
    for (j = 0; j < num_values; j++) {
        if (values[i] < 0) values[i] = 0;

        if (values[j] > 0) {
            for (i = last_zero; i < j; i++) {
                if (values[i] == 0) {
                    last_zero = i;
                    break;
                }
            }
            if (last_zero < j) {
                values[last_zero] = values[j];
                values[j] = 0;
            }
        }
    }
}

My issue with this is that it runs at \$O(N^2)\$ because of the inner for loop. Is there a more efficient way to do this?


texts:
Below are two solutions to the FizzBuzz problem in Python. Which one of these is more "Pythonic" and why is it more "Pythonic" than the other?

Solution One:

fizzbuzz = ''

start = int(input("Start Value:"))
end = int(input("End Value:"))

for i in range(start,end+1):
    if i%3 == 0:
        fizzbuzz += "fizz"
    if i%5 == 0:
        fizzbuzz += "buzz"
    if i%3 != 0 and i%5 != 0:
        fizzbuzz += str(i)

    fizzbuzz += ' '

print(fizzbuzz)

Solution Two:

fizzbuzz = []

start = int(input("Start Value:"))
end = int(input("End Value:"))

for i in range(start,end+1):
    entry = ''
    if i%3 == 0:
        entry += "fizz"
    if i%5 == 0:
        entry += "buzz"
    if i%3 != 0 and i%5 != 0:
        entry = i

    fizzbuzz.append(entry)

for i in fizzbuzz:
    print(i)


texts: Shell script to display environment variables

texts:
This shell script writes my environment variables. If there is an argument, the shell script will grep for the argument in the environment variables.

PAGER=more
if type less > /dev/null;then PAGER=less; fi
echo $PAGER
if [ -z ${1+x} ]; then printenv|"$PAGER"; else printenv|grep "$1"|"$PAGER"; fi

If the above script is correct then I will work on my shell to be able to parse it. It can parse everything except the last line, which I added today.


texts: Getting the square of the difference between many points in a NumPy array

texts:
I have an array with 40000 numbers that are floats or ints. I need to perform some calculation.
To do this I have used nested for loop, but the code is really slow. Can I use something instead of nested the for loop? Is there any other way to reduce the execution time?
When I changed to a list comprehension the execution time reduce slightly.
Why did the list comprehension take less time?
import numpy as np
import time as t

pox1=  np.random.randint(1000, size= 40000)
time = np.arange(40000)

y=np.zeros(len(pox1))
w=np.zeros(len(pox1))

start = t.time()
for num in range (len(time)-1):
    z= [((pox1[i] - pox1[i-num]) ** 2) for i in range(num, len(pox1))]
    k=np.mean(z)
    y[num]=k

  # for i in range(num, len(pox1)):
  #    z.append((pox1[i] - pox1[i-num]) ** 2)

endtime = (t.time()-start)

print(y,endtime)


texts:
I have made a code to check if a word chain is correct or not.

The first input is the amount of words that will following
The first and last letter of every word should be the same
Therefore a chain can look like this:  Alaska - baobab - Cadillac - drievuldigheid -  Enigma -  fotografencollectief - Gasthuisberg

If the chain is incorrect the output should be the wrong word, else it should be 'word chain is correct'.

As you'll be thinking, this is an excercise for school. I have exam in a few days and I'm doing some excercises.

My code looks like this:

import string
words = int(input())
alphabet = string.ascii_lowercase
output = ''

for i in range(words):
    woord = input()

    #for the first word
    if i == 0:
        #make that the alpabet last letter is the starting letter of the word
        alphabet = alphabet[alphabet.index(woord[0].lower())+1:] + alphabet[0:alphabet.index(woord[0].lower())+1]

    #check if the last letter of the word is equal to the first  letter
    #check if the last letter of the word is equal to the last letter of the alphabet
    if woord[0].lower() == woord[-1].lower() and alphabet[-1] == woord[0].lower():
        #if so: move the alphabet one Index
        alphabet = alphabet[1:] + alphabet[:1]

    elif output == '':
        output = woord

if output == '':
    print('word chain is correct')
else:
    print(output)

I'm wondering if there is some room for improvement, as it looks my code isn't pythonic at all.


texts:
I try the most to solve a twoSum problem in leetcode

  Given an array of integers, return indices of the two numbers such that they add up to a specific target.

  You may assume that each input would have exactly one solution, and you may not use the same element twice.

  Example:

  Given nums = [2, 7, 11, 15], target = 9,

  Because nums[0] + nums[1] = 2 + 7 = 9,
  return [0, 1].

The plan:

brute force to iterate len(nums)   O(n)
search for target - num[i] with a hash table   O(1)

Implement

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        nums_d = {}
        for i in range(len(nums)):
            nums_d.setdefault(nums[i], []).append(i)

        for i in range(len(nums)):
            sub_target = target - nums[i]
            nums_d[nums[i]].pop(0) #remove the fixer
            result = nums_d.get(sub_target)#hash table to search

            if result:
                return [i, result[0]]
        return []

I strives  hours for this solution but found that answer accepted but not passed Score 60.

  Runtime: 60 ms, faster than 46.66% of Python3 online submissions for Two Sum.
  Memory Usage: 16.1 MB, less than 5.08% of Python3 online submissions for Two Sum.

I want to refactor the codes  so that to achieve at least faster than 60%.

Could you please provide hints?


texts: Scraping urls asynchronous including exception handling

texts:
I'm trying to understand how to work with aiohttp and asyncio. The code below retrieves all websites in urls and prints out the "size" of each response.

Is the error handling within the fetch method correct?
Is it possible to remove the result of a specific url from results in case of an exception - making return (url, '') unnecessary?
Is there a better way than ssl=False to deal with a potential ssl.SSLCertVerificationError?
Any additional advice on how i can improve my code quality is highly appreciated

import asyncio
import aiohttp

async def fetch(session, url):
    try:
        async with session.get(url, ssl=False) as response:
            return url, await response.text()
    except aiohttp.client_exceptions.ClientConnectorError as e:
        print(e)
        return (url, '')

async def main():
    tasks = []
    urls = [
        'http://www.python.org',
        'http://www.jython.org',
        'http://www.pypy.org'
    ]
    async with aiohttp.ClientSession() as session:
        while urls:
            tasks.append(fetch(session, urls.pop()))

        results = await asyncio.gather(*tasks)
        [print(f'{url}: {len(result)}') for url, result in results]

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

Update

Is there a way how i can add tasks to the list from within the "loop"? e.g. add new urls while scraping a website and finding new subdomains to scrape.


texts:
As of now, I am using this code to open a file and read it into a list and parse that list into a string[]:

string CP4DataBase = "C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt";
CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText);
string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\n');
List<string> tempCP4List = new List<string>();
string[] line1CP4Components;

foreach (var line in splitCP4DataBaseLines)
    tempCP4List.Add(line + Environment.NewLine);

string concattedUnitPart = "";
foreach (var line in tempCP4List)
{
    concattedUnitPart = concattedUnitPart + line;
    line1CP4PartLines++;
}

line1CP4Components = new Regex("\"UNIT\",\"PARTS\"", RegexOptions.Multiline)
                    .Split(concattedUnitPart)
                    .Where(c => !string.IsNullOrEmpty(c)).ToArray();

I am wondering if there is a quicker way to do this. This is just one of the files I am opening, so this is repeated a minimum of 5 times to open and properly load the lists.

The minimum file size being imported right now is 257 KB. The largest file is 1,803 KB. These files will only get larger as time goes on as they are being used to simulate a database and the user will continually add to them.

So my question is: is there a quicker way to do all of the above code?


texts: tic tac toe code in c++ with two players

texts:
My main problems are making draw case and any player can choose a place which is chosen by another player here is the code :
#include <iostream>
using namespace std;

char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
static int turnnumber = 1 ;
bool winner = false, flag = false ;
bool win(){
     if(board[0][0]==board[1][1]&&board[1][1]==board[2][2])
    winner = true ;
    if(board[0][2]==board[1][1]&&board[1][1]==board[2][0])
    winner = true ;
if(board[1][0]==board[1][1]&&board[1][1]==board[1][2])
    winner = true ;
if(board[0][0]==board[0][1]&&board[0][1]==board[0][2])
    winner = true ;
if(board[2][0]==board[2][1]&&board[2][1]==board[2][2])
    winner = true ;
if(board[0][0]==board[1][0]&&board[1][0]==board[2][0])
    winner = true ;
if(board[0][1]==board[1][1]&&board[1][1]==board[2][1])
    winner = true ;
if(board[0][2]==board[1][2]&&board[1][2]==board[2][2])
    winner = true ;

    if(winner==true&&turnnumber==1)
       cout << "player2 won \n\n" ;
    if(winner==true&&turnnumber==2)
       cout << "player1 won \n\n" ;

    return winner;
}

void view()
{
    for (int i = 0; i < 3; i++)
    {
        for (int x = 0; x < 3; x++)
        {
            cout << "[" << board[i][x] << "]  ";
        }
        cout << endl
             << "-------------" << endl;
    }
}

void players()
{

    char player1 = 'X', player2 = 'O';
    int number;
    cout << "\nplayer " << turnnumber << " it's your turn ";
    if(turnnumber==1)
       turnnumber++;
    else if(turnnumber==2)
       turnnumber--;
    char player;
    if(turnnumber==1)
       player=player2;
    if(turnnumber==2)
       player=player1;
    cin >> number ;

    switch(number){

    case 1:
        board[0][0] = player;
        break;
    case 2:
        board[0][1] = player;
        break;
    case 3:
        board[0][2] = player;
        break;
    case 4:
        board[1][0] = player;
        break;
    case 5:
        board[1][1] = player;
        break;
    case 6:
        board[1][2] = player;
        break;
    case 7:
        board[2][0] = player;
        break;
    case 8:
        board[2][1] = player;
        break;
    case 9:
        board[2][2] = player;
        break;
    default:
        cout << "\nwrong number\n";
        players();

    }
    system("cls");
    view();

    if(!win())
        players();
}

int main()
{
    view();
    players();
}


texts:
I've been focusing on my PHP skills lately but have been shifting to JavaScript.  I'm familiar with the bare-bone basics of jQuery.  I'm not as familiar with JavaScript as I'd like to be.  I'm a solo-developer so I'd just like somebody to take a look at this and point out any mistakes or things I could be doing better.

What the code does

Creates an arbitrary number of <script> elements, assigns a type and src attribute to each one and then inserts that <script> element before the </body>.

The code

See Better Code below!

function async_init() {

    var element, type, src;
    var parent = document.getElementsByTagName('body');
    var cdn = new Array;

    cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js';
    cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js';

    for (var i in cdn) {
        element = document.createElement('script');
        type    = document.createAttribute('type');
        src     = document.createAttribute('src');

        type.nodeValue = 'text/javascript';
        src.nodeValue  = cdn[i];

        element.setAttributeNode(type);
        element.setAttributeNode(src);
        document.body.insertBefore(element, parent);
    }

}

<body onload="async_init()">

Right now the code is working, which is great.  But my questions:

Is this the "best" way to do this?  I define best as optimum user experience and efficient code.
Are there any obvious "noobie" flaws in my JavaScript?
Is there anyway I could get the onload attribute out of the body?

I used Mozilla Developer Network as my JavaScript reference.  If there are any other references that are accurate, documented & useful I would love to have more information.

Thanks for checking the code out and your feedback, even if its pointing out how my code sucks!

Better code after critique

function async_init() {
    var element;
    var cdn = new Array;

    cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js';
    cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js';

    for (var i in cdn) {
        element = document.createElement('script');
        element.setAttribute('type', 'text/javascript');
        element.setAttribute('src', cdn[i]);
        document.body.appendChild(element);
    }

}


texts: Connecting to a database and running CRUD operations

texts:
I have a database class that connects to a database and runs CRUD operations. I need a critique of how well this class adheres to SOLID principles. A class to run all database operations seems like 'Single Responsibility' to me. Is there any need for further abstraction, such as an interface of some kind?

<?PHP

class Database
{

  private $pdo='';
  public $dbConn='';

  private $dbName='';
  private $dbHost='';
  private $dbUser='';
  private $dbPass='';

public function __construct($database)
{
  $this->dbName=$database;
}

private function dbConnect()
{
  //place connection in try catch, so errors can be displayed or sent to log
    try
    {
    $this->pdo= new PDO('mysql:dbname='.$this->dbName.';host=xxx.xxx.xx.xxx','abcdef','vwxyz');
    $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $this->dbConn=true;

    return true;

    } catch(PDOException $e){

      return $e;

    }

} //End dbConnect

public function connect(){

    if ($this->dbConnect()) {

         if ($this->dbConn) {

           $myPDO=$this->pdo;

           return $myPDO;
         }

    } else { return false; }

}

function tableExists()
{

   $findTable="SHOW TABLES FROM ".$this->dbName." WHERE tables_in_".$this->dbName." LIKE 'prod%' ";

   $query=$this->pdo->query($findTable);
   $tablesFound=$query->fetch();

   return $tablesFound;

} //END Function tableExists.

public function select($table,$rows='*', $where=null,$order=null,$limit=null)
{

  is_array($rows) ? $rows=implode(',', $rows) : $rows=$rows;

   $stmt='SELECT '.$rows.' FROM '.$table;

  if ( !is_null($where) )
    $stmt .=' WHERE '.$where;

   if (! is_null($order) )
    $stmt .=' ORDER BY '.$order.' DESC ';

  if (! is_null($limit) )
    $stmt .=' Limit '.$limit;

    //if table exists proceed with Query
    $query=$this->pdo->query($stmt);

    $data=$query->fetchAll(PDO::FETCH_ASSOC);

   return $data;

} //End Function Select

public function insert($table,$values,$rows=null)
{
      $ins='INSERT INTO '.$table;

      if ($rows != null) {

        $ins .= ' ('.implode(',', $rows).')';
      }

      for ($i=0; $i<count($values);$i++ )
      {
         $bindingVals[]=':val'.$i;
      }

        $bindVals=implode(',', $bindingVals);
        $ins .=' VALUES ('.$bindVals.') ';

        $params=array_combine($bindingVals, $values);
        $insert=$this->pdo->prepare($ins);

        foreach ($params as $key => &$value) {
          $insert->bindParam($key, $value,PDO::PARAM_STR);
         }

         try {
           $insert->execute();
         } catch (Exception $e) {
           $error=$e->getMessage();

           echo $error.'

' ;
         }

   }//END Function insert

public function setUpdateVals(array $vals)
{
  foreach ($vals as $k => $v)

  {
    $values[]=$k.'='.$this->pdo->quote($v);
  }

  $values=implode(',',$values);

  return $values;
}

public function update($table,$rows,$where=null)
{

  $sql='UPDATE '.$table.' SET '.$rows;
  if ($where != null)
  {
    $sql.=' WHERE '.$where;
  }

  $stmt=$this->pdo->prepare($sql);
  if ($stmt->execute()) {

    return true;
  }

}//END Function update

public function delete($table,$where=null)
{

     if ( is_null($where) )
     {

        if (confirmTableDelete())
        {
          $sql="DELETE $table";
        }

     } else{

      $sql='DELETE FROM '.$table.'WHERE'.$where;
    }

    $stmt=$this->pdo->prepare($sql);
    $stmt->bindParam(':Value',$Value,$Data_Options);
    $stmt->execute();

 }

}


texts:
I was hoping for a bit of advice on cleaning a couple of areas of this code up. In particular, the hex-to-binary section, the checksum is in hex, and the rest is in ASCII. I tried for a good day to do it with tables etc, but in frustration I ended up going with this.

Is there a better way of handling the "Store individual characters in vector" section? I went that way because the message can be of variable size (plus 1 or 2 characters).

Here's an example of the type of message:

!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23

using namespace std;

int main()

{
//Checksum Function

//Get Characters for Checksum
ifstream AisMsg("nmea.txt", ios::in);

    string MsgLine;
    getline(AisMsg, MsgLine, '*');
    MsgLine.erase(0,1);

        string HexVal;
        getline(AisMsg, HexVal);

AisMsg.close();

//Store individual characters in an element of an vector
int i = 0;
int j = ( MsgLine.length() );
vector <int> AsciiValues;
{
    bool done = false;
    while (!done)
    {
        int h ( MsgLine.at (i) );
        i++;
        AsciiValues.push_back(h);

    if ( i == j )
        done = true;
    }
}
//XOR validation
bitset<8> a = (AsciiValues[0]);
bitset<8> b = (AsciiValues[1]);
bitset<8> c = a ^ b;
    int d = 2;
    int e = (AsciiValues.size());

{
    bool done = false;
    while (!done)
    {
        a = (AsciiValues[d]);
        b = c;
        c = a ^ b;
        d++;

    if ( d == e )
        done = true;
    }
}
//Hex Checksum to Binary Conversion (messy, but does the job)
int PosOne = HexVal.at(0);
int PosTwo = HexVal.at(1);

    bitset<4> z = PosOne;
    bitset<4> x = PosTwo;

        ofstream Cheat("Amateur Hour.txt", ios::out | ios::app);
        Cheat << z << x << endl;
        ifstream Cheat1("Amateur Hour.txt", ios::in | ios::binary);

            string Chksm;
            getline(Cheat1,Chksm);

        Cheat.close();
        Cheat1.close();
        remove ("Amateur Hour.txt");

return 0;
}


texts: Return the opposite of two known strings given one

texts:
This is probably silly, but I feel like there should be a much more elegant way to do this simple thing. I have two known strings, whichever one is passed in in the parameter I want to return the opposite. Current code:

def matching_sub(subscription_type)
  if subscription_type == "maths"
    "reading"
  else
    "maths"
  end
end

I came up with:

def matching_sub(subscription_type)
  (%w{reading maths} - [subscription_type]).first
end

and my colleague did:

def matching_sub(subscription_type)
  {"maths" => "reading",  "reading" => "maths"}[subscription_type]
end

Can anyone top that?


texts:
I recently solved the problem below from leetcode:

  Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical).  Find the maximum area of an island in the given 2D array.

This is how I normally write python code. I am thinking this might not be really Pythonic. Please help review the code.

from operator import add

def max_area_of_island(grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """
    rlen = len(grid)
    clen = len(grid[0])

    visited = [[0] * clen for _ in range(rlen)]
    max_island = 0
    dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    def add_dir(cur_loc, d):
        cur_i, cur_j = cur_loc
        new_i, new_j = tuple(map(add, cur_loc, d))
        if new_i >= 0 and new_i < rlen and new_j >= 0 and new_j < clen:
            #print("all good")
            return new_i, new_j
        #print("error")
        return -1, -1

    max_area = 0
    for i in range(rlen):
        for j in range(clen):
            if grid[i][j] == 0 or visited[i][j]:
                continue
            area = 1
            q = [(i,j)]
            visited[i][j] = True
            #print("before qsize", q.qsize())
            while q:
                #print("during qsize", q.qsize())
                cur = q.pop()
                for _,d in enumerate(dirs):
                    new_i, new_j = add_dir(cur, d)
                    if new_i < 0 or visited[new_i][new_j]: continue
                    if new_i >= 0 and grid[new_i][new_j]:
                        new_loc = (new_i, new_j)
                        q.append(new_loc)
                        visited[new_i][new_j] = True
                        area += 1
            max_area = max(area, max_area)

    return max_area


texts: Checking for certain values in a range of numbers


texts:
I am starting to learn python and this has been my first project but I am not entirely happy, I think it could be done better. Could you help me? The strings are in Spanish but I think it does not harm understanding.
    elegir_magnitud = int(input(
"""1 = Temperatura
2 = Longitud
3 = Masa
4 = Volumen
5 = Tiempo
6 = Divisa
Entra número deseado: """))
if elegir_magnitud == 1 :
    unidad_temperatura = int(input(
        """

------------------Elige la unidad de temperatura a ser convertida:---------------
1 = Celsius
2 = Farhengei o como se escriba
3 = Kelvin
Entra número deseado: """))
    cantidad_temperatura = float(input(
        """

Entra la cántidad de esa unidad deseada: """))
#ELEGIR UNIDAD DE TEMPERATURA A CONVERTIR
    unidad_a_convertir = int(input(
        """

--------------------Elige la unidad de temperatura a convertir:-----------------
1 = Celsius
2 = Farhengei o como se escriba
3 = Kelvin
Entra número deseado: """))
    if unidad_temperatura == unidad_a_convertir:
        print("Por qué quieres convertir a la misma unidad?")
    if unidad_temperatura == 1 and unidad_a_convertir == 3:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura - 273),"ºK")
    if unidad_temperatura == 1 and unidad_a_convertir == 2:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura * 9%5 +32),"ºF")
    if unidad_temperatura == 3 and unidad_a_convertir == 1:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura + 273),"ºC")
    if unidad_temperatura == 3 and unidad_a_convertir == 2:
        print("""El resultado de la conversion es: \n""",float((cantidad_temperatura -273) * 9 % 5 + 32),"ºF")
    if unidad_temperatura == 2 and unidad_a_convertir == 3:
        print("""El resultado de la conversion es: \n""",float((cantidad_temperatura - 32) % 9 * 5 - 273),"ºK")
    if unidad_temperatura == 2 and unidad_a_convertir == 1:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura % 9*5 -32),"ºC")


texts:
I want to create lists of the nodes of a binary tree at each depth.
So if the depth is X I would have X lists.
Please see my approach. I think it is correct. Am I right to believe it is correct? Any input is welcome:

public List<List<BinaryNode>> getNodesPerDepth(BinaryNode root){
     if(root == null) {
         throw new IllegalArgumentException();
     }
     List<LinkedList<BinaryNode>> result = new LinkedList<LinkedList<BinaryNode>>();
     result.add(new LinkedList<BinaryNode>());
     getNodesPerDepth(result, root, 0);
     return result;
}

private void getNodesPerDepth(List<LinkedList<BinaryNode>> lists, BinaryNode root , int depth){
      if(root == null){
        return;
      }
      lists.get(depth).add(root);
      if(lists.size() < depth + 1 && (root.left != null || root.right != null)){
           lists.add(new LinkedList<BinaryNode>());
      }
      getNodesPerDepth(lists, root.left, depth + 1);
      getNodesPerDepth(lists, root.right, depth + 1);
}


texts: Function for comparing floating point numbers

texts:
I am trying to make a function for floating point numbers comparison.
The goal is to "evaluate" all operators in single function: >, >=, =, <=, <.
If X>Y, then F>0. If X==Y, F==0. If X<=Y, F<=0 etc (where F is returned value).
I took a piece of code from numeric limits. First thing I changed, in scaling of epsilon, fabs(x+y) to fabs(x)+fabs(y) (because if x=-y, we would be comparing diff to 0; which probably would work fine, but sounds kinda stupid). I've also seen an approach using max(fabs(x), fabs(y)), can we say that one of them is better than the others?
Third parameter, DecadesOfInAccuracy, means how many digits above epsilon() should be ignored.

#include <limits>
#include <iostream>

template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, int>::type
cmp(T x, T y, unsigned int doia = 0)
{
    std::cout << "X: " << x << std::endl;
    std::cout << "Y: " << y << std::endl;
    std::cout << "D: " << fabs(x - y) << std::endl;
    std::cout << "M: " << std::numeric_limits<double>::min() * pow(10, doia+1) << std::endl;
    std::cout << "E: " << std::numeric_limits<T>::epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1) << std::endl;

    if (fabs(x - y) < std::numeric_limits<double>::min() * pow(10, doia + 1))
        return 0;
    bool ltoeq = (x - y) <= std::numeric_limits<T>::epsilon() * (fabs(x)+fabs(y)) * pow(10, doia + 1);
    bool gtoeq = (y - x) <= std::numeric_limits<T>::epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1);
    std::cout << "L: " << ltoeq << std::endl;
    std::cout << "G: " << gtoeq << std::endl;
    return gtoeq - ltoeq;
}

int main()
{
    std::cout.precision(std::numeric_limits<double>::max_digits10 + 5);
    double x = 0.0001000000000000001;
    double y = 0.0001;

    int res = cmp(x, y, 0);
    std::cout << res << std::endl << std::endl;
    if (res > 0)
        std::cout << "X>Y" << std::endl;
    if (res >= 0)
        std::cout << "X>=Y" << std::endl;
    if (res == 0)
        std::cout << "X==Y" << std::endl;
    if (res <= 0)
        std::cout << "X<=Y" << std::endl;
    if (res < 0)
        std::cout << "X<Y" << std::endl;
    return 0;
}

It "correctly" returns equality for pairs like 0.0001000000000000001; 0.0001, 1.0-4*0.2; 0.2, 0; -0, 100000000000.0001; 100000000000.
Is there something I forgot to consider, or maybe something can be simplified? (of course except couts, which will be removed :P).
I am using VS2019 if that matters.


texts:
Please review the code quality of this l33t Speak translator. Improvement suggestions are welcome. Here it is - http://jsbin.com/IHoFuQE/1

(function() {
  "use strict";

  // http://en.wikipedia.org/wiki/Leet
  // http://www.catb.org/jargon/html/crackers.html

  var alphabets = { // common
    "a": "4",
    "b": "8",
    "e": "3",
    "f": "ph",
    "g": "6", // or 9
    "i": "1", // or |
    "o": "0",
    "s": "5",
    "t": "7" // or +
  },
    alphabets2 = { // less common
      "c": "(", // or k or |< or /<
      "d": "<|",
      "h": "|-|",
      "k": "|<", // or /<
      "l": "|", // or 1
      "m": "|\\/|",
      "n": "|\\|",
      "p": "|2",
      "u": "|_|",
      "v": "/", // or \/
      "w": "//", // or \/\/
      "x": "><",
      "y": "'/"
    };

  var words = {
    "am": "m",
    "are": "r",
    "at": "@",
    "thanks": "thx",
    "your": "ur",

    "cool": "kewl",
    "defeated": "pwned",
    "dude": "d00d",
    "fear": "ph33r", // or ph34r
    "fool": "f00",
    "freak": "phreak",
    "hacker": "h4x0r",
    "lamer": "l4m3r",
    "mad": "m4d",
    "newbie": "n00b",
    "own": "pwn",
    "phone": "fone",
    "porn": "pr0n", // or n0rp
    "rocks": "roxxorz",
    "skill": "sk1llz",
    "sucks": "sux0r",
    "the": "t3h",
    "uber": "ub3r", // or |_|83r
    "yay": "w00t",
    "yo": "j0",
    "you": "j00" // or U
  };

  var elite = document.getElementById("elite"),
    leet = document.getElementById("leet"),
    randomcase = document.getElementById("randomcase"),
    adv = document.getElementById("adv"),
    btn = document.getElementById("btn");

  function changeLetters(text) { // change letters
    text = text || elite.value.toLowerCase();
    for (var i = 0; i < text.length; i++) {
      var alphabet = adv.checked ? alphabets[text[i]] || alphabets2[text[i]] : alphabets[text[i]];
      if (alphabet) {
        text = text.replace(text[i], alphabet);
      }
    }
    return text;
  }

  function changeWords() { // change special words and return text
    return changeLetters().replace(
      /\w+/g,
      function(word) {
        return words[word] ? words[word] : word;
      }
    );
  }

  function randomizeCase() { // RANdOMiZE CAsE
    var text = changeWords();
    for (var i = 0; i < text.length; i++) {
      if (Math.random() > 0.5) {
        text = text.replace(text[i], text[i].toUpperCase());
      } // else keep lower case
    }
    return text;
  }

  (function() { // l33t the words object
    for (var word in words) {
      if (words.hasOwnProperty(word)) {
        words[changeLetters(word)] = words[word];
        delete words[word];
      }
    }
  }());

  function tol33t() {
    leet.value = randomcase.checked ? randomizeCase() : changeWords();
  }

  elite.addEventListener("input", tol33t);
  btn.addEventListener("click", tol33t);
}());


texts: Finding vowels, digits, whitespaces and consonants

texts:
I am creating a simple app to find vowels, digits, whitespaces and consonants. the basic idea is to practice multi-threading and writing readable code.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.scene.control.TextField;
import javafx.application.Platform;
import javafx.scene.control.Button;
import java.util.stream.IntStream;
import javafx.fxml.Initializable;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import java.util.Arrays;
import javafx.fxml.FXML;
import java.util.List;
import java.net.URL;

/**
 *
  * @author Aamir khan
 */
public class FXMLDocumentController implements Initializable {

@FXML
TextField inputField;
@FXML
TextField vowelsField;
@FXML
TextField consField;
@FXML
TextField digitField;
@FXML
TextField spaceField;
@FXML
Button check;
@FXML
Button exit;

private List<Runnable> tasks;

@Override
public void initialize(URL url, ResourceBundle rb) {
    tasks = Arrays.asList(
            () -> findAndUpdateVowels(),
            () -> findAndUpdateCons(),
            () -> findAndUpdateDigits(),
            () -> findAndUpdateWhiteSpace()
    );

    exit.setOnAction(e -> System.exit(0));
}

@FXML
void checkBtnHandle(ActionEvent e) {
    ExecutorService thread = Executors.newFixedThreadPool(tasks.size());
    tasks.forEach(thread::submit);
    thread.shutdown();
}

public void findAndUpdateVowels() {
    long numberOfVowels = find(Find.VOWELS);
    updateField(vowelsField, numberOfVowels);
}

void findAndUpdateWhiteSpace() {
    long numberOfWhiteSpaces = find(Find.WHITE_SPACE);
    updateField(spaceField, numberOfWhiteSpaces);
}

void findAndUpdateCons() {
    long numberOfCons = find(Find.CONSONANTS);
    updateField(consField, numberOfCons);
}

void findAndUpdateDigits() {
    long numberOfDigits = find(Find.DIGITS);
    updateField(digitField, numberOfDigits);

}

public boolean isVowel(int codePoint) {
    //checking for lower case because the input will only in lower case
    return (codePoint == 'a')
            || (codePoint == 'e')
            || (codePoint == 'i')
            || (codePoint == 'o')
            || (codePoint == 'u');

}

private void updateField(TextField field, long val) {
    Platform.runLater(() -> field.setText(String.valueOf(val)));
}

private long find(Find whatToFind) {
    final IntStream chars = inputField.getText().toLowerCase().chars();
    long result = 0L;
    switch (whatToFind) {
        case VOWELS:
            result = chars.filter(this::isVowel).count();
            break;
        case CONSONANTS:
            //Note: we are not preventing any special chars such as œ,Ž,Ÿ
            result =  chars.filter(c -> Character.isLetter(c) && !isVowel(c)).count();
            break;
        case DIGITS:
            result = chars.filter(Character::isDigit).count();
            break;
        case WHITE_SPACE:
            result = chars.filter(Character::isWhitespace).count();
            break;
        default:
            result = 0L;
    }
    return result;
}

enum Find {
    VOWELS,
    WHITE_SPACE,
    DIGITS,
    CONSONANTS;
}
}

Is code readable? How can I optimize it?


texts: Improve speed of object-to-html transform in javascript?

texts:
I have a rather large javascript array of objects that I am transforming into an HTML table. Each object in the array looks like:

{
    name:'Document Title',
    url:'/path/to/document.html',
    categories:['Some Category'],
    protocols:['ID Number','Another ID'],
    sites:['Location']
}

It's possible to have multiple categories, protocols, and sites, hence why they are in arrays.

The jQuery I've written to do the transformation is:

var table = $('
'),
    tbody = $('
'),
    thead = $('

Protocol	Report Name	Category	Site

');

$.each(reports,function(i,report) {
    var tr = document.createElement('tr'),
             cellProtocol = document.createElement('td'),
             cellName = document.createElement('td'),
             cellCategory = document.createElement('td'),
             cellSite = document.createElement('td'),
             reportLink = document.createElement('a');

    // If property doesn't exist, set to empty array
    report.protocols = report.protocols || [];
    report.sites = report.sites || [];
    report.categories = report.categories || [];

    reportLink.setAttribute('href',report.url);
    reportLink.appendChild(document.createTextNode(report.name));

    cellProtocol.appendChild(document.createTextNode(report.protocols.join(', ')));
    cellName.appendChild(reportLink);
    cellCategory.appendChild(document.createTextNode(report.categories.join(', ')));
    cellSite.appendChild(document.createTextNode(report.sites.join(', ')));

    tr.appendChild(cellProtocol);
    tr.appendChild(cellName);
    tr.appendChild(cellCategory);
    tr.appendChild(cellSite);

    tbody[0].appendChild(tr);
});

$('#report-table').empty().append(table.append(thead,tbody));

It currently takes about 2 seconds to transform 4200 objects into table rows and display the finished table. In the $.each loop I am using appendChild as I understand it is faster than using innerHTML or $.append.

Are there any improvements here I can make in performance?


texts: Reduce number of operations to get one array value

texts:
I can't wrap my head around that. There seem to be a lot of redundancy, and even if it is not called called more than ten times in the main loop, I still find it hard to swallow that it loops through the whole list at each invocation.

def get_file_info(f, stream, field):

    discoverer = GstPbutils.Discoverer()
    discoverer.connect('discovered', on_discovered)
    info = discoverer.discover_uri(f)

    for vinfo in info.get_video_streams():
        ftype = (vinfo.get_stream_type_nick())
        width = vinfo.get_width()
        height = (format(vinfo.get_height()))
        depth = (format(vinfo.get_depth()))
        framerate = ('Frate: {}'.format(vinfo.get_framerate_num()))
        bitrate = ('Brate: {}'.format(vinfo.get_max_bitrate()))
        par = vinfo.get_par_num()
        fname = vinfo.get_caps().to_string().split(',')[0]

    if stream == 'video':
        if field == 'duration':
            return str(convert_time(info.get_duration(), 'hh:mm:ss'))
        elif field == 'width':
            return str(width)
        elif field == 'height':
            return str(height)
        elif field == 'type':
            return str(ftype)
        elif field == 'depth':
            return str(depth)
        elif field == 'framerate':
            return str(framerate)
        elif field == 'bitrate':
            return str(bitrate)
        elif field == 'par':
            return str(par)
        elif field == 'name':
            return str(par)

I read the lambda documentation, but can't seem to write a proper one, but I would sure like to.


texts:
I have come up with this code to do level order traversal recursively for a binary search tree.

private void printLevelOrder_Recursive(Node root2) {
    Queue<Node> queue = new LinkedList<Node>();
    queue.add(root2);

    Stack<Node> stack = new Stack<Node>();
    stack.add(root2);
    if(stack.isEmpty() == false) {

        Node node = stack.pop();
        System.out.println(node.data);

        stack.addAll(printLevelOrder_Recursive_Children(node.left, node.right));
    }

    while(stack.isEmpty() == false) {
        Node node = stack.pop();
        System.out.println(node.data);
    }
}

private Stack<Node> printLevelOrder_Recursive_Children(Node left, Node right) {
    Stack<Node> stack = new Stack<Node>();
    if (left == null && right == null) {
        return stack;
    }

    Stack<Node> leftChildren = new Stack<Node>();
    Stack<Node> rightChildren = new Stack<Node>();
    if (left != null && (left.left != null || left.right != null)) {
        leftChildren = printLevelOrder_Recursive_Children(left.left, left.right);
    }
    if (right != null && (right.left != null || right.right != null)) {
        rightChildren = printLevelOrder_Recursive_Children(right.left, right.right);
    }

    if (rightChildren.isEmpty() == false) {
        stack.addAll(rightChildren);
    }
    if (leftChildren.isEmpty() == false) {
        stack.addAll(leftChildren);
    }
    if (right != null) {
        stack.add(right);
    }
    if (left != null) {
        stack.add(left);
    }
    return stack;
}

where Node is:

public class Node {
    public int data;
    public Node left;
    public Node right;
}

I looked at various implementations, but I find mine much easier. Could you please chime in with your review and thoughts?


texts: Improving the manipulation of 2D Arrays for an easy challenge on HackerRank with Python 3

texts:
I am practicing some exercises on HackerRank in order to improve my skills on Python3. I am doing the 30 days challenge. There is one challenge involving matrices. I was able to pass the test cases and provide the correct result. However, I think my code could have huge improvements.

I am not really sure about how would be the best way to iterate over matrices to solve the problem asked. That's the challenge:

That's my code:

import sys

matrix_input = sys.stdin.readlines()
#print (matrix_input)

def make_matrix(matrix):

    final_matrix = []

    for line in matrix:

        #remove new_line
        line = line.strip()

        #remove space
        line = line.split(" ")

        #convert string to int
        line = list(map(int,line))

        final_matrix.append(line)

    return (final_matrix)

"""the function is going to receive a hour glass and return the sum of its elements. The easiest way is to treat things as a rectangle and make the elements on the second line, first col and last col, null, like zero"""

def sum_hour_glass_rec(hour_glass_rec):

    hour_glass_rec[1][0]=0

    hour_glass_rec[1][2]=0

    total = 0

    for linha in hour_glass_rec:
        for coluna in linha:
            total = total + coluna

    return total

def make_list_hour_glasses(matrix):

    A = matrix

    col_var= 0
    list_part_hour_glass_iter = []
    list_hour_glasses = []
    k_var_iter = 0

    for k in range(0,4):
        col_var = 0
        for j in range(0,4):
            #print (j,"j")
            for col in range(k_var_iter,k_var_iter+3):
                #print (col,"col")
                #print (A[col][col_var:col_var+3])
                list_part_hour_glass_iter.append(A[col][col_var:col_var+3])
                #print (list_part_hour_glass_iter)
                list_hour_glasses.append(list_part_hour_glass_iter)
            list_part_hour_glass_iter = []
            #print (list_hour_glasses)
            col_var+=1
        k_var_iter +=1

    return list_hour_glasses

matrix_of_recs = (make_list_hour_glasses(make_matrix(matrix_input)))

records = []

for rectangle in matrix_of_recs:
    records.append(sum_hour_glass_rec(rectangle))

maximum_record = max(records)

print(maximum_record)

In order to execute this, I created another file, called d11_input.txt with the input values:

1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36

My command on terminal would just be:

python3 d11.py < d11_input.txt

Points that I suspect could have huge improvements:

1 - I treated the hourglass as a square and then, made two elements A21 and A23 zero. Maybe there is a more elegant way to do that.

2 - I used a three nested loop in order to generate all hour glasses a 6x6 matrix can have. Not good in terms of big O notation. Is there a way better?

3 - As you might see, when generating all possible hour glasses, each one was repeated three times which means I am calculating things that I do not need. Nonetheless, I was not able to fix this and also keep the rest of the code working. Here you see a picture of the "problem" involving repeated data that I am talking about:

I hope I will learn with your comments. Thanks in advance =)


texts: Remove non-printable characters from string in Python 3

texts:
My aim is to print bytes string lines in Python 3, but truncate each line to a maximum width so that it fits the current terminal window.

My first attempt was only print(output[:max_width]), but this did not work because Python counts e.g. tabs \t as one character, but the terminal displays them as multiple characters. Also, it would evaluate carriage-returns etc.

Therefore now I have this snippet of code, line is a bytes string:

output = line.decode(codec, "replace")
if max_width:
    output = "".join(c for c in output if c.isprintable())
    print(output[:max_width])
else:
    print(output)

However, I guess it's pretty slow to refactor each string line this way just to filter out non-printable characters like \t and \r (and whatever characters I might have forgotten).

Please note that codec is specified by the user. It might be "ascii", utf-8, utf-16 or any other valid built-in codec.

Can you please suggest me how to improve this code's performance?


texts:
I have a piece of Clojure code that reverses a string recursively.
It is working but too slow (because I got the problem from Codewars and I cannot validate it before it timeouts).

The algorithm is :

take a string ex. "abc" and reverse it (r "abc") -> "cba"
take the first position and reverse from there "c" + (r "ba") -> "cab"
take the second position and reverse from there "ca" + (r "b") -> "cab"
and so on..

First iteration :

(defn reverse-fun [s]
  (loop [r s p 0]
    (if (= p (count s))
      r
      (let [[b e] (split-at p r)
            e     (reverse e)]
        (recur (apply str (concat b e)) (inc p))))))

However it was too slow. I pass about 31 tests with this one before the timeout. Here is the fastest I have for now :

(defn reverse-fun [s]
  (apply str (loop [r (vec s) p 0]
               (if (= p (count r))
                 r
                 (let [b (subvec r 0 p)
                       e (rseq (subvec r p (count r)))]
                   (recur (into [] (concat b e)) (inc p)))))))

This code passes about 72 tests before there is a timeout.
How can I make this code faster ?


texts: Retrieve rich text from GridFS with Java

texts:
I am writing a storage for articles and I have decided to use GridFS from MongoDB. I have found and tested some code, but I am not sure that it is a best one. Could you advice me how to make it better?

private GridFS gridFs;

public String getPostContent(String name) {
    GridFSDBFile file = gridFs.findOne(name + ".html");
    if (file == null) {
        return "There is no text for this article.";
    }
    return getStringFromInputStream(file.getInputStream());
}

private static String getStringFromInputStream(InputStream is) {
    BufferedReader bufferedReader = null;
    StringBuilder builder = new StringBuilder();

    String line;
    try {
        bufferedReader = new BufferedReader(new InputStreamReader(is));
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(System.getProperty("line.separator")).append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return builder.toString();
}

I will appreciate any suggestions even regarding chosen approach.


texts: How would you improve this object model design to get around Covariance Issues with ObjectModel.Collection?

texts:
Consider the following simple relationship.

Code

[DataContract(Name = "Wheel")]
public class Wheel { }

[DataContract(Name = "OffRoadWheel")]
public class OffRoadWheel : Wheel { }

[DataContract(Name = "RoadVehicle")]
public class RoadVehicle
{
    public Collection<Wheel> Wheels { get; private set; }

    public RoadVehicle()
    {
        Wheels = new Collection<Wheel>();
    }
}

[DataContract(Name = "Truck")]
public class Truck : RoadVehicle
{
    public Collection<OffRoadWheel> OffRoadWheels { get; private set; }

    public Truck()
    {
        OffRoadWheels = new Collection<OffRoadWheel>();
    }
}

The Collections are configured as Read-Only and initiated in the class constructor as per FXCop recommendation CAS2227. http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx

Now I know all the rules about Covariance & Contravariance, and the varying capabilities of using Collections vs. Lists vs. Enumerables (vs. their Interface Equivalents). However the above object model creates a number of competing difficulties.

If you create a truck with 4 Off-Road Wheels, down cast it to a RoadVehicle, and then iterate the Wheels collection... it's empty.

One way around this would be to create a public new Collection<Wheel> Wheels property on the Truck class which on-the-fly casts the contents of the OffRoadWheel collection, but this breaks behaviour if you go to add or remove on that collection.

Another problem is serialization, you can alter the above to store and duplicate the inner Wheels and OffRoadWheels properties, but then you'd end up complete serializing both if you wanted to serialize Truck

Any other suggestions on how to make this more Developer Friendly object model where things happen as you'd expect them to?


texts:
I have various strings that contain codes, e.g. like this:

"file = new JarFile(new File()" + "\nSystem.out.println(file"

but also

"args"

Now I want to find the substring that is in the beginning and in the end of the string. E.g. in the first case the result would be file. In the second example the result has to be args

I now wrote the following method:

public static String findWord(String text) {
        String result = null;
        boolean found = false;
        for (int i = 0; i < text.length(); i++) {
            for (int j = 0; j < text.length(); j++) {
                String first = text.substring(0, i*j);
                String last = text.substring(text.length() - i*j, text.length());
                if (first.equals(last) && first.length() > 0) {
                    result = first;
                    found = true;
                    break;
                }
            }
            if (found) {
                break;
            }
        }
        return result;
    }

This seems to work for the test cases I tested, but I'm not sure if it works for all cases. Additionally, I'm not sure if there isn't a simpler solution. I need two loops and ugly break statements. So how could I improve that?


texts:
With a few experience of python and golang, I tried to make (simple) thread pool executor. Tasks of the executor must be copy-constructible std::function<void()> and the result of tasks are required in the main thread.

My Header and Implementation File:

#include <iostream>
#include <queue>
#include <chrono>
#include <atomic>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <functional>

class PoolExecutor
{
public:
    explicit PoolExecutor(const unsigned int pool_size)
        : stop_(false)
        , working_(0)
    {
        for(unsigned int i = 0; i < pool_size; ++i)
        {
            this->threads_.emplace_back(
                std::thread(std::bind(&PoolExecutor::worker, this)));
        }

    }
    virtual ~PoolExecutor()
    {
        this->stop_ = true;
        for(auto& thread : this->threads_)
        {
            thread.join();
        }
    }

    void submit(std::function<void()> func)
    {
        {
            std::lock_guard<std::mutex> guard(this->mu2_);
            this->work_queue_.push(func);
        }
        this->cv_.notify_all();
    }

    bool finished()
    {
        std::lock_guard<std::mutex> guard(this->mu2_);
        return this->working_ == 0 && this->work_queue_.empty();
    }

    void stop()
    {
        this->stop_ = true;
    }

private:
    std::vector<std::thread> threads_;
    std::shared_timed_mutex mu_;
    std::mutex mu2_;
    std::atomic_bool stop_;
    std::atomic_int working_;
    std::condition_variable_any cv_;
    std::queue<std::function<void()> > work_queue_;

    void worker()
    {
        std::function<void()> func;
        while(!this->stop_)
        {
            using namespace std::literals::chrono_literals;
            std::shared_lock<std::shared_timed_mutex> lock(this->mu_, std::try_to_lock);
            this->cv_.wait_for(lock, 10ms);

            bool accquired = false;
            {
                std::lock_guard<std::mutex> guard(this->mu2_);
                if(!this->work_queue_.empty())
                {
                    func = this->work_queue_.front();
                    this->work_queue_.pop();
                    accquired = true;
                    this->working_++;
                }
            }
            if(accquired)
            {
                func();
                --this->working_;
            }
        }
    }
};

Sample Usage:

int main()
{
    PoolExecutor executor(8);
    std::mutex mu;
    int sum = 0;

    auto func = [&sum, &mu](const int i) {
        std::cout << "work " << i << " try lock\n";
        {
            //simulate long running function
            using namespace std::literals::chrono_literals;
            std::lock_guard<std::mutex> guard(mu);
            std::this_thread::sleep_for(10ms);
            std::cout << "work " << i << " acquire lock\n";
            sum += i;
        }
    };

    for(auto i = 0; i < 100; ++i)
    {
        executor.submit(std::bind(func, i));
    }

    int count = 0;
    while(!executor.finished())
    {
        using namespace std::literals::chrono_literals;
        std::this_thread::sleep_for(200ms);
        std::cout << "sleep count: " << ++count << "\n";
    }

    std::cout << "sum: " << sum << "\n";
    return 0;
}

I've tested with sample code using MSVC 15 (also tested with shared_mutex instead of shared_timed_mutex) and clang 3.8. The result is printed as expected, but I cannot sure what I did it.

Some questions.

Q1. Am I using mutex and lock correctly?

Q2. It is possible to use single mutex in PoolExecutor class?

Q3. Is there any ways to wait executor until finished?


texts:
I have started learning Java recently and I solved the following problem on Hackerrank.

The challenge is to :

  You are given NN sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.

  Suppose we have six sticks of the following lengths:
  5 4 4 2 2 8

  Then, in one cut operation we make a cut of length 2 from each of the six >sticks. For the next cut operation four sticks are left (of non-zero length), >whose lengths are the following:
  3 2 2 6

  The above step is repeated until no sticks are left.

  Given the length of NN sticks, print the number of sticks that are left before each subsequent cut operations.

  Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks).

  Input Format
  The first line contains a single integer NN.
  The next line contains NN integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick.

  Output Format
  For each operation, print the number of sticks that are cut, on separate lines.

Sample Input :

6
5 4 4 2 2 8

Sample Output:

6
4
2
1

I am trying to get better at writing good code for my solutions. Please give me your suggestions.

 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Scanner;

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

    Scanner keyboard = new Scanner(System.in);

    int size = keyboard.nextInt(); // get total number of sticks

    ArrayList<Integer> list = new ArrayList<Integer>(size);
    for(int i=0;i<size;i++)
    {
        int values = keyboard.nextInt();
        list.add(values);
    }
     list.removeAll(Collections.singleton(0));// remove all zeroes if present
     Collections.sort(list); // sort in ascending order
        while(list.size()>0)
        {
            int smallest = list.get(0);  // get the smallest element
            for(int i =0 ;i < list.size();i++)
            {

                list.set(i, list.get(i) - smallest);
            }
            //System.out.println(list);
            System.out.println(list.size());
            list.removeAll(Collections.singleton(0)); // remove the elements which are zero after cutting the sticks
            //System.out.println(list);
        }

   }

  }


texts: Summing the size/count of associations for multiple records

texts:
I'm working on a plain Ruby class within a Rails application.

For the total_leg_count method---is that the best way to go about achieving what I want? I feel like there's potentially a better way.

class AircraftTimeReport

  ...

  def total_leg_count
    count = 0
    active_flights_within_timeframe.includes(:legs).each do |flight|
      count += flight.legs.size
    end
    count
  end

  private

  def active_flights_within_timeframe
    @aircraft.flights.within_timeframe(from_datetime, to_datetime).not_cancelled
  end
end

report = AircraftTimeReport.new(@aircraft)
puts report.total_leg_count

An Aircraft has_many Flights and a Flight belongs_to Aircraft.

A Flight has_many Legs and a Leg belongs_to a Flight.

I've seen other solutions that use Arel or plain SQL but I can't seem to wrap my head around it.

Also, I'm finding it difficult to unit test this method, which is why I'm wondering if there's a better way!


texts:
So, chance, huh? Randomness.

I'm looking into how I can test a class whose sole responsibility is to return weighted random results, that is, where there is a set probability of returning true.

The trouble is, random being what it is, sometimes the result doesn't reflect the initial probability.

Here's my attempt, which passes the specs most of the time.

chance.rb

class Chance

  include Singleton

  def self.percent(amount)
    (rand(100) + 1) <= amount
  end

  # x in y chance of being true
  def self.proportion(x, y)
    rand(y) <= x
  end

end

chance_spec.rb

describe Chance do

  context 'percent' do

    it 'should return true 50% of the time' do
      results = 100.times.collect{ Chance.percent(50) }
      results.select{|x|x}.count.should be_within(10).of(50)
    end

    it 'should return true 75% of the time' do
      results = 100.times.collect{ Chance.percent(75) }
      results.select{|x|x}.count.should be_within(10).of(75)
    end

    it 'should return true 25% of the time' do
      results = 100.times.collect{ Chance.percent(25) }
      results.select{|x|x}.count.should be_within(10).of(25)
    end

    it 'should return true 100% of the time' do
      results = 100.times.collect{ Chance.percent(100) }
      results.select{|x|x}.count.should eq(100)
    end

    it 'should return true 0% of the time' do
      results = 100.times.collect{ Chance.percent(0) }
      results.select{|x|x}.count.should eq(0)
    end

  end

  context 'proportion' do

    it 'should return true 6 in 12 times' do
      results = 12.times.collect{ Chance.proportion(6, 12) }
      results.select{|x|x}.count.should be_within(2).of(6)
    end

    it 'should return true 2 in 6 times' do
      results = 6.times.collect{ Chance.proportion(2, 6) }
      results.select{|x|x}.count.should be_within(1).of(2)
    end

  end

end

Any clues?


texts:
I developed this small code to make my life easier when I work with remote machines over ssh tunnel crossing a bastion host. I would like to publich it so others could benefit/learn from it.

So I would appreciate your opinions for improvement or maybe I overlooked some issues in this approach.

Goal:

I have a postgres VM in a private subnet running on default local host with port 5432. I want to be able to reach this machine from my go code or to let PgAdming GUI reach it from my local machine.

the workflow as following:

create ssh client to Bastion machine
from bastion client create a new client fo the postgres machine
forward the remote port to local listner

Thanks!

sshHelper

package sshHelper

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"

    "golang.org/x/crypto/ssh"
)

var home, err = os.UserHomeDir()

func SignKey(KeyName string) ssh.Signer {

    pathToPrivateKey := filepath.FromSlash(fmt.Sprintf("%s/.ssh/%s", home, KeyName))

    key, err := ioutil.ReadFile(pathToPrivateKey)
    if err != nil {
        panic(err)
    }

    // Create the Signer for this private key.
    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        panic(err)
    }

    return signer

}

func CreateClient(user string, signer ssh.Signer, address string, port string) *ssh.Client {

    config := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.PublicKeys(signer),
        },
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    cleint, err := ssh.Dial("tcp", address+":"+port, config)
    if err != nil {
        panic(err)
    }

    return cleint
}

func ViaBastionConn(cleint *ssh.Client, user string, signer ssh.Signer, address string, port string) *ssh.Client {

    conn, err := cleint.Dial("tcp", address+":"+port)
    if err != nil {
        log.Fatal(err)
    }

    config := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.PublicKeys(signer),
        },
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    ncc, chans, reqs, err := ssh.NewClientConn(conn, address+":"+port, config)
    if err != nil {
        log.Fatal(err)
    }

    newCleint := ssh.NewClient(ncc, chans, reqs)

    return newCleint
}

func localListner(cleintBroker *ssh.Client, localAddress string, remoteAddress string) {
    listener, err := net.Listen("tcp", localAddress)
    if err != nil {
        fmt.Println(err)
    }
    defer listener.Close()

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println(err)
        }

        forward(cleintBroker, conn, remoteAddress)

    }

}

func forward(cleintBroker *ssh.Client, localConn net.Conn, remoteAddress string) {

    remoteConn, err := cleintBroker.Dial("tcp", remoteAddress)
    if err != nil {
        fmt.Printf("Remote dial error: %s\n", err)
        return
    }

    copyConn := func(writer, reader net.Conn) {
        _, err := io.Copy(writer, reader)
        if err != nil {

            fmt.Println("")
            fmt.Printf("io.Copy error: %s", err)
            fmt.Println("")

        }
    }

    go copyConn(localConn, remoteConn)
    go copyConn(remoteConn, localConn)

}

main.go

package main

import (
sshM "lib/sshHelper"
)

const (
    sshPort        = "22"
    postgresUser    = "ubuntu"
    bastionUser    = "ubuntu"
    bastionAddress = "54.xxx.xxx.xxx"
    postgresAddress  = "10.0.x.xxx"
    localAddr = "localhost:5432"
    remoteAddr= "localhost:5432"

)

func main() {

    bastionKey := "bastion_key.pem"
    postgresKey := "postgres_key.pem"

    signerBastion := sshM.SignKey(bastionKey)
    signerPostgres := sshM.SignKey(postgresKey)

    clientBastion := sshM.CreateClient(bastionUser, signerBastion, bastionAddress, sshPort)
    cleintPostgres:= sshM.ViaBastionConn(clientBastion, brokerUser, signerPostgres, postgresAddress, sshPort)

    go localListner(cleintPostgres, localAddr, remoteAddr)

}


texts: Suggested parameter names for utility class function

texts:
During our internal code review process, my following code raised some eyebrows:

public class MySuperUtil {
    public static List<Long> updateAndSubtract(List<Long> first, List<Long> second) {
        List<Long> updated = updatePlaceholdersWithLargestIds(second, first);
        Collection<?> difference = CollectionUtils.subtract(first, updated);
        return castCollectionToListUsingClass(difference, Long.class);
    }

(the castCollectionToListUsingClass is not related to this problem; it is from this SO answer)

The main feedback is the names of parameters: first and second.

My reviewer suggests using names more informative to the caller, e.g. inDB instead of first, inUI instead of second.

My main points (of using first and second) are:

this is a Util class (although probably there will be only one occasion for it to be used)
this is similar to what CollectionUtils.substract() has

I guess my question really is:
what context do we use when naming those two parameters?

do we name them in the context of the callee MySuperUtil (thus
something like first and second, or probably minuend and subtrahend), OR,
do we name them in the context of the caller (thus inDB and inUI)?

Any suggestion is appreciated.


texts: Displaying blog posts from non-SSL site in SSL site

texts:
The Issue

I added SSL to a previously static and non-SSL website because some new features will require it. I'm using rails 4.0.5, ruby 1.9.3, and the site is deployed on heroku (it's at www dot palleylaw com).
The newly SSL site included content from my non-SSL blog (it's at www spblog dot herokuapp com).  I had been grabbing the content via Feedburner, right to the view.  But Feedburner is http only, so was no longer an option. I don't want to add SSL to the blog site and I want the two sites to remain separate.

Correct Solution?

I used Nokogiri to grab the index.xml in a controller and then display the content that I want in the view.  The code below that does this "works" in that I don't get errors in my error console and the lock icon now shows up when you browse to the SSL site.  (I think I understand why, that because it's provided through a controller I'm getting the feed server side, not client side through an external feed).

That said, I'm not a security expert or professional programmer, and am teaching myself all of this stuff as I go.  This is my first foray into SSL (and Nokogiri for that matter) and am learning Ruby (you will see I am not entirely clear on the difference between to_s and to_string, just that the difference matters here and allows the code to work).  So there are a ton of moving parts and I had to learn more than a few new things to do this.

Are there any glaring holes in the code or approach?  Is there a better way to do this (or a resource that I should consider using instead)?

Production.rb

# force access to the app over https
config.force_ssl = true

Controller

def home
# save the blog content to the local variable 'feed''
  feed = Nokogiri::XML(open('http://blog.site.com/index.xml'))
  # grab the content we want and save in instance variables that can be used in the view
  @title =feed.css("title")
  @summary =feed.css("summary")
  @date =feed.css("published")
# define counter for number of post items we want to display in the view
  @counter = [1,2,3,4]
end

View

# some basic markup for the div containing the feed partial

Blog

full posts @ blog.site.com

# using the instance variable that we set in the controller, loop through the  elements 4
# times, displaying with html format
# need to understand difference between to_str and to _s, as well as html_safe — is it necessary? @summary throws no method error with to_s but works with to_string — why?

<% @counter.each do |i| %>  # Loop through selected elements in each post

<%= @title[i].text.to_s.html_safe %> | <%= @date[i].to_s.html_safe %>

<%= @summary[i].to_str.html_safe%>

More . . ./

<% end %>


texts: Inserting text file rows into an Access DB

texts:
I am trying to speed up the process of inserting all of the rows in my text file into an Access DB. I originally switched to this route because of the size of those text files (that I am generating on another step of my process). I have more ROM than RAM. The overall process is working now, but I am falling into the rabbit hole of "optimizing" and can use someone else's opinion.

Limitations and specifications:

I can't load all of the text file into one variable. I can't get more RAM.
My logic needs to accept any text size (Column x Row).
All the data will be inserted to an existing empty Access table.

I will try to minimize the code posted here. Feel free to ask questions if anything important seems to be missing. Here is the logic in question:

Method that contains the code:

Public Sub InsertTextFileRowsIntoAccessDB2(sAccessTableName As String, sDBFilePath As String, CashePath As String)
'...all the code here
End Sub

Logic A: Best I could do

           'Insert each Row from the text file into the access DB

   Do While (Not reader.EndOfStream)
                Try
                    Dim fullRow() = reader.ReadLine.Split(CChar(vbTab))

                    'Create the parameters
                    Dim Prams As String = "@p1"
                    For i = 2 To fullRow.Count
                        Prams = Prams & " ,@p" & i
                    Next

                    Dim insertQuery As String = "INSERT INTO " & sAccessTableName & " VALUES (" & Prams & ");"
                    Dim cmd2 = New OleDbCommand(insertQuery, conn)

                    For index As Integer = 1 To fullRow.Length
                        Dim tempP As String = "@p" & index  'Array starts from zero
                        cmd2.Parameters.AddWithValue(tempP, fullRow(index - 1))
                    Next
                    cmd2.ExecuteNonQuery()

                Catch ex As Exception
                    Dim rex = ex 'TODO: Write the row and the exception somewhere
                End Try
            Loop

Logic 2

                'Insert each Row from the text file into the access DB
            Do While (Not reader.EndOfStream)
                Try
                    Dim fullRow() = reader.ReadLine.Split(CChar(vbTab))

                    'Build the query string to have all the columns
                    Dim query As String = "INSERT INTO " & sAccessTableName & " VALUES (" & "'" & fullRow(0) & "'"
                    For index As Integer = 1 To fullRow.Length - 1

                        If fullRow(index).Equals("") Then    'Check if the column is empty
                            query = query & ", NULL "
                        Else
                            'Check if the string has a quote in it (which causes issues to SQL)
                            query = query & ", '" & fullRow(index).Replace("'", "''") & "'"
                        End If
                    Next
                    query = query & ");"

                    Dim cmd As OleDbCommand = New OleDbCommand(query, conn)
                    cmd.ExecuteNonQuery()

                Catch ex As Exception
                    Dim rex = ex 'TODO: Write the row and the exception somewhere
                End Try
            Loop

How can I improve my inserts?

Questions asked in comments:

  What version of Access is it? Can you post your connection string?

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sDBFilePath

Let me know if this could cause any issues with other machines or how to avoid incompatibility.

  Also, what does the table you are inserting into look like?

It depends on the data (table) I am getting. I am trying to get the column count to be dynamic so the method would work with any table. However, I am making the assumption that the column number in the table will be the same as the column number in the text file that I am reading from.


texts: Generating string primary keys with sequence in SQLAlchemy

texts:
I need improvement on solution to the following problem:

  Generating random string keys in SQA is relatively simple, something
  like:

request_id = Column(String, default=lambda: uuid.uuid4().hex, primary_key=True)

  However, I need to to get request_id have format like
  DIVISION_ABC_REQUEST_223 (this is because PK is also supposed to be
  good for human consumption -- that key will be sent around in emails,
  copied/pasted, etc, but it also should be usable for regular SQA/SQL
  queries as a typical PK), with integer suffixes ideally following a
  normal (ordinal) sequence.

  (the backend DB is Postgres)

I found a solution, if a bit wasteful:

class WorkPackage(Base):
    __tablename__ = 'work_package'
    int_id = Column(Integer, primary_key=True)
    wp_prefix = Column(Unicode, default=u'DIVISION_ABC_REQUEST_', primary_key=True)
    data = Column(Unicode)

    @hybrid_property
    def wp_id(self):
        return self.wp_prefix + str(self.int_id)

    @wp_id.expression
    def wp_id(cls):
        return cls.wp_prefix.concat(cls.int_id)

wp_id.expression uses concat (a ColumnOperator that produces SQL concatenation operator ||).

It works in the sense of automatic PK creation in desired order and for querying by the wp_id attribute.

However, the silly aspect is that obviously there's a single column filled with the same prefix over and over.

The obvious problem here is that wp_prefix is a column for a single reason: so that I could use its concat method.

I would like to change it in such way that the wp_prefix column is unnecessary (e.g. it could be SQL concatenation of a string and int_id column).

I do not know how to construct SQLAlchemy Core expression that would achieve this without using column method.


texts:
What is the best practice to run continually api request, like every 1-10 seconds.

Currently I am doing this which is not a good practice I think, it probably causes some overhead:

    countDownTimer = new CountDownTimer(10000, 2000) {
        @Override
        public void onTick(long millisUntilFinished) {
            apiRequest();
        }
        @Override
        public void onFinish() {
            countDownTimer.start();
        }
    };

 void apiRequest() {

    call = service.getImg();
    call.enqueue(new retrofit2.Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
              // some code...
            } else {
              // some code ...
            }

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toasty.error(LiveBroadcastActivity.this, "Error.", Toast.LENGTH_SHORT, true).show();
        }
    });
}


texts: RUST: How can I optimize this password cracking algorithm?

texts:
I made this project in my free time to try to crack a 4x hashed md5 with a couple of hints but I'm looking for ways I can optimize this algo because it's pretty slow and I know you could probs use threading or some other ways to increase speed.
If you can even point out some minor ways to increase performance I would be eternally grateful.
I was told I could try re-using the memory for the strings but I'm not sure how to do that. I was also told to not generate the wordlist in advance and try  as I go but I dont think the algorithm I used supports that?
Here's the branch to review (more info in the readme): https://github.com/TransmissionsDev/crack_yearn_md5/tree/v1
Here's the main.rs file:
#[cfg(debug_assertions)]
use num_format::{Locale, ToFormattedString};

fn hash_md5(input: String) -> String {
    format!("{:x}", md5::compute(input.into_bytes()))
}

fn main() {
    let goal_hash = "dbba1bfe930d953cabcc03d7b6ab05e";

    let length = 17;

    let alphabet = "bdeilmostu-"
        .split("")
        .map(String::from)
        .filter(|letter| !letter.is_empty())
        .collect::<Vec<String>>();

    let mut words = alphabet.clone();

    for phase in 1..length {
        let mut temp: Vec<String> = Vec::new();

        #[cfg(not(debug_assertions))]
        let loopable_words = words.iter();

        #[cfg(debug_assertions)]
        let loopable_words = words.iter().enumerate();

        for data in loopable_words {
            #[cfg(not(debug_assertions))]
            let word = data;

            #[cfg(debug_assertions)]
            let word = data.1;
            #[cfg(debug_assertions)]
            let index = data.0;

            for letter in alphabet.iter() {
                let new_word = format!("{}{}", word, letter);

                temp.push(new_word);
            }

            #[cfg(debug_assertions)]
            if index != 0 && ((index % 1000000) == 0) {
                println!(
                    "Completed phase {}/{}'s sub-phase {}/{}",
                    phase,
                    length,
                    index.to_formatted_string(&Locale::en),
                    words.len().to_formatted_string(&Locale::en),
                );
            }
        }

        words = temp;
    }

    #[cfg(debug_assertions)]
    let word_list_length = words.len();
    #[cfg(debug_assertions)]
    println!("\n\nLength of word list: {}\n\n", word_list_length);

    #[cfg(not(debug_assertions))]
    let loopable_words = words.iter();

    #[cfg(debug_assertions)]
    let loopable_words = words.iter().enumerate();

    for data in loopable_words {
        #[cfg(not(debug_assertions))]
        let word = data;

        #[cfg(debug_assertions)]
        let word = data.1;
        #[cfg(debug_assertions)]
        let attempts = data.0;

        let merged = format!(
            "{}{}",
            word, "........................................................!1"
        );

        let hash = hash_md5(hash_md5(hash_md5(hash_md5(merged.clone()))));

        #[cfg(debug_assertions)]
        println!(
            "Attempts: {}/{}, Hash: {}, Text: {}",
            attempts, word_list_length, hash, merged
        );

        if hash == goal_hash {
            println!("We found the password: {}", merged);

            return;
        }
    }
}


texts: Counting occurrences of duplicate items in an array

texts:
I have to make a simple program that reads N integers from the user and counts the occurrences of duplicate items. I know that the chosen sorting algorithm has poor performance, but I chose it for its simplicity.

I'm looking for suggestions for the last part, in which I count the duplicates.

#include <stdio.h>

#define N 10

int main(void) {
    int i, values[N];
    puts("Insert the values:");
    for (i = 0; i < N; i++) {
        scanf("%d", &values[i]);
    }

    /* Sorting */
    int j, tmp, minvalue, minindex;
    for (i = 0; i < N; i++) {
        tmp = values[i];
        minvalue = tmp;
        for (j = i + 1; j < N; j++) {
            if (values[j] < minvalue) {
                minvalue = values[j];
                minindex = j;
            }
        }
        values[i] = minvalue;
        values[minindex] = tmp;
    }

    printf("Array is: ");
    for (i = 0; i < N; i++) {
        printf("%d ", values[i]);
    }
    putchar('\n');

    /* Actual counting */
    int dupn = 0, duplicates[N], dupocc[N];
    for (i = 0; i < N; i++) {
        dupocc[i] = 0;
    }
    for (i = 1; i < N; i++) {
        if (values[i] == values[i - 1]) {
            duplicates[dupn] = values[i];
            if (dupocc[dupn] == 0) dupocc[dupn]++;
            dupocc[dupn]++;
        } else if (dupocc[dupn] > 0) dupn++;
    }
    for (i = 0; i < dupn; i++) {
        printf("Duplicate %d occurs %d times\n", duplicates[i], dupocc[i]);
    }
    return 0;
}


texts: Give function get file extension for you

texts:
I have written a function that retrieves the extension from a given file name for you. I would like to make this more efficient and increase it's performance.

<?php
function getExt($filename) {
    //if(!is_file($filename)) return '';
    $n = strlen($filename);
    if($n<2) return '';
    $non_ext = '';
    $ext = '';
    for($i=$n;$i--;$i>=1) {
        $c = $filename[$i];
        if($c==='.') {
            $ext = '.'.$non_ext.$ext;
            $non_ext = '';
        }else
            $non_ext = $c.$non_ext;
    }
    return $ext;
}
$filename = "asdfasdfasd.tar.gz";
$ext = getExt($filename);
var_dump($ext);
?>


texts: Xamarin image download and resizing for Android

texts:
This code addresses performance issues specific to Android running Xamarin / C# when downloading images (BMP/PNG) into a listview. The caller simply specifies the URL to fetch the image from, and the preferred dimensions.

Optimisations I could do, but haven't:

Not sure if I should use the Android or Java namespace
Stage the downloaded byte[] in an intermediate location - not sure if memory exhaustion is possible
Image caching
Convert to an Android Drawable
Abstract the source to be something other than a URL, e.g. the local resources
Make a static "helper" class (not sure how to do this...)

using System;
using System.Threading.Tasks;
using Android.Graphics;
using Android.Content.Res;
using System.Net;

namespace validAndroid
{
    public class ImageUtils
    {
        async Task<BitmapFactory.Options> GetBitmapOptionsOfImageAsync(byte[] imageBytes)
        {
            BitmapFactory.Options options = new BitmapFactory.Options {
                /*Setting the InJustDecodeBounds property to true while decoding avoids memory allocation,
                 * returning null for the bitmap object but setting OutWidth, OutHeight and OutMimeType .
                 * This technique allows you to read the dimensions and type of the image data prior to
                 * construction (and memory allocation) of the bitmap.*/
                InJustDecodeBounds = true
            };

            // The result will be null because InJustDecodeBounds == true.
            Bitmap result = await BitmapFactory.DecodeByteArrayAsync (imageBytes, 0, imageBytes.Length -1, options);

            int imageHeight = options.OutHeight;
            int imageWidth = options.OutWidth;

            System.Diagnostics.Debug.WriteLine (string.Format ("Original Size= {0}x{1}", imageWidth, imageHeight));

            return options;
        }

          static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Raw height and width of image
            float height = options.OutHeight;
            float width = options.OutWidth;
            double inSampleSize = 1D;

            if (height > reqHeight || width > reqWidth)
            {
                int halfHeight = (int)(height / 2);
                int halfWidth = (int)(width / 2);

                // Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway.
                while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return (int)inSampleSize;
        }

        async Task<Android.Graphics.Bitmap> LoadScaledDownBitmapForDisplayAsync(byte[] imageBytes, BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Calculate inSampleSize
            options.InSampleSize = CalculateInSampleSize (options, reqWidth, reqHeight);

            // Decode bitmap with inSampleSize set
            options.InJustDecodeBounds = false;

            return await Android.Graphics.BitmapFactory.DecodeByteArrayAsync (imageBytes,0,imageBytes.Length-1,  options);
        }

        public  async  Task<Bitmap> GetImageForDisplay(string imageURL,int reqWidth, int reqHeight )
        {
            byte[] imageBytes = null;

            using (var webClient = new WebClient())
            {
                imageBytes= webClient.DownloadData(imageURL);
            }

            BitmapFactory.Options options = await GetBitmapOptionsOfImageAsync(imageBytes);
            var bitmapToDisplay = await LoadScaledDownBitmapForDisplayAsync ( imageBytes,options, reqWidth, reqHeight);
            imageBytes = null;
            return bitmapToDisplay;
        }
    }
}


texts:
I have these two functions and I was just wondering if there is any way to shorten the line of code with the many && statements. Shortening of the rest of the code would be cool too, but it's not necessary. I'm trying to learn if there is a better way to accomplish this though.

# Accepts two stroks and determines if they overlap with one another
def overlap? stroke1, stroke2
    min_x = 0
    max_x = 1
    min_y = 2
    max_y = 3

    bounds1 = get_bounds stroke1
    bounds2 = get_bounds stroke2

    return true if (bounds1[max_x] >= bounds2[min_x]) && (bounds1[max_y] >= bounds2[min_y]) && (bounds2[max_x] >= bounds1[min_x]) && (bounds2[max_y] >= bounds1[min_y])

    return false
end

# Returns an array of bounds [x_min, x_max, y_min, y_max] for the stroke
def get_bounds stroke
    # Arrays for storing x and y values for the stroke currently being inspected
    xvals = Array.new
    yvals = Array.new

    stroke.each_slice(3) do |point|
        xvals.push(point[0])
        yvals.push(point[1])
    end

    # A temporary array that stores the min/max x/y for the stroke being inspected
    bounds = Array.new
    bounds << xvals.min << xvals.max << yvals.min << yvals.max

    return bounds
end

I actually did not write this code, but I offered to clean it up and I came upon this and thought that there was probably a better way.


texts:
Have a look at this Mersenne Twister random-number generator function that I've written based on what I found on SO.

As I am a beginner and don't understand half of the stuff below, I would very much appreciate if you guided me a little on my journey to improving this random number generator.

I don't need it to be fast, I just want it to be secure.
I want it to be more or less the most secure way of generating numbers.
All that, because I plan on generating random passwords with it later on.

#include <iostream>
#include <random>

unsigned long long int random_integer(unsigned long long int rand_min, unsigned long long int rand_max)
{

    // initialize = seed the random device
    std::random_device random_device;

    // use Mersenne Twister as random-number generator engine
    std::mt19937 random_number_generator(random_device());

    // number distribution, guaranteed unbiased
    std::uniform_int_distribution<int> number_distribution(rand_min, rand_max);

    return number_distribution(random_number_generator);

}

int main()
{

    for (int i = 1; i <= 10; i++)
    {
        std::cout << random_integer(1, 1000) << std::endl;
    }

    return 0;

}

Notes:

I'm on Linux.
Compiler is g++5.
Standard being C++17.


texts: Select member for comparison in sort or search

texts:
This code is predicated on the notion that when sorting (or using a sorted collection of items, such as with std::lower_bound) you're usually comparing a single field in each object being sorted/searched.

So a typical sort might look something like:

// Sort by age
std::sort(people.begin(), people.end(),
    [](Person const &a, Person const &b) { return a.age < b.age; });

Or:

// sort by height, descending:
std::sort(people.begin(), people.end(),
    [](Person const &a, Person const &b) { return b.height < a.height; });

Although the lambda is cleaner than C++98 code, I'd really rather be able to specify something like by(height, descending). I haven't (yet) figured out a way to (quite) get to that ideal, but I think this gets us quite a bit closer:

#ifndef SORT_MEMBERS_H_
#define SORT_MEMBERS_H_

namespace sort {
    namespace detail {
        template <class FieldType, class RecordType>
        struct Desc {
            FieldType RecordType::*fn;
        public:
            Desc(FieldType RecordType::*fn) : fn(fn) {}

            bool operator()(RecordType const &a, RecordType const &b) {
                return b.*fn < a.*fn;
            }
        };

        template <class FieldType, class RecordType>
        struct Asc {
            FieldType RecordType::*fn;
        public:
            Asc(FieldType RecordType::*fn) : fn(fn) {}

            bool operator()(RecordType const &a, RecordType const &b) {
                return a.*fn < b.*fn;
            }
        };
    }

    template <class FieldType, class RecordType>
    detail::Asc<FieldType, RecordType> ascending(FieldType RecordType::*b) {
        return detail::Asc<FieldType, RecordType>(b);
    }

    template <class FieldType, class RecordType>
    detail::Desc<FieldType, RecordType> descending(FieldType RecordType::*b) {
        return detail::Desc<FieldType, RecordType>(b);
    }
}

#endif

Example usage would be something like this:

#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
#include "sort_members.h"

struct Person
{
    std::string first_name;
    std::string last_name;
    int age;

    friend std::ostream &operator<<(std::ostream &os, Person const &person) {
        return os << person.first_name << " " << person.last_name << ", " << person.age;
    }
};

int main() {
    std::vector<Person> people = {
        { "John", "Rambo", 42 },
        { "Joffrey", "Baratheon", 14 },
        { "Kyle", "Reese", 25 }
    };

    std::sort(people.begin(), people.end(), sort::descending(&Person::age));

    std::cout << "Sorted by age, descending:\n";
    for (const auto& person : people)
        std::cout << person << "\n";

    std::cout << "\nSorted by last name:\n";
    std::sort(people.begin(), people.end(), sort::ascending(&Person::last_name));
    for (const auto& person : people)
        std::cout << person << "\n";
}

I'd welcome any comments--but I'm mostly interested in the part in the header; the file using it is just a demo, not anything very interesting in itself, beyond the fact that it demonstrates how the preceding code is used.


texts:
I'm a beginner at coding and the past days I tried to write the famous "Conway's Game of Life" in Angular.js. Right now I'm done with the code and the game works. But if the size of the playground grid gets too big (e.g. 100x100 cells), my program is kind of slow. I wanted to ask you where I could improve my code to make it run more quickly. It would be great for me to see what I have could done in a better way to learn from it.

The following code creates the grid for the playing field and gives the cells their coordinates and alive status:

$scope.createGrid = function(width,height){ // Spielfeld erzeugen
    $scope.playingField = {
        width:width,
        height:height,
        data:[]
    };
    for( var r = 0 ; r < width; r++){
        $scope.playingField.data.push([]);
        for( var c = 0 ; c < height; c++){
            $scope.playingField.data[r].push({ x:c, y:r, alive:false });
        }
    }
    $(".grid").width("600px");
    $(".grid").height("600px");
};

Changes color and live status of a cell when clicked on it:

$scope.clickCell = function(cell){ // Zellen Status ändern. tot / leben
    cell.alive = !cell.alive;
};
$scope.style = function(value) { // Einen Style zuweisen
    return { "background-color": value };
};

This is the part where I think the program gets slowed down. It checks all the cell neighbours and copies a new grid after it; I would be very curious about other solutions to this problem:

$scope.startRound = function(){ // Runde durchlaufen
    console.time("Benchmark für das kopieren");
    // TODO: Kopieren ist zu langsam, muss anders erfolgen!
    var newData = angular.copy($scope.playingField.data);
    console.timeEnd("Benchmark für das kopieren");
    angular.forEach($scope.playingField.data, function(cells,r){
        angular.forEach(cells, function(cell,c){
            var alive = 0;
            //Nachbarn überprüfen
            for(var i = r-1 ; i<=r+1;++i){
                for(var j = c-1; j<= c+1 ; ++j){
                    if($scope.getCell(j,i).alive){
                        alive++;
                    }
                }
            }

            if(cell.alive){
                alive -=1;
            }

            // Regeln überprüfen
            if(cell.alive == true && (alive < 2 || alive > 3)){
                newData[r][c].alive = false;
            }
            if(cell.alive == true && (alive == 2 || alive == 3)){
                newData[r][c].alive = true;
            }
            if(cell.alive == false && alive == 3){
                newData[r][c].alive = true;
            }
        });
    });

    $scope.playingField.data = newData;
};

Checks if an alive cell is at the edge of the playing field. If yes, then a new neighbour will be set.

 $scope.getCell = function(x,y){ // Nachbarn überprüfen
    // Wenn das Spielfeld verlassen wird, wird der Nachbar neu bestimmt (auf der anderen Seite)
    var h = $scope.playingField.height-1;
    var w = $scope.playingField.width-1;
    return $scope.playingField.data[(y+h) % h][(x+w) %w];
};

Functions to start the game, stop the game and to refresh the grid.

$scope.startGame = function(){ // Spiel starten
    console.log("Game started");
    $scope.stopInterval = $interval($scope.startRound, 10);
};
$scope.stopGame = function(){ // Spiel beenden
    console.log("Game stopped");
    $interval.cancel($scope.stopInterval);
};
$scope.refreshGameField = function(){ //Sspielfeld zurücksetzen
    console.log("Game refreshed");
    $scope.createGrid($scope.playingField.width, $scope.playingField.height);
};


texts: Remove a query string parameter from a URL

texts:
I have a URL in wstring format in C++, e.g.:

http://stackoverflow.com?Country=US&City=Seattle&State=WA

I want to get rid of Country query param from the above string. Country query param can be the first query param or could be the last too.

 wstring ManagementUrl = L"http://stackoverflow.com?Country=US&City=Seattle&State=WA"
    wstring queryParam = L"&Country=US";
    wstring queryParam1 = L"Country=US";

    string::size_type urlLength = ManagementUrl.length();
    string::size_type queryLength = queryParam.length();
    string::size_type queryLength1 = queryParam1.length();

    size_t index = ManagementUrl.find(queryParam);
            if (index != std::wstring::npos)
            {
                wstrLink.erase(index, queryLength);
            }
        size_t index1 = ManagementUrl.find(queryParam1);
            if (index != std::wstring::npos)
            {
                wstrLink.erase(index, queryLength1);
            }

Is there a better way to do this?


texts: Handling many networking exceptions in Ruby

texts:
What would be a prettier/faster way to do handling of multiple errors in Ruby? Here is the code I am working with:

begin
  response = session.get url
rescue Patron::HostResolutionError
  puts "Error resolving remote host."
  exit 1
rescue Patron::PartialFileError
  puts "File size mismatch. (Host reported a file size, but the actual file is of different size)"
  exit 1
rescue Patron::TimeoutError
  puts "Operation timed out."
  exit 1
rescue Patron::TooManyRedirects
  puts "Tried redirecting too many times."
  exit 1
rescue Patron::URLFormatError
  puts "Error with the URL format"
  exit 1
rescue Patron::UnsupportedProtocol
  puts "This URL is using a protocol that we cannot handle."
  exit 1
rescue Patron::ConnectionFailed
  puts "Error connecting to host. Check your internet connection."
  exit 1
end


texts:
I would like some feedback on my solution for the trip programming challenge. Please go through my code understanding that I am interested in interviewing for a dev position at some point and am also interested in competitive programming (I'm just getting started):

'''

@author: Teererai
This code is intended to calculate the minimum that a number of students needs to exchange
 in order to get the ammounts that they spend to within one cent of each other. The idea
 is to calculate the average then round it up and down to the nearest cent. The next step
 is to calculate the cumulative absolute positive and negative difference for each ammount spen
 from the nearest rounded average spend and take the maximum between the cumulative positive and negative difference.
'''
import sys
from sys import stdin
import math
from decimal import Decimal

def main():
    num_students=int(stdin.readline()) #read number of students
    while num_students!=0:
        i=num_students
        total_spending=0
        student_spending=[] # stores amount spend by each student
        pos_difference=0 # Keeps track of cumulative absolute difference between average spend and ammounts higher than the average.
        neg_difference=0 #Keeps track of cumulative negative difference.
        for i in range(i):
            current_spending=float(stdin.readline())
            student_spending.append(current_spending)
            total_spending+=current_spending
        average_spending=total_spending/num_students
        #these following two variables account for the fact that we can never get to the exact average.
        lower_average_spending=math.floor(average_spending*100)/100
        upper_average_spending=math.ceil(average_spending*100)/100
        #As the challenge specifies, we are not aiming to get the ammount spend to the exact average but rather to either the nearest cent above and below it.
        for element in student_spending:
            if element>average_spending:
                pos_difference=pos_difference+element-upper_average_spending
            else:
                neg_difference=neg_difference+lower_average_spending-element
        amount_exchanged=Decimal(max(neg_difference,pos_difference))
        amount_exchanged=round(amount_exchanged,2)
        print("$",amount_exchanged,sep="")
        num_students=int(stdin.readline())

    return
main()
sys.exit(0)

p.s. the code works perfectly and has been accepted by the uva online judge. I am simply looking for advice.


texts:
I wrote a quick function to create a set of radio buttons, three per table row. I would like some feedback about how I can shorten this bit of code using algebraic functions, or different jQuery functionality.

var arr = [ "earth", "mars", "jupiter", "saturn", "venus", "argus", "pluto", "janus", "canary", "orange", "butter pineapple", "eventual bliss"];

var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };

var start = ""; end = "";
var count = 0;
$("#radio_container").append("
");
    $.each(arr, function(i, val) {

        if(count == 3)
        {
            start = "
";
            end = "
"
            count= 0;
        }

        $("#radio_container").append(start);
        $("#radio_container").append("<input name='finalcategory' type='radio' value='"+val+"'></input>	"+val+"	");
        $("#radio_container").append(end);
        count++;
        start = "";
        end = "";

    });
$("#radio_container").append("
");